├── .github ├── dependabot.yml └── workflows │ └── build-publish.yaml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── browser.ts ├── constants │ ├── atoms.ts │ ├── costs.ts │ ├── keywords.ts │ └── printable.ts ├── index.d.ts ├── index.ts ├── types │ ├── BetterSet.ts │ ├── NodePath.ts │ ├── ParserError.ts │ ├── Position.ts │ ├── Program.ts │ └── Token.ts └── utils │ ├── compare.ts │ ├── compile.ts │ ├── environment.ts │ ├── helpers.ts │ ├── instructions.ts │ ├── ir.ts │ ├── macros.ts │ ├── match.ts │ ├── mod.ts │ ├── operators.ts │ ├── optimize.ts │ └── parser.ts ├── test ├── compile.ts ├── deserialize.ts ├── run.ts └── serialize.ts └── tsconfig.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # This file is managed by the repo-content-updater project. Manual changes here will result in a PR to bring back 2 | # inline with the upstream template, unless you remove the dependabot managed file property from the repo 3 | 4 | version: 2 5 | updates: 6 | - package-ecosystem: "gomod" 7 | directory: / 8 | schedule: 9 | interval: "weekly" 10 | day: "tuesday" 11 | open-pull-requests-limit: 10 12 | rebase-strategy: auto 13 | labels: 14 | - dependencies 15 | - go 16 | - "Changed" 17 | reviewers: ["cmmarslender", "Starttoaster"] 18 | groups: 19 | global: 20 | patterns: 21 | - "*" 22 | 23 | - package-ecosystem: "pip" 24 | directory: / 25 | schedule: 26 | interval: "weekly" 27 | day: "tuesday" 28 | open-pull-requests-limit: 10 29 | rebase-strategy: auto 30 | labels: 31 | - dependencies 32 | - python 33 | - "Changed" 34 | reviewers: ["emlowe", "altendky"] 35 | 36 | - package-ecosystem: "github-actions" 37 | directories: ["/", ".github/actions/*"] 38 | schedule: 39 | interval: "weekly" 40 | day: "tuesday" 41 | open-pull-requests-limit: 10 42 | rebase-strategy: auto 43 | labels: 44 | - dependencies 45 | - github_actions 46 | - "Changed" 47 | reviewers: ["cmmarslender", "Starttoaster", "pmaslana"] 48 | 49 | - package-ecosystem: "npm" 50 | directory: / 51 | schedule: 52 | interval: "weekly" 53 | day: "tuesday" 54 | open-pull-requests-limit: 10 55 | rebase-strategy: auto 56 | labels: 57 | - dependencies 58 | - javascript 59 | - "Changed" 60 | reviewers: ["cmmarslender", "ChiaMineJP"] 61 | 62 | - package-ecosystem: cargo 63 | directory: / 64 | schedule: 65 | interval: "weekly" 66 | day: "tuesday" 67 | open-pull-requests-limit: 10 68 | rebase-strategy: auto 69 | labels: 70 | - dependencies 71 | - rust 72 | - "Changed" 73 | 74 | - package-ecosystem: swift 75 | directory: / 76 | schedule: 77 | interval: "weekly" 78 | day: "tuesday" 79 | open-pull-requests-limit: 10 80 | rebase-strategy: auto 81 | -------------------------------------------------------------------------------- /.github/workflows/build-publish.yaml: -------------------------------------------------------------------------------- 1 | name: 📦🚀 Build & Publish 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: 7 | - main 8 | release: 9 | types: [published] 10 | pull_request: 11 | branches: 12 | - '**' 13 | 14 | concurrency: 15 | group: ${{ github.ref }}-${{ github.workflow }}-${{ github.event_name }} 16 | cancel-in-progress: true 17 | 18 | jobs: 19 | build: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Checkout Code 23 | uses: actions/checkout@v4 24 | env: 25 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | 27 | - name: Set Common Job Env 28 | uses: Chia-Network/actions/setjobenv@main 29 | 30 | - uses: actions/setup-node@v4 31 | with: 32 | node-version: 18 33 | 34 | - name: Update Version 35 | if: env.RELEASE == 'true' 36 | run: | 37 | jq --arg VER "$RELEASE_TAG" '.version=$VER' package.json > temp.json && mv temp.json package.json 38 | 39 | - name: Install 40 | run: npm install 41 | 42 | - name: Run Tests 43 | run: npm run test 44 | 45 | - name: Build Library 46 | run: npm run build 47 | 48 | - name: Upload Bundle to Artifacts 49 | uses: actions/upload-artifact@v4 50 | with: 51 | name: dist 52 | path: dist/ 53 | 54 | - name: Publish to NPM 55 | if: env.FULL_RELEASE == 'true' 56 | env: 57 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 58 | run: | 59 | echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc 60 | npm publish --access public 61 | 62 | - name: Upload to Release 63 | if: env.RELEASE == 'true' 64 | env: 65 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 66 | run: | 67 | gh release upload \ 68 | $RELEASE_TAG \ 69 | dist/bundle.js 70 | 71 | - name: Cleanup 72 | if: always() 73 | run: rm ${{ github.workspace }}/js_build/js-bindings/.npmrc || true 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | .DS_Store 4 | yarn-error.log 5 | .parcel-cache/ -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "singleQuote": true 4 | } 5 | -------------------------------------------------------------------------------- /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 2025 Chia Network Inc. 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 | # CLVM 2 | 3 | [![npm package](https://nodei.co/npm/clvm-lib.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/clvm-lib) 4 | 5 | A browser friendly implementation of CLVM in TypeScript, based off of [the Chia Network implementation written in Python](https://github.com/Chia-Network/clvm). 6 | 7 | ## Introduction 8 | 9 | [Chialisp](https://chialisp.com) is an on-chain smart coin programming language developed by the [Chia Network](https://chia.net). It is compiled and then executed by the Chialisp Virtual Machine, or CLVM for short. 10 | 11 | This particular implementation is written with TypeScript, and is not bindings to native code. This allows it to be used in the browser as well. However, if you prefer native bindings, you should check out [this library](https://github.com/Chia-Network/clvm_rs) instead. 12 | 13 | ## Usage 14 | 15 | You can learn more about how this language works [here](https://chialisp.com). This is a implementation and should work as expected, but in any case that it differs, please open an issue. 16 | 17 | By design, the functions and methods exposed by this library are synchronous and everything is exported for ease of use. 18 | 19 | Since it is written in TypeScript, there are built-in typings for IntelliSense. The following documentation is non-exhaustive, but should be enough for most uses. 20 | 21 | ## Documentation 22 | 23 | - [Program](#program) 24 | 25 | ## Value 26 | 27 | Either `Cons` or `Uint8Array`. 28 | 29 | ## Cons 30 | 31 | A tuple of `Program` and `Program`. 32 | 33 | ## Program 34 | 35 | This represents a program or value in Chialisp or compiled clvm. It is the main class of the library, allowing you to manipulate programs and convert between various forms. 36 | 37 | ### static true 38 | 39 | - A program representing the value `1`. 40 | 41 | ### static false 42 | 43 | - A program representing the value `()`. 44 | 45 | ### atom 46 | 47 | - The `Uint8Array` value of the program. 48 | 49 | ### cons 50 | 51 | - The `Cons` pair of the program. 52 | 53 | ### first 54 | 55 | - The first `Program` value of `cons`. 56 | 57 | ### rest 58 | 59 | - The rest `Program` value of `cons`. 60 | 61 | ### isAtom 62 | 63 | - A `boolean` for if it's an atom. 64 | 65 | ### isCons 66 | 67 | - A `boolean` for if it's a cons pair. 68 | 69 | ### isNull 70 | 71 | - A `boolean` for if it's null. 72 | 73 | ### static cons(first, rest) 74 | 75 | - `first` is a `Program`. 76 | - `rest` is a `Program`. 77 | - Returns a `Program` that is a cons pair between them. 78 | 79 | ### static fromBytes(bytes) 80 | 81 | - `bytes` is a `Uint8Array`. 82 | - Returns a `Program`. 83 | 84 | ### static fromHex(hex) 85 | 86 | - `hex` is a hex `string`. 87 | - Returns a `Program`. 88 | 89 | ### static fromBool(value) 90 | 91 | - `value` is a `boolean`. 92 | - Returns a `Program`. 93 | 94 | ### static fromInt(value) 95 | 96 | - `value` is a `number`. 97 | - Returns a `Program`. 98 | 99 | ### static fromBigint(value) 100 | 101 | - `value` is a `bigint`. 102 | - Returns a `Program`. 103 | 104 | ### static fromText(text) 105 | 106 | - `text` is a `string`. 107 | - Returns a `Program`. 108 | 109 | ### static fromSource(source) 110 | 111 | - `source` is a `string`. 112 | - Returns a `Program`. 113 | 114 | ### static fromList(programs) 115 | 116 | - `programs` is an `Array`. 117 | - Returns a `Program`. 118 | 119 | ### static deserialize(bytes) 120 | 121 | - `bytes` is a `Uint8Array`. 122 | - Returns a `Program`. 123 | 124 | ### constructor(value) 125 | 126 | - `value` is a `Value`. 127 | 128 | ### positionSuffix 129 | 130 | - A `string` containing the line and column suffix, if there is one. 131 | 132 | ### at(position) 133 | 134 | - `position` is a `Position`. 135 | - Returns `this`. 136 | 137 | ### curry(args) 138 | 139 | - `args` is an `Array`. 140 | - Returns a `Program` containing the current one with each argument applied to it in reverse, precommitting them in the final solution. 141 | 142 | ### uncurry() 143 | 144 | - Returns a `[Program, Array]` containing the mod and curried in arguments. 145 | 146 | ### hash() 147 | 148 | - Returns a `Uint8Array` of the tree hash of the program. Hashed with `1` for atoms, and `2` for cons pairs. 149 | 150 | ### hashHex() 151 | 152 | - Returns a hex `string` representation of the tree hash. 153 | 154 | ### define(program) 155 | 156 | - Returns a `Program` containing the current one wrapped in a mod if there isn't already, and with a definition inserted. 157 | 158 | ### defineAll(programs) 159 | 160 | - `programs` is an `Array`. 161 | - Returns a `Program` containing the current one and each definition. 162 | 163 | ### compile(options?) 164 | 165 | - `options` is a partial `CompileOptions`, defaulting to `strict = false`, `operators = base`, and `includeFilePaths = {}`. 166 | - Returns a `ProgramOutput` that is the result of compiling the program. Should be identical to the `run` CLI tool. 167 | 168 | ### run(environment, options?) 169 | 170 | - `environment` is a `Program`. 171 | - `options` is a partial `RunOptions`, defaulting to `strict = false` and `operators = base`. 172 | - Returns a `ProgramOutput` that is the result of running the program. Should be identical to the `brun` CLI tool. 173 | 174 | ### toBytes() 175 | 176 | - Returns a `Uint8Array` representation. 177 | 178 | ### toHex() 179 | 180 | - Returns a hex `string` representation. 181 | 182 | ### toBool() 183 | 184 | - Returns a `boolean` representation. 185 | 186 | ### toInt() 187 | 188 | - Returns a `number` representation. 189 | 190 | ### toBigInt() 191 | 192 | - Returns a `bigint` representation. 193 | 194 | ### toText() 195 | 196 | - Returns a `string` representation. 197 | 198 | ### toSource(showKeywords?) 199 | 200 | - `showKeywords` is a `boolean`, by default `true`. 201 | - Returns a `string` source code representation, like it would be if it were an output from `run` or `brun`. 202 | 203 | ### toList(strict?) 204 | 205 | - `strict` is a `boolean`, by default `false`. 206 | - Returns an `Array` representation. If it's strict, it must be a proper list. 207 | 208 | ### serialize() 209 | 210 | - Returns a `Uint8Array` serialized form of the program. 211 | 212 | ### serializeHex() 213 | 214 | - Returns a hex `string` representation of the serialized form of the program. 215 | 216 | ### equals(value) 217 | 218 | - `value` is a `Program`. 219 | - Returns a `boolean` for if the values are exactly equal. 220 | 221 | ### toString() 222 | 223 | - Returns a `string` source code representation, like it would be if it were an output from `run` or `brun`. 224 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "clvm-lib", 3 | "author": "rigidity", 4 | "version": "1.0.0", 5 | "description": "A browser friendly implementation of clvm.", 6 | "repository": "https://github.com/Chia-Network/node-clvm-lib.git", 7 | "license": "Apache-2.0", 8 | "main": "dist/src/index.js", 9 | "source": "src/index.ts", 10 | "types": "dist/src/index.d.ts", 11 | "bundle": "dist/bundle.js", 12 | "scripts": { 13 | "build": "parcel build", 14 | "watch": "parcel watch", 15 | "test": "parcel build --target test && mocha './dist/test/**/*.js' --require source-map-support/register --recursive --timeout 0" 16 | }, 17 | "files": [ 18 | "dist/src" 19 | ], 20 | "targets": { 21 | "main": { 22 | "distDir": "dist/src", 23 | "context": "node" 24 | }, 25 | "test": { 26 | "source": [ 27 | "test/compile.ts", 28 | "test/deserialize.ts", 29 | "test/run.ts", 30 | "test/serialize.ts" 31 | ], 32 | "distDir": "dist/test", 33 | "context": "node" 34 | }, 35 | "bundle": { 36 | "source": "src/browser.ts", 37 | "context": "browser" 38 | } 39 | }, 40 | "devDependencies": { 41 | "@parcel/packager-ts": "^2.12.0", 42 | "@parcel/transformer-typescript-types": "^2.12.0", 43 | "@types/chai": "^4.3.16", 44 | "@types/mocha": "^10.0.7", 45 | "mocha": "^10.4.0", 46 | "parcel": "^2.12.0", 47 | "source-map-support": "^0.5.21", 48 | "typescript": "^5.4.5" 49 | }, 50 | "dependencies": { 51 | "chai": "^4.4.1", 52 | "chia-bls": "^1.0.2" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/browser.ts: -------------------------------------------------------------------------------- 1 | import * as CLVM from './index'; 2 | 3 | declare global { 4 | interface Window { 5 | CLVM: typeof CLVM; 6 | } 7 | } 8 | 9 | window.CLVM = CLVM; 10 | -------------------------------------------------------------------------------- /src/constants/atoms.ts: -------------------------------------------------------------------------------- 1 | import { encodeBigInt } from 'chia-bls'; 2 | import { keywords } from './keywords'; 3 | 4 | export const quoteAtom = encodeBigInt(keywords['q']); 5 | export const applyAtom = encodeBigInt(keywords['a']); 6 | export const firstAtom = encodeBigInt(keywords['f']); 7 | export const restAtom = encodeBigInt(keywords['r']); 8 | export const consAtom = encodeBigInt(keywords['c']); 9 | export const raiseAtom = encodeBigInt(keywords['x']); 10 | -------------------------------------------------------------------------------- /src/constants/costs.ts: -------------------------------------------------------------------------------- 1 | export const costs = { 2 | if: 33n, 3 | cons: 50n, 4 | first: 30n, 5 | rest: 30n, 6 | listp: 19n, 7 | mallocPerByte: 10n, 8 | arithBase: 99n, 9 | arithPerByte: 3n, 10 | arithPerArg: 320n, 11 | logBase: 100n, 12 | logPerByte: 3n, 13 | logPerArg: 264n, 14 | grsBase: 117n, 15 | grsPerByte: 1n, 16 | eqBase: 117n, 17 | eqPerByte: 1n, 18 | grBase: 498n, 19 | grPerByte: 2n, 20 | divmodBase: 1116n, 21 | divmodPerByte: 6n, 22 | divBase: 988n, 23 | divPerByte: 4n, 24 | sha256Base: 87n, 25 | sha256PerByte: 2n, 26 | sha256PerArg: 134n, 27 | pointAddBase: 101094n, 28 | pointAddPerArg: 1343980n, 29 | pubkeyBase: 1325730n, 30 | pubkeyPerByte: 38n, 31 | mulBase: 92n, 32 | mulPerOp: 885n, 33 | mulLinearPerByte: 6n, 34 | mulSquarePerByteDivider: 128n, 35 | strlenBase: 173n, 36 | strlenPerByte: 1n, 37 | pathLookupBase: 40n, 38 | pathLookupPerLeg: 4n, 39 | pathLookupPerZeroByte: 4n, 40 | concatBase: 142n, 41 | concatPerByte: 3n, 42 | concatPerArg: 135n, 43 | boolBase: 200n, 44 | boolPerArg: 300n, 45 | ashiftBase: 596n, 46 | ashiftPerByte: 3n, 47 | lshiftBase: 277n, 48 | lshiftPerByte: 3n, 49 | lognotBase: 331n, 50 | lognotPerByte: 3n, 51 | apply: 90n, 52 | quote: 20n, 53 | }; 54 | -------------------------------------------------------------------------------- /src/constants/keywords.ts: -------------------------------------------------------------------------------- 1 | export const keywords = { 2 | q: 0x01n, 3 | a: 0x02n, 4 | i: 0x03n, 5 | c: 0x04n, 6 | f: 0x05n, 7 | r: 0x06n, 8 | l: 0x07n, 9 | x: 0x08n, 10 | '=': 0x09n, 11 | '>s': 0x0an, 12 | sha256: 0x0bn, 13 | substr: 0x0cn, 14 | strlen: 0x0dn, 15 | concat: 0x0en, 16 | '+': 0x10n, 17 | '-': 0x11n, 18 | '*': 0x12n, 19 | '/': 0x13n, 20 | divmod: 0x14n, 21 | '>': 0x15n, 22 | ash: 0x16n, 23 | lsh: 0x17n, 24 | logand: 0x18n, 25 | logior: 0x19n, 26 | logxor: 0x1an, 27 | lognot: 0x1bn, 28 | point_add: 0x1dn, 29 | pubkey_for_exp: 0x1en, 30 | not: 0x20n, 31 | any: 0x21n, 32 | all: 0x22n, 33 | '.': 0x23n, 34 | softfork: 0x24n, 35 | }; 36 | -------------------------------------------------------------------------------- /src/constants/printable.ts: -------------------------------------------------------------------------------- 1 | export const printable = `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_\`{|}~ 2 | 3 | `; 4 | -------------------------------------------------------------------------------- /src/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.clib' { 2 | const content: string; 3 | export default content; 4 | } 5 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './types/ParserError'; 2 | export { 3 | Program, 4 | type CompileOptions, 5 | type Cons, 6 | type ProgramOutput, 7 | type RunOptions, 8 | type Value, 9 | } from './types/Program'; 10 | -------------------------------------------------------------------------------- /src/types/BetterSet.ts: -------------------------------------------------------------------------------- 1 | export class BetterSet extends Set { 2 | public isSuperset(set: Set): boolean { 3 | for (const item of set) if (!this.has(item)) return false; 4 | return true; 5 | } 6 | 7 | public isSubset(set: Set): boolean { 8 | for (const item of this) if (!set.has(item)) return false; 9 | return true; 10 | } 11 | 12 | public isSupersetProper(set: Set): boolean { 13 | return this.isSuperset(set) && !this.isSubset(set); 14 | } 15 | 16 | public isSubsetProper(set: Set): boolean { 17 | return this.isSubset(set) && !this.isSuperset(set); 18 | } 19 | 20 | public equals(set: Set): boolean { 21 | return this.isSubset(set) && this.isSuperset(set); 22 | } 23 | 24 | public union(set: Set): BetterSet { 25 | const union = new BetterSet(this); 26 | for (const item of set) union.add(item); 27 | return union; 28 | } 29 | 30 | public intersection(set: Set): BetterSet { 31 | const intersection = new BetterSet(); 32 | for (const item of set) if (this.has(item)) intersection.add(item); 33 | return intersection; 34 | } 35 | 36 | public symmetricDifference(set: Set): BetterSet { 37 | const difference = new BetterSet(this); 38 | for (const item of set) 39 | if (difference.has(item)) difference.delete(item); 40 | else difference.add(item); 41 | return difference; 42 | } 43 | 44 | public difference(set: Set): BetterSet { 45 | const difference = new BetterSet(this); 46 | for (const item of set) difference.delete(item); 47 | return difference; 48 | } 49 | 50 | public update(set: Set): this { 51 | for (const item of set) this.add(item); 52 | return this; 53 | } 54 | 55 | public differenceUpdate(set: Set): this { 56 | for (const item of set) this.delete(item); 57 | return this; 58 | } 59 | 60 | public symmetricDifferenceUpdate(set: Set): this { 61 | for (const item of set) 62 | if (this.has(item)) this.delete(item); 63 | else this.add(item); 64 | return this; 65 | } 66 | 67 | public intersectionUpdate(set: Set): this { 68 | for (const item of this) if (!set.has(item)) this.delete(item); 69 | return this; 70 | } 71 | 72 | public sort(sorter?: (a: T, b: T) => number): BetterSet { 73 | return new BetterSet([...this].sort(sorter)); 74 | } 75 | 76 | public map( 77 | mapper: (value: T, index: number, array: BetterSet) => U 78 | ): BetterSet { 79 | const result = new BetterSet(); 80 | let index = 0; 81 | for (const item of this) result.add(mapper(item, index++, this)); 82 | return result; 83 | } 84 | 85 | public filter( 86 | predicate: (value: T, index: number, array: BetterSet) => unknown 87 | ): BetterSet { 88 | const result = new BetterSet(); 89 | let index = 0; 90 | for (const item of this) 91 | if (predicate(item, index++, this)) result.add(item); 92 | return result; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/types/NodePath.ts: -------------------------------------------------------------------------------- 1 | import { bigIntBitLength, bigIntToBytes, bytesToBigInt } from 'chia-bls'; 2 | 3 | export function composePaths(left: bigint, right: bigint): bigint { 4 | let mask = 1n; 5 | let tempPath = left; 6 | while (tempPath > 1n) { 7 | right <<= 1n; 8 | mask <<= 1n; 9 | tempPath >>= 1n; 10 | } 11 | mask -= 1n; 12 | return right | (left & mask); 13 | } 14 | 15 | export class NodePath { 16 | public static top: NodePath = new NodePath(); 17 | public static left: NodePath = NodePath.top.first(); 18 | public static right: NodePath = NodePath.top.rest(); 19 | 20 | private index: bigint; 21 | 22 | constructor(index: bigint = 1n) { 23 | if (index < 0n) { 24 | const byteCount = (bigIntBitLength(index) + 7) >> 3; 25 | const blob = bigIntToBytes(index, byteCount, 'big', true); 26 | index = bytesToBigInt(Uint8Array.from([0, ...blob]), 'big', false); 27 | } 28 | this.index = index; 29 | } 30 | 31 | public asPath(): Uint8Array { 32 | const byteCount = (bigIntBitLength(this.index) + 7) >> 3; 33 | return bigIntToBytes(this.index, byteCount, 'big'); 34 | } 35 | 36 | public add(other: NodePath): NodePath { 37 | return new NodePath(composePaths(this.index, other.index)); 38 | } 39 | 40 | public first(): NodePath { 41 | return new NodePath(this.index * 2n); 42 | } 43 | 44 | public rest(): NodePath { 45 | return new NodePath(this.index * 2n + 1n); 46 | } 47 | 48 | public toString(): string { 49 | return `NodePath: ${this.index}`; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/types/ParserError.ts: -------------------------------------------------------------------------------- 1 | export class ParserError extends Error { 2 | constructor(message: string) { 3 | super(message); 4 | Object.setPrototypeOf(this, ParserError.prototype); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/types/Position.ts: -------------------------------------------------------------------------------- 1 | export class Position { 2 | public line: number; 3 | public column: number; 4 | 5 | constructor(source: string, index: number) { 6 | source = source.replaceAll('\r\n', '\n'); 7 | let line = 1; 8 | let column = 1; 9 | for (let i = 0; i < index; i++) { 10 | if (source[i] === '\n') { 11 | line++; 12 | column = 1; 13 | } else { 14 | column++; 15 | } 16 | } 17 | this.line = line; 18 | this.column = column; 19 | } 20 | 21 | public toString(): string { 22 | return `${this.line}:${this.column}`; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/types/Program.ts: -------------------------------------------------------------------------------- 1 | import { 2 | bytesEqual, 3 | concatBytes, 4 | decodeBigInt, 5 | decodeInt, 6 | encodeBigInt, 7 | encodeInt, 8 | fromHex, 9 | hash256, 10 | JacobianPoint, 11 | PrivateKey, 12 | toHex, 13 | } from 'chia-bls'; 14 | import { keywords } from '../constants/keywords'; 15 | import { printable } from '../constants/printable'; 16 | import { makeDoCom } from '../utils/compile'; 17 | import { instructions } from '../utils/instructions'; 18 | import { deserialize } from '../utils/ir'; 19 | import { match } from '../utils/match'; 20 | import { makeDefaultOperators, Operators } from '../utils/operators'; 21 | import { makeDoOpt } from '../utils/optimize'; 22 | import { tokenizeExpr, tokenStream } from '../utils/parser'; 23 | import { ParserError } from './ParserError'; 24 | import { Position } from './Position'; 25 | 26 | export interface ProgramOutput { 27 | value: Program; 28 | cost: bigint; 29 | } 30 | 31 | export interface RunOptions { 32 | maxCost?: bigint; 33 | operators: Operators; 34 | strict: boolean; 35 | } 36 | 37 | export interface CompileOptions extends RunOptions { 38 | includeFilePaths: Record>; 39 | } 40 | 41 | export type Cons = [Program, Program]; 42 | export type Value = Cons | Uint8Array; 43 | 44 | export type Instruction = ( 45 | instructions: Instruction[], 46 | stack: Program[], 47 | options: RunOptions 48 | ) => bigint; 49 | 50 | export class Program { 51 | public static cost = 11000000000; 52 | public static true = Program.fromBytes(Uint8Array.from([1])); 53 | public static false = Program.fromBytes(Uint8Array.from([])); 54 | public static nil = Program.false; 55 | 56 | public readonly value: Value; 57 | public position?: Position; 58 | 59 | public get atom(): Uint8Array { 60 | if (!this.isAtom) 61 | throw new Error(`Expected atom${this.positionSuffix}.`); 62 | return this.value as Uint8Array; 63 | } 64 | 65 | public get cons(): Cons { 66 | if (!this.isCons) 67 | throw new Error(`Expected cons${this.positionSuffix}.`); 68 | return this.value as Cons; 69 | } 70 | 71 | public get first(): Program { 72 | return this.cons[0]; 73 | } 74 | 75 | public get rest(): Program { 76 | return this.cons[1]; 77 | } 78 | 79 | public get isAtom() { 80 | return this.value instanceof Uint8Array; 81 | } 82 | 83 | public get isCons() { 84 | return Array.isArray(this.value); 85 | } 86 | 87 | public get isNull(): boolean { 88 | return this.isAtom && this.value.length === 0; 89 | } 90 | 91 | public static cons(first: Program, rest: Program): Program { 92 | return new Program([first, rest]); 93 | } 94 | 95 | public static fromBytes(bytes: Uint8Array): Program { 96 | return new Program(bytes); 97 | } 98 | 99 | public static fromJacobianPoint(jacobianPoint: JacobianPoint): Program { 100 | return new Program(jacobianPoint.toBytes()); 101 | } 102 | 103 | public static fromPrivateKey(privateKey: PrivateKey): Program { 104 | return new Program(privateKey.toBytes()); 105 | } 106 | 107 | public static fromHex(hex: string): Program { 108 | return new Program(fromHex(hex)); 109 | } 110 | 111 | public static fromBool(value: boolean): Program { 112 | return value ? Program.true : Program.false; 113 | } 114 | 115 | public static fromInt(value: number): Program { 116 | return new Program(encodeInt(value)); 117 | } 118 | 119 | public static fromBigInt(value: bigint): Program { 120 | return new Program(encodeBigInt(value)); 121 | } 122 | 123 | public static fromText(text: string): Program { 124 | return new Program(new TextEncoder().encode(text)); 125 | } 126 | 127 | public static fromSource(source: string): Program { 128 | const stream = tokenStream(source); 129 | const tokens = [...stream]; 130 | if (tokens.length) return tokenizeExpr(source, tokens); 131 | else throw new ParserError('Unexpected end of source.'); 132 | } 133 | 134 | public static fromList(programs: Program[]): Program { 135 | let result = Program.nil; 136 | for (const program of programs.reverse()) 137 | result = Program.cons(program, result); 138 | return result; 139 | } 140 | 141 | public static deserialize(bytes: Uint8Array): Program { 142 | const program = [...bytes]; 143 | if (!program.length) throw new ParserError('Unexpected end of source.'); 144 | return deserialize(program); 145 | } 146 | 147 | public static deserializeHex(hex: string): Program { 148 | return Program.deserialize(fromHex(hex)); 149 | } 150 | 151 | constructor(value: Value) { 152 | this.value = value; 153 | } 154 | 155 | public get positionSuffix(): string { 156 | return this.position ? ` at ${this.position}` : ''; 157 | } 158 | 159 | public at(position: Position): this { 160 | this.position = position; 161 | return this; 162 | } 163 | 164 | public curry(args: Program[]): Program { 165 | return Program.fromSource( 166 | '(a (q #a 4 (c 2 (c 5 (c 7 0)))) (c (q (c (q . 2) (c (c (q . 1) 5) (c (a 6 (c 2 (c 11 (q 1)))) 0))) #a (i 5 (q 4 (q . 4) (c (c (q . 1) 9) (c (a 6 (c 2 (c 13 (c 11 0)))) 0))) (q . 11)) 1) 1))' 167 | ).run(Program.cons(this, Program.fromList(args))).value; 168 | } 169 | 170 | public uncurry(): [Program, Program[]] | null { 171 | const uncurryPatternFunction = Program.fromSource( 172 | '(a (q . (: . function)) (: . core))' 173 | ); 174 | const uncurryPatternCore = Program.fromSource( 175 | '(c (q . (: . parm)) (: . core))' 176 | ); 177 | 178 | let result = match(uncurryPatternFunction, this); 179 | if (!result) return null; 180 | 181 | const fn = result.function; 182 | let core = result.core; 183 | 184 | const args: Array = []; 185 | 186 | while (true) { 187 | result = match(uncurryPatternCore, core); 188 | if (!result) break; 189 | 190 | args.push(result.parm); 191 | core = result.core; 192 | } 193 | 194 | if (core.isAtom && core.toBigInt() === 1n) return [fn, args]; 195 | return null; 196 | } 197 | 198 | public hash(): Uint8Array { 199 | return this.isAtom 200 | ? hash256(concatBytes(Uint8Array.from([1]), this.atom)) 201 | : hash256( 202 | concatBytes( 203 | Uint8Array.from([2]), 204 | this.first.hash(), 205 | this.rest.hash() 206 | ) 207 | ); 208 | } 209 | 210 | public hashHex(): string { 211 | return toHex(this.hash()); 212 | } 213 | 214 | public define(program: Program): Program { 215 | let result: Program = this; 216 | if (this.isAtom || this.first.isCons || this.first.toText() !== 'mod') 217 | result = Program.fromList([ 218 | Program.fromText('mod'), 219 | Program.nil, 220 | this, 221 | ]); 222 | const items = result.toList(); 223 | items.splice(2, 0, program); 224 | return Program.fromList(items); 225 | } 226 | 227 | public defineAll(programs: Program[]): Program { 228 | let result: Program = this; 229 | for (const program of programs.reverse()) 230 | result = result.define(program); 231 | return result; 232 | } 233 | 234 | public compile(options: Partial = {}): ProgramOutput { 235 | const fullOptions: CompileOptions = { 236 | strict: false, 237 | operators: makeDefaultOperators(), 238 | includeFilePaths: {}, 239 | ...options, 240 | }; 241 | if (fullOptions.strict) 242 | fullOptions.operators.unknown = (_operator, args) => { 243 | throw new Error( 244 | `Unimplemented operator${args.positionSuffix}.` 245 | ); 246 | }; 247 | function doFullPathForName(args: Program): ProgramOutput { 248 | const fileName = args.first.toText(); 249 | for (const [path, files] of Object.entries( 250 | fullOptions.includeFilePaths 251 | )) { 252 | if (fileName in files) 253 | return { 254 | value: Program.fromText(`${path}/${fileName}`), 255 | cost: 1n, 256 | }; 257 | } 258 | throw new Error(`Can't open ${fileName}${args.positionSuffix}.`); 259 | } 260 | function doRead(args: Program): ProgramOutput { 261 | const fileName = args.first.toText(); 262 | let source: string | null = null; 263 | for (const [path, files] of Object.entries( 264 | fullOptions.includeFilePaths 265 | )) { 266 | for (const [file, content] of Object.entries(files)) { 267 | if (fileName === `${path}/${file}`) source = content; 268 | } 269 | } 270 | if (source === null) 271 | throw new Error( 272 | `Can't open ${fileName}${args.positionSuffix}.` 273 | ); 274 | return { value: Program.fromSource(source), cost: 1n }; 275 | } 276 | // Not functional, due to browser support. May reimplement later. 277 | function doWrite(_args: Program): ProgramOutput { 278 | return { value: Program.nil, cost: 1n }; 279 | } 280 | 281 | function runProgram(program: Program, args: Program): ProgramOutput { 282 | return program.run(args, fullOptions); 283 | } 284 | const bindings = { 285 | com: makeDoCom(runProgram), 286 | opt: makeDoOpt(runProgram), 287 | _full_path_for_name: doFullPathForName, 288 | _read: doRead, 289 | _write: doWrite, 290 | }; 291 | Object.assign(fullOptions.operators.operators, bindings); 292 | return runProgram( 293 | Program.fromSource('(a (opt (com 2)) 3)'), 294 | Program.fromList([this]) 295 | ); 296 | } 297 | 298 | public run( 299 | environment: Program, 300 | options: Partial = {} 301 | ): ProgramOutput { 302 | const fullOptions: RunOptions = { 303 | strict: false, 304 | operators: makeDefaultOperators(), 305 | ...options, 306 | }; 307 | if (fullOptions.strict) 308 | fullOptions.operators.unknown = (_operator, args) => { 309 | throw new Error( 310 | `Unimplemented operator${args.positionSuffix}.` 311 | ); 312 | }; 313 | const instructionStack: Array = [instructions.eval]; 314 | const stack: Array = [Program.cons(this, environment)]; 315 | let cost = 0n; 316 | while (instructionStack.length) { 317 | const instruction = instructionStack.pop()!; 318 | cost += instruction(instructionStack, stack, fullOptions); 319 | if (fullOptions.maxCost !== undefined && cost > fullOptions.maxCost) 320 | throw new Error( 321 | `Exceeded cost of ${fullOptions.maxCost}${ 322 | stack[stack.length - 1].positionSuffix 323 | }.` 324 | ); 325 | } 326 | return { 327 | value: stack[stack.length - 1], 328 | cost, 329 | }; 330 | } 331 | 332 | public toBytes(): Uint8Array { 333 | if (this.isCons) 334 | throw new Error( 335 | `Cannot convert ${this.toString()} to hex${ 336 | this.positionSuffix 337 | }.` 338 | ); 339 | return this.atom; 340 | } 341 | 342 | public toJacobianPoint(): JacobianPoint { 343 | if (this.isCons || (this.atom.length !== 48 && this.atom.length !== 96)) 344 | throw new Error( 345 | `Cannot convert ${this.toString()} to JacobianPoint${ 346 | this.positionSuffix 347 | }.` 348 | ); 349 | return this.atom.length === 48 350 | ? JacobianPoint.fromBytesG1(this.atom) 351 | : JacobianPoint.fromBytesG2(this.atom); 352 | } 353 | 354 | public toPrivateKey(): PrivateKey { 355 | if (this.isCons) 356 | throw new Error( 357 | `Cannot convert ${this.toString()} to private key${ 358 | this.positionSuffix 359 | }.` 360 | ); 361 | return PrivateKey.fromBytes(this.atom); 362 | } 363 | 364 | public toHex(): string { 365 | if (this.isCons) 366 | throw new Error( 367 | `Cannot convert ${this.toString()} to hex${ 368 | this.positionSuffix 369 | }.` 370 | ); 371 | return toHex(this.atom); 372 | } 373 | 374 | public toBool(): boolean { 375 | if (this.isCons) 376 | throw new Error( 377 | `Cannot convert ${this.toString()} to bool${ 378 | this.positionSuffix 379 | }.` 380 | ); 381 | return !this.isNull; 382 | } 383 | 384 | public toInt(): number { 385 | if (this.isCons) 386 | throw new Error( 387 | `Cannot convert ${this.toString()} to int${ 388 | this.positionSuffix 389 | }.` 390 | ); 391 | return decodeInt(this.atom); 392 | } 393 | 394 | public toBigInt(): bigint { 395 | if (this.isCons) 396 | throw new Error( 397 | `Cannot convert ${this.toString()} to bigint${ 398 | this.positionSuffix 399 | }.` 400 | ); 401 | return decodeBigInt(this.atom); 402 | } 403 | 404 | public toText(): string { 405 | if (this.isCons) 406 | throw new Error( 407 | `Cannot convert ${this.toString()} to text${ 408 | this.positionSuffix 409 | }.` 410 | ); 411 | return new TextDecoder().decode(this.atom); 412 | } 413 | 414 | public toSource(showKeywords: boolean = true): string { 415 | if (this.isAtom) { 416 | if (this.isNull) return '()'; 417 | else if (this.value.length > 2) { 418 | try { 419 | const string = this.toText(); 420 | for (let i = 0; i < string.length; i++) { 421 | if (!printable.includes(string[i])) 422 | return `0x${this.toHex()}`; 423 | } 424 | if (string.includes('"') && string.includes("'")) 425 | return `0x${this.toHex()}`; 426 | const quote = string.includes('"') ? "'" : '"'; 427 | return quote + string + quote; 428 | } catch { 429 | return `0x${this.toHex()}`; 430 | } 431 | } else if (bytesEqual(encodeInt(decodeInt(this.atom)), this.atom)) 432 | return decodeInt(this.atom).toString(); 433 | else return `0x${this.toHex()}`; 434 | } else { 435 | let result = '('; 436 | if (showKeywords && this.first.isAtom) { 437 | const value = this.first.toBigInt(); 438 | const keyword = Object.keys(keywords).find( 439 | (keyword) => 440 | keywords[keyword as keyof typeof keywords] === value 441 | ); 442 | result += keyword ? keyword : this.first.toSource(showKeywords); 443 | } else result += this.first.toSource(showKeywords); 444 | let current = this.cons[1]; 445 | while (current.isCons) { 446 | result += ` ${current.first.toSource(showKeywords)}`; 447 | current = current.cons[1]; 448 | } 449 | result += 450 | (current.isNull ? '' : ` . ${current.toSource(showKeywords)}`) + 451 | ')'; 452 | return result; 453 | } 454 | } 455 | 456 | public toList(strict: boolean = false): Program[] { 457 | const result: Array = []; 458 | let current: Program = this; 459 | while (current.isCons) { 460 | const item = current.first; 461 | result.push(item); 462 | current = current.rest; 463 | } 464 | if (!current.isNull && strict) 465 | throw new Error(`Expected strict list${this.positionSuffix}.`); 466 | return result; 467 | } 468 | 469 | public serialize(): Uint8Array { 470 | if (this.isAtom) { 471 | if (this.isNull) return Uint8Array.from([0x80]); 472 | else if (this.atom.length === 1 && this.atom[0] <= 0x7f) 473 | return this.atom; 474 | else { 475 | const size = this.atom.length; 476 | const result: Array = []; 477 | if (size < 0x40) result.push(0x80 | size); 478 | else if (size < 0x2000) { 479 | result.push(0xc0 | (size >> 8)); 480 | result.push((size >> 0) & 0xff); 481 | } else if (size < 0x100000) { 482 | result.push(0xe0 | (size >> 16)); 483 | result.push((size >> 8) & 0xff); 484 | result.push((size >> 0) & 0xff); 485 | } else if (size < 0x8000000) { 486 | result.push(0xf0 | (size >> 24)); 487 | result.push((size >> 16) & 0xff); 488 | result.push((size >> 8) & 0xff); 489 | result.push((size >> 0) & 0xff); 490 | } else if (size < 0x400000000) { 491 | result.push(0xf8 | (size >> 32)); 492 | result.push((size >> 24) & 0xff); 493 | result.push((size >> 16) & 0xff); 494 | result.push((size >> 8) & 0xff); 495 | result.push((size >> 0) & 0xff); 496 | } else 497 | throw new RangeError( 498 | `Cannot serialize ${this.toString()} as it is 17,179,869,184 or more bytes in size${ 499 | this.positionSuffix 500 | }.` 501 | ); 502 | for (const byte of this.atom) result.push(byte); 503 | return Uint8Array.from(result); 504 | } 505 | } else { 506 | const result = [0xff]; 507 | for (const byte of this.first.serialize()) result.push(byte); 508 | for (const byte of this.rest.serialize()) result.push(byte); 509 | return Uint8Array.from(result); 510 | } 511 | } 512 | 513 | public serializeHex(): string { 514 | return toHex(this.serialize()); 515 | } 516 | 517 | public equals(value: Program): boolean { 518 | return ( 519 | this.isAtom === value.isAtom && 520 | (this.isAtom 521 | ? bytesEqual(this.atom, value.atom) 522 | : this.first.equals(value.first) && 523 | this.rest.equals(value.rest)) 524 | ); 525 | } 526 | 527 | public toString(): string { 528 | return this.toSource(); 529 | } 530 | } 531 | -------------------------------------------------------------------------------- /src/types/Token.ts: -------------------------------------------------------------------------------- 1 | export interface Token { 2 | text: string; 3 | index: number; 4 | } 5 | -------------------------------------------------------------------------------- /src/utils/compare.ts: -------------------------------------------------------------------------------- 1 | export function compareStrings(a: string, b: string): number { 2 | return a < b ? -1 : a > b ? 1 : 0; 3 | } 4 | -------------------------------------------------------------------------------- /src/utils/compile.ts: -------------------------------------------------------------------------------- 1 | import { bytesEqual, encodeBigInt, toHex } from 'chia-bls'; 2 | import { applyAtom, consAtom, quoteAtom } from '../constants/atoms'; 3 | import { keywords } from '../constants/keywords'; 4 | import { BetterSet } from '../types/BetterSet'; 5 | import { NodePath } from '../types/NodePath'; 6 | import { Program, ProgramOutput } from '../types/Program'; 7 | import { brunAsProgram, Eval, evalAsProgram, quoteAsProgram } from './helpers'; 8 | import { defaultMacroLookup } from './macros'; 9 | import { compileMod } from './mod'; 10 | import { Operator } from './operators'; 11 | 12 | const passThroughOperators = new BetterSet([ 13 | ...Object.values(keywords).map((value) => toHex(encodeBigInt(value))), 14 | toHex(new TextEncoder().encode('com')), 15 | toHex(new TextEncoder().encode('opt')), 16 | ]); 17 | 18 | export function compileQq( 19 | args: Program, 20 | macroLookup: Program, 21 | symbolTable: Program, 22 | runProgram: Eval, 23 | level: number = 1 24 | ): Program { 25 | function com(program: Program): Program { 26 | return doComProgram(program, macroLookup, symbolTable, runProgram); 27 | } 28 | 29 | const program = args.first; 30 | if (!program.isCons) { 31 | return quoteAsProgram(program); 32 | } 33 | if (!program.first.isCons) { 34 | const op = program.first.toText(); 35 | if (op === 'qq') { 36 | const expression = compileQq( 37 | program.rest, 38 | macroLookup, 39 | symbolTable, 40 | runProgram, 41 | level + 1 42 | ); 43 | return com( 44 | Program.fromList([ 45 | Program.fromBytes(consAtom), 46 | Program.fromText(op), 47 | Program.fromList([ 48 | Program.fromBytes(consAtom), 49 | expression, 50 | quoteAsProgram(Program.nil), 51 | ]), 52 | ]) 53 | ); 54 | } else if (op === 'unquote') { 55 | if (level === 1) { 56 | return com(program.rest.first); 57 | } 58 | const expression = compileQq( 59 | program.rest, 60 | macroLookup, 61 | symbolTable, 62 | runProgram, 63 | level - 1 64 | ); 65 | return com( 66 | Program.fromList([ 67 | Program.fromBytes(consAtom), 68 | Program.fromText(op), 69 | Program.fromList([ 70 | Program.fromBytes(consAtom), 71 | expression, 72 | quoteAsProgram(Program.nil), 73 | ]), 74 | ]) 75 | ); 76 | } 77 | } 78 | const first = com( 79 | Program.fromList([Program.fromText('qq'), program.first]) 80 | ); 81 | const rest = com(Program.fromList([Program.fromText('qq'), program.rest])); 82 | return Program.fromList([Program.fromBytes(consAtom), first, rest]); 83 | } 84 | 85 | export function compileMacros( 86 | _args: Program, 87 | macroLookup: Program, 88 | _symbolTable: Program, 89 | _runProgram: Eval 90 | ): Program { 91 | return quoteAsProgram(macroLookup); 92 | } 93 | 94 | export function compileSymbols( 95 | _args: Program, 96 | _macroLookup: Program, 97 | symbolTable: Program, 98 | _runProgram: Eval 99 | ): Program { 100 | return quoteAsProgram(symbolTable); 101 | } 102 | 103 | export const compileBindings = { 104 | qq: compileQq, 105 | macros: compileMacros, 106 | symbols: compileSymbols, 107 | lambda: compileMod, 108 | mod: compileMod, 109 | }; 110 | 111 | export function lowerQuote( 112 | program: Program, 113 | _macroLookup?: Program, 114 | _symbolTable?: Program, 115 | _runProgram?: Eval 116 | ): Program { 117 | if (program.isAtom) { 118 | return program; 119 | } else if (program.first.isAtom && program.first.toText() === 'quote') { 120 | if (!program.rest.rest.isNull) 121 | throw new Error( 122 | `Compilation error while compiling ${program}. Quote takes exactly one argument${program.positionSuffix}.` 123 | ); 124 | return quoteAsProgram(lowerQuote(program.rest.first)); 125 | } else 126 | return Program.cons( 127 | lowerQuote(program.first), 128 | lowerQuote(program.rest) 129 | ); 130 | } 131 | 132 | export function doComProgram( 133 | program: Program, 134 | macroLookup: Program, 135 | symbolTable: Program, 136 | runProgram: Eval 137 | ): Program { 138 | program = lowerQuote(program, macroLookup, symbolTable, runProgram); 139 | if (!program.isCons) { 140 | const atom = program.toText(); 141 | if (atom === '@') { 142 | return Program.fromBytes(NodePath.top.asPath()); 143 | } 144 | for (const pair of symbolTable.toList()) { 145 | const symbol = pair.first; 146 | const value = pair.rest.first; 147 | if (symbol.isAtom && symbol.toText() === atom) { 148 | return value; 149 | } 150 | } 151 | return quoteAsProgram(program); 152 | } 153 | const operator = program.first; 154 | if (operator.isCons) { 155 | const inner = evalAsProgram( 156 | Program.fromList([ 157 | Program.fromText('com'), 158 | quoteAsProgram(operator), 159 | quoteAsProgram(macroLookup), 160 | quoteAsProgram(symbolTable), 161 | ]), 162 | Program.fromBytes(NodePath.top.asPath()) 163 | ); 164 | return Program.fromList([inner]); 165 | } 166 | const atom = operator.toText(); 167 | for (const macroPair of macroLookup.toList()) { 168 | if (macroPair.first.isAtom && macroPair.first.toText() === atom) { 169 | const macroCode = macroPair.rest.first; 170 | const postProgram = brunAsProgram(macroCode, program.rest); 171 | const result = evalAsProgram( 172 | Program.fromList([ 173 | Program.fromText('com'), 174 | postProgram, 175 | quoteAsProgram(macroLookup), 176 | quoteAsProgram(symbolTable), 177 | ]), 178 | Program.fromBytes(NodePath.top.asPath()) 179 | ); 180 | return result; 181 | } 182 | } 183 | if (atom in compileBindings) { 184 | const compiler = compileBindings[atom as keyof typeof compileBindings]; 185 | const postProgram = compiler( 186 | program.rest, 187 | macroLookup, 188 | symbolTable, 189 | runProgram 190 | ); 191 | return evalAsProgram( 192 | quoteAsProgram(postProgram), 193 | Program.fromBytes(NodePath.top.asPath()) 194 | ); 195 | } 196 | if (bytesEqual(operator.atom, quoteAtom)) { 197 | return program; 198 | } 199 | const compiledArgs = program.rest 200 | .toList() 201 | .map((item) => 202 | doComProgram(item, macroLookup, symbolTable, runProgram) 203 | ); 204 | let result = Program.fromList([operator, ...compiledArgs]); 205 | if ( 206 | passThroughOperators.has(toHex(new TextEncoder().encode(atom))) || 207 | atom.startsWith('_') 208 | ) { 209 | return result; 210 | } 211 | for (const item of symbolTable.toList()) { 212 | const [symbol, value] = item.toList(); 213 | if (!symbol.isAtom) continue; 214 | const symbolText = symbol.toText(); 215 | if (symbolText === '*') { 216 | return result; 217 | } else if (symbolText === atom) { 218 | const newArgs = evalAsProgram( 219 | Program.fromList([ 220 | Program.fromText('opt'), 221 | Program.fromList([ 222 | Program.fromText('com'), 223 | quoteAsProgram( 224 | Program.fromList([ 225 | Program.fromText('list'), 226 | ...program.rest.toList(), 227 | ]) 228 | ), 229 | quoteAsProgram(macroLookup), 230 | quoteAsProgram(symbolTable), 231 | ]), 232 | ]), 233 | Program.fromBytes(NodePath.top.asPath()) 234 | ); 235 | return Program.fromList([ 236 | Program.fromBytes(applyAtom), 237 | value, 238 | Program.fromList([ 239 | Program.fromBytes(consAtom), 240 | Program.fromBytes(NodePath.left.asPath()), 241 | newArgs, 242 | ]), 243 | ]); 244 | } 245 | } 246 | throw new Error( 247 | `Can't compile unknown operator ${program}${program.positionSuffix}.` 248 | ); 249 | } 250 | 251 | export function makeDoCom(runProgram: Eval): Operator { 252 | return (sexp: Program): ProgramOutput => { 253 | const prog = sexp.first; 254 | let symbolTable = Program.nil; 255 | let macroLookup: Program; 256 | if (!sexp.rest.isNull) { 257 | macroLookup = sexp.rest.first; 258 | if (!sexp.rest.rest.isNull) symbolTable = sexp.rest.rest.first; 259 | } else { 260 | macroLookup = defaultMacroLookup(runProgram); 261 | } 262 | return { 263 | value: doComProgram(prog, macroLookup, symbolTable, runProgram), 264 | cost: 1n, 265 | }; 266 | }; 267 | } 268 | -------------------------------------------------------------------------------- /src/utils/environment.ts: -------------------------------------------------------------------------------- 1 | import { costs } from '../constants/costs'; 2 | import { Program, ProgramOutput } from '../types/Program'; 3 | 4 | export function msbMask(byte: number): number { 5 | byte |= byte >> 1; 6 | byte |= byte >> 2; 7 | byte |= byte >> 4; 8 | return (byte + 1) >> 1; 9 | } 10 | 11 | export function traversePath( 12 | value: Program, 13 | environment: Program 14 | ): ProgramOutput { 15 | let cost = costs.pathLookupBase + costs.pathLookupPerLeg; 16 | if (value.isNull) return { value: Program.nil, cost }; 17 | let endByteCursor = 0; 18 | const atom = value.atom; 19 | while (endByteCursor < atom.length && atom[endByteCursor] === 0) 20 | endByteCursor++; 21 | cost += BigInt(endByteCursor) * costs.pathLookupPerZeroByte; 22 | if (endByteCursor === atom.length) return { value: Program.nil, cost }; 23 | const endBitMask = msbMask(atom[endByteCursor]); 24 | let byteCursor = atom.length - 1; 25 | let bitMask = 0x01; 26 | while (byteCursor > endByteCursor || bitMask < endBitMask) { 27 | if (environment.isAtom) 28 | throw new Error( 29 | `Cannot traverse into ${environment}${environment.positionSuffix}.` 30 | ); 31 | if ((atom[byteCursor] & bitMask) !== 0) environment = environment.rest; 32 | else environment = environment.first; 33 | cost += costs.pathLookupPerLeg; 34 | bitMask <<= 1; 35 | if (bitMask === 0x100) { 36 | byteCursor--; 37 | bitMask = 0x01; 38 | } 39 | } 40 | return { value: environment, cost }; 41 | } 42 | -------------------------------------------------------------------------------- /src/utils/helpers.ts: -------------------------------------------------------------------------------- 1 | import { keywords } from '../constants/keywords'; 2 | import { NodePath } from '../types/NodePath'; 3 | import { Program, ProgramOutput } from '../types/Program'; 4 | 5 | export type Eval = (program: Program, args: Program) => ProgramOutput; 6 | export type Group = Record; 7 | 8 | export function quoteAsProgram(program: Program): Program { 9 | return Program.cons(Program.fromBigInt(keywords['q']), program); 10 | } 11 | 12 | export function evalAsProgram(program: Program, args: Program): Program { 13 | return Program.fromList([Program.fromBigInt(keywords['a']), program, args]); 14 | } 15 | 16 | export function runAsProgram(program: Program, macroLookup: Program): Program { 17 | return evalAsProgram( 18 | Program.fromList([ 19 | Program.fromText('com'), 20 | program, 21 | quoteAsProgram(macroLookup), 22 | ]), 23 | Program.fromBytes(NodePath.top.asPath()) 24 | ); 25 | } 26 | 27 | export function brunAsProgram(program: Program, args: Program): Program { 28 | return evalAsProgram(quoteAsProgram(program), quoteAsProgram(args)); 29 | } 30 | -------------------------------------------------------------------------------- /src/utils/instructions.ts: -------------------------------------------------------------------------------- 1 | import { bytesEqual } from 'chia-bls'; 2 | import { applyAtom, quoteAtom } from '../constants/atoms'; 3 | import { costs } from '../constants/costs'; 4 | import { Instruction, Program } from '../types/Program'; 5 | import { traversePath } from './environment'; 6 | import { runOperator } from './operators'; 7 | 8 | export const instructions = { 9 | swap: ((_instructionStack, stack, _options) => { 10 | const second = stack.pop()!; 11 | const first = stack.pop()!; 12 | stack.push(second, first); 13 | return 0n; 14 | }) as Instruction, 15 | cons: ((_instructionStack, stack, _options) => { 16 | const first = stack.pop()!; 17 | const second = stack.pop()!; 18 | stack.push(Program.cons(first, second)); 19 | return 0n; 20 | }) as Instruction, 21 | eval: ((instructionStack, stack, _options) => { 22 | const pair = stack.pop()!; 23 | const program = pair.first; 24 | const args = pair.rest; 25 | if (program.isAtom) { 26 | const output = traversePath(program, args); 27 | stack.push(output.value); 28 | return output.cost; 29 | } 30 | const op = program.first; 31 | if (op.isCons) { 32 | const [newOperator, mustBeNil] = op.cons; 33 | if (newOperator.isCons || !mustBeNil.isNull) 34 | throw new Error( 35 | `Operators that are lists must contain a single atom${op.positionSuffix}.` 36 | ); 37 | const newOperandList = program.rest; 38 | stack.push(newOperator, newOperandList); 39 | instructionStack.push(instructions.apply); 40 | return costs.apply; 41 | } 42 | let operandList = program.rest; 43 | if (bytesEqual(op.atom, quoteAtom)) { 44 | stack.push(operandList); 45 | return costs.quote; 46 | } 47 | instructionStack.push(instructions.apply); 48 | stack.push(op); 49 | while (!operandList.isNull) { 50 | stack.push(Program.cons(operandList.first, args)); 51 | instructionStack.push( 52 | instructions.cons, 53 | instructions.eval, 54 | instructions.swap 55 | ); 56 | operandList = operandList.rest; 57 | } 58 | stack.push(Program.nil); 59 | return 1n; 60 | }) as Instruction, 61 | apply: ((instructionStack, stack, options) => { 62 | const operandList = stack.pop()!; 63 | const op = stack.pop()!; 64 | if (op.isCons) 65 | throw new Error(`An internal error occurred${op.positionSuffix}.`); 66 | if (bytesEqual(op.atom, applyAtom)) { 67 | const args = operandList.toList(); 68 | if (args.length !== 2) 69 | throw new Error( 70 | `Expected 2 arguments in "a" operator${operandList.positionSuffix}.` 71 | ); 72 | stack.push(Program.cons(args[0], args[1])); 73 | instructionStack.push(instructions.eval); 74 | return costs.apply; 75 | } 76 | const output = runOperator(op, operandList, options); 77 | stack.push(output.value); 78 | return output.cost; 79 | }) as Instruction, 80 | }; 81 | -------------------------------------------------------------------------------- /src/utils/ir.ts: -------------------------------------------------------------------------------- 1 | import { decodeInt } from 'chia-bls'; 2 | import { ParserError } from '../types/ParserError'; 3 | import { Program } from '../types/Program'; 4 | 5 | export function deserialize(program: number[]): Program { 6 | const sizeBytes: Array = []; 7 | if (program[0] <= 0x7f) 8 | return Program.fromBytes(Uint8Array.from([program[0]])); 9 | else if (program[0] <= 0xbf) sizeBytes.push(program[0] & 0x3f); 10 | else if (program[0] <= 0xdf) { 11 | sizeBytes.push(program[0] & 0x1f); 12 | program.shift(); 13 | if (!program.length) 14 | throw new ParserError('Expected next byte in source.'); 15 | sizeBytes.push(program[0]); 16 | } else if (program[0] <= 0xef) { 17 | sizeBytes.push(program[0] & 0x0f); 18 | for (let i = 0; i < 2; i++) { 19 | program.shift(); 20 | if (!program.length) 21 | throw new ParserError('Expected next byte in source.'); 22 | sizeBytes.push(program[0]); 23 | } 24 | } else if (program[0] <= 0xf7) { 25 | sizeBytes.push(program[0] & 0x07); 26 | for (let i = 0; i < 3; i++) { 27 | program.shift(); 28 | if (!program.length) 29 | throw new ParserError('Expected next byte in source.'); 30 | sizeBytes.push(program[0]); 31 | } 32 | } else if (program[0] <= 0xfb) { 33 | sizeBytes.push(program[0] & 0x03); 34 | for (let i = 0; i < 4; i++) { 35 | program.shift(); 36 | if (!program.length) 37 | throw new ParserError('Expected next byte in source.'); 38 | sizeBytes.push(program[0]); 39 | } 40 | } else if (program[0] === 0xff) { 41 | program.shift(); 42 | if (!program.length) 43 | throw new ParserError('Expected next byte in source.'); 44 | const first = deserialize(program); 45 | program.shift(); 46 | if (!program.length) 47 | throw new ParserError('Expected next byte in source.'); 48 | const rest = deserialize(program); 49 | return Program.cons(first, rest); 50 | } else throw new ParserError('Invalid encoding.'); 51 | const size = decodeInt(Uint8Array.from(sizeBytes)); 52 | let bytes: Array = []; 53 | for (let i = 0; i < size; i++) { 54 | program.shift(); 55 | if (!program.length) { 56 | throw new ParserError('Expected next byte in atom.'); 57 | } 58 | bytes.push(program[0]); 59 | } 60 | return Program.fromBytes(Uint8Array.from(bytes)); 61 | } 62 | -------------------------------------------------------------------------------- /src/utils/macros.ts: -------------------------------------------------------------------------------- 1 | import { Program } from '../index'; 2 | import { Eval } from './helpers'; 3 | 4 | const defaultMacroSources = [ 5 | ` 6 | ; we have to compile this externally, since it uses itself 7 | ;(defmacro defmacro (name params body) 8 | ; (qq (list (unquote name) (mod (unquote params) (unquote body)))) 9 | ;) 10 | (q . ("defmacro" 11 | (c (q . "list") 12 | (c (f 1) 13 | (c (c (q . "mod") 14 | (c (f (r 1)) 15 | (c (f (r (r 1))) 16 | (q . ())))) 17 | (q . ())))))) 18 | `, 19 | ` 20 | ;(defmacro list ARGS 21 | ; ((c (mod args 22 | ; (defun compile-list 23 | ; (args) 24 | ; (if args 25 | ; (qq (c (unquote (f args)) 26 | ; (unquote (compile-list (r args))))) 27 | ; ())) 28 | ; (compile-list args) 29 | ; ) 30 | ; ARGS 31 | ; )) 32 | ;) 33 | (q "list" 34 | (a (q #a (q #a 2 (c 2 (c 3 (q)))) 35 | (c (q #a (i 5 36 | (q #c (q . 4) 37 | (c 9 (c (a 2 (c 2 (c 13 (q)))) 38 | (q))) 39 | ) 40 | (q 1)) 41 | 1) 42 | 1)) 43 | 1)) 44 | `, 45 | `(defmacro function (BODY) 46 | (qq (opt (com (q . (unquote BODY)) 47 | (qq (unquote (macros))) 48 | (qq (unquote (symbols)))))))`, 49 | `(defmacro if (A B C) 50 | (qq (a 51 | (i (unquote A) 52 | (function (unquote B)) 53 | (function (unquote C))) 54 | @)))`, 55 | `(defmacro / (A B) (qq (f (divmod (unquote A) (unquote B)))))`, 56 | ]; 57 | 58 | let defaultMacroLookupProgram: Program | undefined; 59 | 60 | function buildDefaultMacroLookup(evalAsProgram: Eval): Program { 61 | const run = Program.fromSource('(a (com 2 3) 1)'); 62 | for (const macroSource of defaultMacroSources) { 63 | const macroProgram = Program.fromSource(macroSource); 64 | const env = Program.cons(macroProgram, defaultMacroLookupProgram!); 65 | const newMacro = evalAsProgram(run, env).value; 66 | defaultMacroLookupProgram = Program.cons( 67 | newMacro, 68 | defaultMacroLookupProgram! 69 | ); 70 | } 71 | return defaultMacroLookupProgram!; 72 | } 73 | 74 | export function defaultMacroLookup(evalAsProgram: Eval): Program { 75 | if (!defaultMacroLookupProgram || defaultMacroLookupProgram.isNull) { 76 | defaultMacroLookupProgram = Program.fromList([]); 77 | buildDefaultMacroLookup(evalAsProgram); 78 | } 79 | return defaultMacroLookupProgram; 80 | } 81 | -------------------------------------------------------------------------------- /src/utils/match.ts: -------------------------------------------------------------------------------- 1 | import { bytesEqual } from 'chia-bls'; 2 | import { Program } from '../index'; 3 | import { Group } from './helpers'; 4 | 5 | const atomMatch = new TextEncoder().encode('$'); 6 | const sexpMatch = new TextEncoder().encode(':'); 7 | 8 | export function unifyBindings( 9 | bindings: Group, 10 | key: string, 11 | valueProgram: Program 12 | ): Group | null { 13 | if (key in bindings) { 14 | if (!bindings[key].equals(valueProgram)) return null; 15 | return bindings; 16 | } 17 | return { ...bindings, [key]: valueProgram }; 18 | } 19 | 20 | export function match( 21 | pattern: Program, 22 | sexp: Program, 23 | knownBindings: Group = {} 24 | ): Group | null { 25 | if (!pattern.isCons) { 26 | if (sexp.isCons) return null; 27 | return bytesEqual(pattern.atom, sexp.atom) ? knownBindings : null; 28 | } 29 | const left = pattern.first; 30 | const right = pattern.rest; 31 | if (left.isAtom && bytesEqual(left.atom, atomMatch)) { 32 | if (sexp.isCons) return null; 33 | if (right.isAtom && bytesEqual(right.atom, atomMatch)) { 34 | if (bytesEqual(sexp.atom, atomMatch)) return {}; 35 | return null; 36 | } 37 | return unifyBindings(knownBindings, right.toText(), sexp); 38 | } 39 | if (left.isAtom && bytesEqual(left.atom, sexpMatch)) { 40 | if (right.isAtom && bytesEqual(right.atom, sexpMatch)) { 41 | if (bytesEqual(sexp.atom, sexpMatch)) return {}; 42 | return null; 43 | } 44 | return unifyBindings(knownBindings, right.toText(), sexp); 45 | } 46 | if (!sexp.isCons) return null; 47 | const newBindings = match(left, sexp.first, knownBindings); 48 | if (!newBindings) return newBindings; 49 | return match(right, sexp.rest, newBindings); 50 | } 51 | -------------------------------------------------------------------------------- /src/utils/mod.ts: -------------------------------------------------------------------------------- 1 | import { consAtom } from '../constants/atoms'; 2 | import { Program } from '../index'; 3 | import { BetterSet } from '../types/BetterSet'; 4 | import { NodePath } from '../types/NodePath'; 5 | import { compareStrings } from './compare'; 6 | import { Eval, evalAsProgram, Group, quoteAsProgram } from './helpers'; 7 | import { optimizeProgram } from './optimize'; 8 | 9 | const mainName = ''; 10 | 11 | export function buildTree(items: Program[]): Program { 12 | if (items.length === 0) return Program.nil; 13 | else if (items.length === 1) return items[0]; 14 | const halfSize = items.length >> 1; 15 | return Program.cons( 16 | buildTree(items.slice(0, halfSize)), 17 | buildTree(items.slice(halfSize)) 18 | ); 19 | } 20 | 21 | export function buildTreeProgram(items: Program[]): Program { 22 | if (items.length === 0) 23 | return Program.fromList([quoteAsProgram(Program.nil)]); 24 | else if (items.length === 1) return items[0]; 25 | const halfSize = items.length >> 1; 26 | return Program.fromList([ 27 | Program.fromBytes(consAtom), 28 | buildTreeProgram(items.slice(0, halfSize)), 29 | buildTreeProgram(items.slice(halfSize)), 30 | ]); 31 | } 32 | 33 | export function flatten(program: Program): string[] { 34 | if (program.isCons) 35 | return [...flatten(program.first), ...flatten(program.rest)]; 36 | else return [program.toText()]; 37 | } 38 | 39 | export function buildUsedConstantNames( 40 | functions: Group, 41 | constants: Group, 42 | macros: Program[] 43 | ): BetterSet { 44 | const macrosAsDict: Group = {}; 45 | for (const item of macros) macrosAsDict[item.rest.first.toText()] = item; 46 | const possibleSymbols = new BetterSet(Object.keys(functions)); 47 | possibleSymbols.update(new BetterSet(Object.keys(constants))); 48 | let newNames = new BetterSet([mainName]); 49 | const usedNames = new BetterSet(newNames); 50 | while (newNames.size) { 51 | const priorNewNames = new BetterSet(newNames); 52 | newNames = new BetterSet(); 53 | for (const item of priorNewNames) { 54 | for (const group of [functions, macrosAsDict]) { 55 | if (item in group) 56 | newNames.update(new BetterSet(flatten(group[item]))); 57 | } 58 | } 59 | newNames.differenceUpdate(usedNames); 60 | usedNames.update(newNames); 61 | } 62 | usedNames.intersectionUpdate(possibleSymbols); 63 | usedNames.delete(mainName); 64 | return usedNames.sort((a, b) => compareStrings(a, b)); 65 | } 66 | 67 | export function parseInclude( 68 | name: Program, 69 | namespace: BetterSet, 70 | functions: Group, 71 | constants: Group, 72 | macros: Program[], 73 | runProgram: Eval 74 | ): void { 75 | const program = Program.fromSource('(_read (_full_path_for_name 1))'); 76 | const output = runProgram(program, name).value; 77 | for (const item of output.toList()) 78 | parseModProgram( 79 | item, 80 | namespace, 81 | functions, 82 | constants, 83 | macros, 84 | runProgram 85 | ); 86 | } 87 | 88 | export function unquoteArgs(program: Program, args: string[]): Program { 89 | if (program.isCons) { 90 | return Program.cons( 91 | unquoteArgs(program.first, args), 92 | unquoteArgs(program.rest, args) 93 | ); 94 | } else if (args.includes(program.toText())) { 95 | return Program.fromList([Program.fromText('unquote'), program]); 96 | } 97 | return program; 98 | } 99 | 100 | export function defunInlineToMacro(program: Program): Program { 101 | const second = program.rest; 102 | const third = second.rest; 103 | const items = [Program.fromText('defmacro'), second.first, third.first]; 104 | const code = third.rest.first; 105 | const args = flatten(third.first).filter((item) => item.length); 106 | const unquotedCode = unquoteArgs(code, args); 107 | items.push(Program.fromList([Program.fromText('qq'), unquotedCode])); 108 | return Program.fromList(items); 109 | } 110 | 111 | export function parseModProgram( 112 | declarationProgram: Program, 113 | namespace: BetterSet, 114 | functions: Group, 115 | constants: Group, 116 | macros: Program[], 117 | runProgram: Eval 118 | ): void { 119 | const op = declarationProgram.first.toText(); 120 | const nameProgram = declarationProgram.rest.first; 121 | if (op === 'include') { 122 | parseInclude( 123 | nameProgram, 124 | namespace, 125 | functions, 126 | constants, 127 | macros, 128 | runProgram 129 | ); 130 | return; 131 | } 132 | const name = nameProgram.toText(); 133 | if (namespace.has(name)) { 134 | throw new Error(`Symbol ${JSON.stringify(name)} redefined.`); 135 | } 136 | namespace.add(name); 137 | if (op === 'defmacro') { 138 | macros.push(declarationProgram); 139 | } else if (op === 'defun') { 140 | functions[name] = declarationProgram.rest.rest; 141 | } else if (op === 'defun-inline') { 142 | macros.push(defunInlineToMacro(declarationProgram)); 143 | } else if (op === 'defconstant') { 144 | constants[name] = quoteAsProgram(declarationProgram.rest.rest.first); 145 | } else { 146 | throw new Error( 147 | `Expected "defun", "defun-inline", "defmacro", or "defconstant", but got ${JSON.stringify( 148 | op 149 | )}.` 150 | ); 151 | } 152 | } 153 | 154 | export function compileModStage1( 155 | args: Program, 156 | runProgram: Eval 157 | ): [functions: Group, constants: Group, macros: Program[]] { 158 | const functions: Group = {}; 159 | const constants: Group = {}; 160 | const macros: Array = []; 161 | const mainLocalArguments = args.first; 162 | const namespace = new BetterSet(); 163 | while (true) { 164 | args = args.rest; 165 | if (args.rest.isNull) break; 166 | parseModProgram( 167 | args.first, 168 | namespace, 169 | functions, 170 | constants, 171 | macros, 172 | runProgram 173 | ); 174 | } 175 | const uncompiledMain = args.first; 176 | functions[mainName] = Program.fromList([ 177 | mainLocalArguments, 178 | uncompiledMain, 179 | ]); 180 | return [functions, constants, macros]; 181 | } 182 | 183 | export function symbolTableForTree(tree: Program, rootNode: NodePath): Program { 184 | if (tree.isNull) return Program.nil; 185 | else if (!tree.isCons) 186 | return Program.fromList([ 187 | Program.fromList([tree, Program.fromBytes(rootNode.asPath())]), 188 | ]); 189 | const left = symbolTableForTree(tree.first, rootNode.add(NodePath.left)); 190 | const right = symbolTableForTree(tree.rest, rootNode.add(NodePath.right)); 191 | return Program.fromList([...left.toList(), ...right.toList()]); 192 | } 193 | 194 | export function buildMacroLookupProgram( 195 | macroLookup: Program, 196 | macros: Program[], 197 | runProgram: Eval 198 | ): Program { 199 | let macroLookupProgram = quoteAsProgram(macroLookup); 200 | for (const macro of macros) { 201 | macroLookupProgram = evalAsProgram( 202 | Program.fromList([ 203 | Program.fromText('opt'), 204 | Program.fromList([ 205 | Program.fromText('com'), 206 | quoteAsProgram( 207 | Program.fromList([ 208 | Program.fromBytes(consAtom), 209 | macro, 210 | macroLookupProgram, 211 | ]) 212 | ), 213 | macroLookupProgram, 214 | ]), 215 | ]), 216 | Program.fromBytes(NodePath.top.asPath()) 217 | ); 218 | macroLookupProgram = optimizeProgram(macroLookupProgram, runProgram); 219 | } 220 | return macroLookupProgram; 221 | } 222 | 223 | export function compileFunctions( 224 | functions: Group, 225 | macroLookupProgram: Program, 226 | constantSymbolTable: Program, 227 | argsRootNode: NodePath 228 | ): Group { 229 | const compiledFunctions: Group = {}; 230 | for (const [name, lambdaExpression] of Object.entries(functions)) { 231 | const localSymbolTable = symbolTableForTree( 232 | lambdaExpression.first, 233 | argsRootNode 234 | ); 235 | const allSymbols = Program.fromList([ 236 | ...localSymbolTable.toList(), 237 | ...constantSymbolTable.toList(), 238 | ]); 239 | compiledFunctions[name] = Program.fromList([ 240 | Program.fromText('opt'), 241 | Program.fromList([ 242 | Program.fromText('com'), 243 | quoteAsProgram(lambdaExpression.rest.first), 244 | macroLookupProgram, 245 | quoteAsProgram(allSymbols), 246 | ]), 247 | ]); 248 | } 249 | return compiledFunctions; 250 | } 251 | 252 | export function compileMod( 253 | args: Program, 254 | macroLookup: Program, 255 | _symbolTable: Program, 256 | runProgram: Eval 257 | ): Program { 258 | const [functions, constants, macros] = compileModStage1(args, runProgram); 259 | const macroLookupProgram = buildMacroLookupProgram( 260 | macroLookup, 261 | macros, 262 | runProgram 263 | ); 264 | const allConstantNames = buildUsedConstantNames( 265 | functions, 266 | constants, 267 | macros 268 | ); 269 | const hasConstantTree = allConstantNames.size > 0; 270 | const constantTree = buildTree([ 271 | ...allConstantNames.map((item) => Program.fromText(item)), 272 | ]); 273 | const constantRootNode = NodePath.left; 274 | const argsRootNode = hasConstantTree ? NodePath.right : NodePath.top; 275 | const constantSymbolTable = symbolTableForTree( 276 | constantTree, 277 | constantRootNode 278 | ); 279 | const compiledFunctions = compileFunctions( 280 | functions, 281 | macroLookupProgram, 282 | constantSymbolTable, 283 | argsRootNode 284 | ); 285 | const mainPathSource = compiledFunctions[mainName].toString(); 286 | let argTreeSource: string; 287 | if (hasConstantTree) { 288 | const allConstantsLookup: Group = {}; 289 | for (const [key, value] of Object.entries(compiledFunctions)) 290 | if (allConstantNames.has(key)) allConstantsLookup[key] = value; 291 | Object.assign(allConstantsLookup, constants); 292 | const allConstantsList = [...allConstantNames].map( 293 | (item) => allConstantsLookup[item] 294 | ); 295 | const allConstantsTreeProgram = buildTreeProgram(allConstantsList); 296 | const allConstantsTreeSource = allConstantsTreeProgram.toString(); 297 | argTreeSource = `(c ${allConstantsTreeSource} 1)`; 298 | } else { 299 | argTreeSource = '1'; 300 | } 301 | return Program.fromSource( 302 | `(opt (q . (a ${mainPathSource} ${argTreeSource})))` 303 | ); 304 | } 305 | -------------------------------------------------------------------------------- /src/utils/operators.ts: -------------------------------------------------------------------------------- 1 | import { 2 | bigIntToBytes, 3 | bytesEqual, 4 | bytesToBigInt, 5 | bytesToInt, 6 | defaultEc, 7 | hash256, 8 | JacobianPoint, 9 | mod, 10 | PrivateKey, 11 | } from 'chia-bls'; 12 | import { costs } from '../constants/costs'; 13 | import { keywords } from '../constants/keywords'; 14 | import { Program, ProgramOutput, RunOptions } from '../types/Program'; 15 | 16 | export type Operator = (args: Program) => ProgramOutput; 17 | 18 | export interface Operators { 19 | operators: Record; 20 | unknown: (operator: Program, args: Program) => ProgramOutput; 21 | quote: string; 22 | apply: string; 23 | } 24 | 25 | export const operators = { 26 | i: ((args: Program): ProgramOutput => { 27 | const list = toList(args, 'i', 3); 28 | return { value: list[0].isNull ? list[2] : list[1], cost: costs.if }; 29 | }) as Operator, 30 | c: ((args: Program): ProgramOutput => { 31 | const list = toList(args, 'c', 2); 32 | return { value: Program.cons(list[0], list[1]), cost: costs.cons }; 33 | }) as Operator, 34 | f: ((args: Program): ProgramOutput => { 35 | const list = toList(args, 'f', 1, 'cons'); 36 | return { value: list[0].first, cost: costs.first }; 37 | }) as Operator, 38 | r: ((args: Program): ProgramOutput => { 39 | const list = toList(args, 'r', 1, 'cons'); 40 | return { value: list[0].rest, cost: costs.rest }; 41 | }) as Operator, 42 | l: ((args: Program): ProgramOutput => { 43 | const list = toList(args, 'l', 1); 44 | return { value: Program.fromBool(list[0].isCons), cost: costs.listp }; 45 | }) as Operator, 46 | x: ((args: Program): ProgramOutput => { 47 | throw new Error(`The error ${args} was raised${args.positionSuffix}.`); 48 | }) as Operator, 49 | '=': ((args: Program): ProgramOutput => { 50 | const list = toList(args, '=', 2, 'atom'); 51 | return { 52 | value: Program.fromBool(bytesEqual(list[0].atom, list[1].atom)), 53 | cost: 54 | costs.eqBase + 55 | (BigInt(list[0].atom.length) + BigInt(list[1].atom.length)) * 56 | costs.eqPerByte, 57 | }; 58 | }) as Operator, 59 | sha256: ((args: Program): ProgramOutput => { 60 | const list = toList(args, 'sha256', undefined, 'atom'); 61 | let cost = costs.sha256Base; 62 | let argLength = 0; 63 | const bytes: Array = []; 64 | for (const item of list) { 65 | for (const byte of item.atom) bytes.push(byte); 66 | argLength += item.atom.length; 67 | cost += costs.sha256PerArg; 68 | } 69 | cost += BigInt(argLength) * costs.sha256PerByte; 70 | return mallocCost({ 71 | value: Program.fromBytes(hash256(Uint8Array.from(bytes))), 72 | cost, 73 | }); 74 | }) as Operator, 75 | '+': ((args: Program): ProgramOutput => { 76 | const list = toList(args, '+', undefined, 'atom'); 77 | let total = 0n; 78 | let cost = costs.arithBase; 79 | let argSize = 0; 80 | for (const item of list) { 81 | total += item.toBigInt(); 82 | argSize += item.atom.length; 83 | cost += costs.arithPerArg; 84 | } 85 | cost += BigInt(argSize) * costs.arithPerByte; 86 | return mallocCost({ value: Program.fromBigInt(total), cost }); 87 | }) as Operator, 88 | '-': ((args: Program): ProgramOutput => { 89 | let cost = costs.arithBase; 90 | if (args.isNull) return { value: Program.nil, cost: cost }; 91 | const list = toList(args, '-', undefined, 'atom'); 92 | let total = 0n; 93 | let sign = 1n; 94 | let argSize = 0; 95 | for (const item of list) { 96 | total += sign * item.toBigInt(); 97 | sign = -1n; 98 | argSize += item.atom.length; 99 | cost += costs.arithPerArg; 100 | } 101 | cost += BigInt(argSize) * costs.arithPerByte; 102 | return mallocCost({ value: Program.fromBigInt(total), cost }); 103 | }) as Operator, 104 | '*': ((args: Program): ProgramOutput => { 105 | const list = toList(args, '*', undefined, 'atom'); 106 | let cost = costs.mulBase; 107 | if (!list.length) return mallocCost({ value: Program.true, cost }); 108 | let value = list[0].toBigInt(); 109 | let size = list[0].atom.length; 110 | for (const item of list.slice(1)) { 111 | cost += 112 | costs.mulPerOp + 113 | (BigInt(item.atom.length) + BigInt(size)) * 114 | costs.mulLinearPerByte + 115 | (BigInt(item.atom.length) * BigInt(size)) / 116 | costs.mulSquarePerByteDivider; 117 | value *= item.toBigInt(); 118 | size = limbsForBigInt(value); 119 | } 120 | return mallocCost({ value: Program.fromBigInt(value), cost }); 121 | }) as Operator, 122 | divmod: ((args: Program): ProgramOutput => { 123 | const list = toList(args, 'divmod', 2, 'atom'); 124 | let cost = costs.divmodBase; 125 | const numerator = list[0].toBigInt(); 126 | const denominator = list[1].toBigInt(); 127 | if (denominator === 0n) 128 | throw new Error( 129 | `Cannot divide by zero in "divmod" operator${args.positionSuffix}.` 130 | ); 131 | cost += 132 | (BigInt(list[0].atom.length) + BigInt(list[1].atom.length)) * 133 | costs.divmodPerByte; 134 | let quotientValue = numerator / denominator; 135 | const remainderValue = mod(numerator, denominator); 136 | if (numerator < 0n !== denominator < 0n && remainderValue !== 0n) 137 | quotientValue -= 1n; 138 | const quotient = Program.fromBigInt(quotientValue); 139 | const remainder = Program.fromBigInt(remainderValue); 140 | cost += 141 | (BigInt(quotient.atom.length) + BigInt(remainder.atom.length)) * 142 | costs.mallocPerByte; 143 | return { value: Program.cons(quotient, remainder), cost }; 144 | }) as Operator, 145 | '/': ((args: Program): ProgramOutput => { 146 | const list = toList(args, '/', 2, 'atom'); 147 | let cost = costs.divBase; 148 | const numerator = list[0].toBigInt(); 149 | const denominator = list[1].toBigInt(); 150 | if (denominator === 0n) 151 | throw new Error( 152 | `Cannot divide by zero in "/" operator${args.positionSuffix}.` 153 | ); 154 | cost += 155 | (BigInt(list[0].atom.length) + BigInt(list[1].atom.length)) * 156 | costs.divPerByte; 157 | let quotientValue = numerator / denominator; 158 | const remainderValue = mod(numerator, denominator); 159 | if (numerator < 0n !== denominator < 0n && quotientValue < 0n) 160 | quotientValue -= 1n; 161 | const quotient = Program.fromBigInt(quotientValue); 162 | return mallocCost({ value: quotient, cost }); 163 | }) as Operator, 164 | '>': ((args: Program): ProgramOutput => { 165 | const list = toList(args, '>', 2, 'atom'); 166 | const cost = 167 | costs.grBase + 168 | (BigInt(list[0].atom.length) + BigInt(list[1].atom.length)) * 169 | costs.grPerByte; 170 | return { 171 | value: Program.fromBool(list[0].toBigInt() > list[1].toBigInt()), 172 | cost, 173 | }; 174 | }) as Operator, 175 | '>s': ((args: Program): ProgramOutput => { 176 | const list = toList(args, '>s', 2, 'atom'); 177 | const cost = 178 | costs.grsBase + 179 | (BigInt(list[0].atom.length) + BigInt(list[1].atom.length)) * 180 | costs.grsPerByte; 181 | return { 182 | value: Program.fromBool( 183 | list[0].toHex().localeCompare(list[1].toHex()) === 1 184 | ), 185 | cost, 186 | }; 187 | }) as Operator, 188 | pubkey_for_exp: ((args: Program): ProgramOutput => { 189 | const list = toList(args, 'pubkey_for_exp', 1, 'atom'); 190 | const value = mod(list[0].toBigInt(), defaultEc.n); 191 | const exponent = PrivateKey.fromBytes(bigIntToBytes(value, 32, 'big')); 192 | const cost = 193 | costs.pubkeyBase + 194 | BigInt(list[0].atom.length) * costs.pubkeyPerByte; 195 | return mallocCost({ 196 | value: Program.fromBytes(exponent.getG1().toBytes()), 197 | cost, 198 | }); 199 | }) as Operator, 200 | point_add: ((args: Program): ProgramOutput => { 201 | const list = toList(args, 'point_add', undefined, 'atom'); 202 | let cost = costs.pointAddBase; 203 | let point = JacobianPoint.infinityG1(); 204 | for (const item of list) { 205 | point = point.add(JacobianPoint.fromBytes(item.atom, false)); 206 | cost += costs.pointAddPerArg; 207 | } 208 | return mallocCost({ value: Program.fromBytes(point.toBytes()), cost }); 209 | }) as Operator, 210 | strlen: ((args: Program): ProgramOutput => { 211 | const list = toList(args, 'strlen', 1, 'atom'); 212 | const size = list[0].atom.length; 213 | const cost = costs.strlenBase + BigInt(size) * costs.strlenPerByte; 214 | return mallocCost({ value: Program.fromInt(size), cost }); 215 | }) as Operator, 216 | substr: ((args: Program): ProgramOutput => { 217 | const list = toList(args, 'substr', [2, 3], 'atom'); 218 | const value = list[0].atom; 219 | if ( 220 | list[1].atom.length > 4 || 221 | (list.length === 3 && list[2].atom.length > 4) 222 | ) 223 | throw new Error( 224 | `Expected 4 byte indices in "substr" operator${args.positionSuffix}.` 225 | ); 226 | const from = list[1].toInt(); 227 | const to = list.length === 3 ? list[2].toInt() : value.length; 228 | if (to > value.length || to < from || to < 0 || from < 0) 229 | throw new Error( 230 | `Invalid indices in "substr" operator${args.positionSuffix}.` 231 | ); 232 | return { value: Program.fromBytes(value.slice(from, to)), cost: 1n }; 233 | }) as Operator, 234 | concat: ((args: Program): ProgramOutput => { 235 | const list = toList(args, 'concat', undefined, 'atom'); 236 | let cost = costs.concatBase; 237 | const bytes: Array = []; 238 | for (const item of list) { 239 | for (const byte of item.atom) bytes.push(byte); 240 | cost += costs.concatPerArg; 241 | } 242 | cost += BigInt(bytes.length) * costs.concatPerByte; 243 | return mallocCost({ 244 | value: Program.fromBytes(Uint8Array.from(bytes)), 245 | cost, 246 | }); 247 | }) as Operator, 248 | ash: ((args: Program): ProgramOutput => { 249 | const list = toList(args, 'ash', 2, 'atom'); 250 | if (list[1].atom.length > 4) 251 | throw new Error( 252 | `Shift must be 32 bits in "ash" operator${args.positionSuffix}.` 253 | ); 254 | const shift = list[1].toBigInt(); 255 | if ((shift < 0n ? -shift : shift) > 65535n) 256 | throw new Error( 257 | `Shift too large in "ash" operator${args.positionSuffix}.` 258 | ); 259 | let value = list[0].toBigInt(); 260 | if (shift >= 0) value <<= shift; 261 | else value >>= -shift; 262 | const cost = 263 | costs.ashiftBase + 264 | (BigInt(list[0].atom.length) + BigInt(limbsForBigInt(value))) * 265 | costs.ashiftPerByte; 266 | return mallocCost({ value: Program.fromBigInt(value), cost }); 267 | }) as Operator, 268 | lsh: ((args: Program): ProgramOutput => { 269 | const list = toList(args, 'lsh', 2, 'atom'); 270 | if (list[1].atom.length > 4) 271 | throw new Error( 272 | `Shift must be 32 bits in "lsh" operator${args.positionSuffix}.` 273 | ); 274 | const shift = list[1].toBigInt(); 275 | if ((shift < 0n ? -shift : shift) > 65535n) 276 | throw new Error( 277 | `Shift too large in "lsh" operator${args.positionSuffix}.` 278 | ); 279 | let value = bytesToBigInt(list[0].atom, 'big', false); 280 | if (value < 0n) value = -value; 281 | if (shift >= 0) value <<= shift; 282 | else value >>= -shift; 283 | const cost = 284 | costs.lshiftBase + 285 | (BigInt(list[0].atom.length) + BigInt(limbsForBigInt(value))) * 286 | costs.lshiftPerByte; 287 | return mallocCost({ value: Program.fromBigInt(value), cost }); 288 | }) as Operator, 289 | logand: ((args: Program): ProgramOutput => 290 | binopReduction('logand', -1n, args, (a, b) => a & b)) as Operator, 291 | logior: ((args: Program): ProgramOutput => 292 | binopReduction('logior', 0n, args, (a, b) => a | b)) as Operator, 293 | logxor: ((args: Program): ProgramOutput => 294 | binopReduction('logxor', 0n, args, (a, b) => a ^ b)) as Operator, 295 | lognot: ((args: Program): ProgramOutput => { 296 | const items = toList(args, 'lognot', 1, 'atom'); 297 | const cost = 298 | costs.lognotBase + 299 | BigInt(items[0].atom.length) * costs.lognotPerByte; 300 | return mallocCost({ 301 | value: Program.fromBigInt(~items[0].toBigInt()), 302 | cost, 303 | }); 304 | }) as Operator, 305 | not: ((args: Program): ProgramOutput => { 306 | const items = toList(args, 'not', 1); 307 | const cost = costs.boolBase; 308 | return { value: Program.fromBool(items[0].isNull), cost: cost }; 309 | }) as Operator, 310 | any: ((args: Program): ProgramOutput => { 311 | const list = toList(args, 'any'); 312 | const cost = costs.boolBase + BigInt(list.length) * costs.boolPerArg; 313 | let result = false; 314 | for (const item of list) { 315 | if (!item.isNull) { 316 | result = true; 317 | break; 318 | } 319 | } 320 | return { value: Program.fromBool(result), cost: cost }; 321 | }) as Operator, 322 | all: ((args: Program): ProgramOutput => { 323 | const list = toList(args, 'all'); 324 | const cost = costs.boolBase + BigInt(list.length) * costs.boolPerArg; 325 | let result = true; 326 | for (const item of list) { 327 | if (item.isNull) { 328 | result = false; 329 | break; 330 | } 331 | } 332 | return { value: Program.fromBool(result), cost: cost }; 333 | }) as Operator, 334 | softfork: ((args: Program): ProgramOutput => { 335 | const list = toList(args, 'softfork', [1, Infinity]); 336 | if (!list[0].isAtom) 337 | throw new Error( 338 | `Expected atom argument in "softfork" operator at ${list[0].positionSuffix}.` 339 | ); 340 | const cost = list[0].toBigInt(); 341 | if (cost < 1n) 342 | throw new Error( 343 | `Cost must be greater than zero in "softfork" operator${args.positionSuffix}.` 344 | ); 345 | return { value: Program.false, cost: cost }; 346 | }) as Operator, 347 | }; 348 | 349 | export const defaultOperators = { 350 | operators, 351 | unknown: defaultUnknownOperator, 352 | quote: 'q', 353 | apply: 'a', 354 | }; 355 | 356 | export function makeDefaultOperators() { 357 | return { 358 | ...defaultOperators, 359 | operators: { ...defaultOperators.operators }, 360 | }; 361 | } 362 | 363 | export function toList( 364 | program: Program, 365 | name: string, 366 | length?: [number, number] | number, 367 | type?: 'atom' | 'cons' 368 | ): Program[] { 369 | const list = program.toList(); 370 | if (typeof length === 'number' && list.length !== length) 371 | throw new Error( 372 | `Expected ${length} arguments in ${JSON.stringify(name)} operator${ 373 | program.positionSuffix 374 | }.` 375 | ); 376 | else if ( 377 | Array.isArray(length) && 378 | (list.length < length[0] || list.length > length[1]) 379 | ) 380 | throw new Error( 381 | `Expected ${ 382 | length[1] === Infinity 383 | ? `at least ${length[0]}` 384 | : `between ${length[0]} and ${length[1]}` 385 | } arguments in ${JSON.stringify(name)} operator${ 386 | program.positionSuffix 387 | }.` 388 | ); 389 | if (type !== undefined) 390 | list.forEach((item) => { 391 | if ( 392 | (type === 'atom' && !item.isAtom) || 393 | (type === 'cons' && !item.isCons) 394 | ) 395 | throw new Error( 396 | `Expected ${type} argument in ${JSON.stringify( 397 | name 398 | )} operator${item.positionSuffix}.` 399 | ); 400 | }); 401 | return list; 402 | } 403 | 404 | export function limbsForBigInt(value: bigint): number { 405 | let length = 406 | value === 0n ? 0 : (value < 0n ? -value : value).toString(2).length; 407 | if (value < 0n) length++; 408 | return (length + 7) >> 3; 409 | } 410 | 411 | export function mallocCost(output: ProgramOutput): ProgramOutput { 412 | return { 413 | value: output.value, 414 | cost: 415 | output.cost + 416 | BigInt(output.value.atom.length) * costs.mallocPerByte, 417 | }; 418 | } 419 | 420 | export function binopReduction( 421 | opName: string, 422 | initialValue: bigint, 423 | args: Program, 424 | opFunction: (a: bigint, b: bigint) => bigint 425 | ): ProgramOutput { 426 | let total = initialValue; 427 | let argSize = 0; 428 | let cost = costs.logBase; 429 | for (const item of args.toList().map((item) => { 430 | if (!item.isAtom) 431 | throw new Error( 432 | `Expected atom argument in ${JSON.stringify(opName)} operator${ 433 | item.positionSuffix 434 | }.` 435 | ); 436 | return item; 437 | })) { 438 | total = opFunction(total, item.toBigInt()); 439 | argSize += item.atom.length; 440 | cost += costs.logPerArg; 441 | } 442 | cost += BigInt(argSize) * costs.logPerByte; 443 | return mallocCost({ value: Program.fromBigInt(total), cost }); 444 | } 445 | 446 | export function defaultUnknownOperator( 447 | op: Program, 448 | args: Program 449 | ): ProgramOutput { 450 | if ( 451 | !op.atom.length || 452 | bytesEqual(op.atom.slice(0, 2), Uint8Array.from([0xff, 0xff])) 453 | ) 454 | throw new Error(`Reserved operator${op.positionSuffix}.`); 455 | if (op.atom.length > 5) 456 | throw new Error(`Invalid operator${op.positionSuffix}.`); 457 | const costFunction = (op.atom[op.atom.length - 1] & 0xc0) >> 6; 458 | const costMultiplier = 459 | bytesToInt(op.atom.slice(0, op.atom.length - 1), 'big') + 1; 460 | let cost: bigint; 461 | if (costFunction === 0) cost = 1n; 462 | else if (costFunction === 1) { 463 | cost = costs.arithBase; 464 | let argSize = 0; 465 | for (const item of args.toList()) { 466 | if (!item.isAtom) 467 | throw new Error( 468 | `Expected atom argument${item.positionSuffix}.` 469 | ); 470 | argSize += item.atom.length; 471 | cost += costs.arithPerArg; 472 | } 473 | cost += BigInt(argSize) * costs.arithPerByte; 474 | } else if (costFunction === 2) { 475 | cost = costs.mulBase; 476 | const argList = args.toList(); 477 | if (argList.length) { 478 | const first = argList[0]; 479 | if (!first.isAtom) 480 | throw new Error( 481 | `Expected atom argument${first.positionSuffix}.` 482 | ); 483 | let current = first.atom.length; 484 | for (const item of argList.slice(1)) { 485 | if (!item.isAtom) 486 | throw new Error( 487 | `Expected atom argument${item.positionSuffix}.` 488 | ); 489 | cost += 490 | costs.mulPerOp + 491 | (BigInt(item.atom.length) + BigInt(current)) * 492 | costs.mulLinearPerByte + 493 | (BigInt(item.atom.length) * BigInt(current)) / 494 | costs.mulSquarePerByteDivider; 495 | current += item.atom.length; 496 | } 497 | } 498 | } else if (costFunction === 3) { 499 | cost = costs.concatBase; 500 | let length = 0; 501 | for (const item of args.toList()) { 502 | if (!item.isAtom) 503 | throw new Error( 504 | `Expected atom argument${item.positionSuffix}.` 505 | ); 506 | cost += costs.concatPerArg; 507 | length += item.atom.length; 508 | } 509 | cost += BigInt(length) * costs.concatPerByte; 510 | } else throw new Error(`Unknown cost function${op.positionSuffix}.`); 511 | cost *= BigInt(costMultiplier); 512 | if (cost >= 2n ** 32n) 513 | throw new Error(`Invalid operator${op.positionSuffix}.`); 514 | return { value: Program.nil, cost: cost }; 515 | } 516 | 517 | export function runOperator( 518 | op: Program, 519 | args: Program, 520 | options: RunOptions 521 | ): ProgramOutput { 522 | const symbol = op.toBigInt(); 523 | const keyword = 524 | Object.entries(keywords).find((entry) => entry[1] === symbol)?.[0] ?? 525 | op.toText(); 526 | if (keyword in options.operators.operators) { 527 | const result = options.operators.operators[keyword](args); 528 | return result; 529 | } else return options.operators.unknown(op, args); 530 | } 531 | -------------------------------------------------------------------------------- /src/utils/optimize.ts: -------------------------------------------------------------------------------- 1 | import { bytesEqual } from 'chia-bls'; 2 | import { quoteAtom, raiseAtom } from '../constants/atoms'; 3 | import { keywords } from '../constants/keywords'; 4 | import { NodePath } from '../types/NodePath'; 5 | import { Program } from '../types/Program'; 6 | import { Eval, quoteAsProgram } from './helpers'; 7 | import { match } from './match'; 8 | import { Operator } from './operators'; 9 | 10 | export function seemsConstant(program: Program): boolean { 11 | if (!program.isCons) return program.isNull; 12 | const operator = program.first; 13 | if (!operator.isCons) { 14 | const value = operator.atom; 15 | if (bytesEqual(value, quoteAtom)) return true; 16 | else if (bytesEqual(value, raiseAtom)) return false; 17 | } else if (!seemsConstant(operator)) return false; 18 | return program.rest.toList().every((item) => seemsConstant(item)); 19 | } 20 | 21 | export function constantOptimizer( 22 | program: Program, 23 | evalAsProgram: Eval 24 | ): Program { 25 | if (seemsConstant(program) && !program.isNull) { 26 | const newProgram = evalAsProgram(program, Program.nil).value; 27 | program = quoteAsProgram(newProgram); 28 | } 29 | return program; 30 | } 31 | 32 | export function isArgsCall(program: Program): boolean { 33 | return program.isAtom && program.toBigInt() === 1n; 34 | } 35 | 36 | export function consQuoteApplyOptimizer( 37 | program: Program, 38 | _evalAsProgram: Eval 39 | ): Program { 40 | const matched = match( 41 | Program.fromSource('(a (q . (: . sexp)) (: . args))'), 42 | program 43 | ); 44 | if (matched && isArgsCall(matched['args'])) { 45 | return matched['sexp']; 46 | } 47 | return program; 48 | } 49 | 50 | export function consFirst(args: Program): Program { 51 | const matched = match( 52 | Program.fromSource('(c (: . first) (: . rest))'), 53 | args 54 | ); 55 | if (matched) { 56 | return matched['first']; 57 | } 58 | return Program.fromList([Program.fromBigInt(keywords['f']), args]); 59 | } 60 | 61 | export function consRest(args: Program): Program { 62 | const matched = match( 63 | Program.fromSource('(c (: . first) (: . rest))'), 64 | args 65 | ); 66 | if (matched) { 67 | return matched['rest']; 68 | } 69 | return Program.fromList([Program.fromBigInt(keywords['r']), args]); 70 | } 71 | 72 | export function pathFromArgs(program: Program, args: Program): Program { 73 | const value = program.toBigInt(); 74 | if (value <= 1n) { 75 | return args; 76 | } 77 | program = Program.fromBigInt(value >> 1n); 78 | if (value & 1n) { 79 | return pathFromArgs(program, consRest(args)); 80 | } 81 | return pathFromArgs(program, consFirst(args)); 82 | } 83 | 84 | export function subArgs(program: Program, args: Program): Program { 85 | if (!program.isCons) { 86 | return pathFromArgs(program, args); 87 | } 88 | let first = program.first; 89 | if (first.isCons) first = subArgs(first, args); 90 | else if (bytesEqual(first.atom, quoteAtom)) { 91 | return program; 92 | } 93 | return Program.fromList([ 94 | first, 95 | ...program.rest.toList().map((item) => subArgs(item, args)), 96 | ]); 97 | } 98 | 99 | export function varChangeOptimizerConsEval( 100 | program: Program, 101 | evalAsProgram: Eval 102 | ): Program { 103 | const matched = match( 104 | Program.fromSource('(a (q . (: . sexp)) (: . args))'), 105 | program 106 | ); 107 | if (!matched) { 108 | return program; 109 | } 110 | const originalArgs = matched['args']; 111 | const originalCall = matched['sexp']; 112 | const newEvalProgramArgs = subArgs(originalCall, originalArgs); 113 | if (seemsConstant(newEvalProgramArgs)) { 114 | return optimizeProgram(newEvalProgramArgs, evalAsProgram); 115 | } 116 | const newOperands = newEvalProgramArgs.toList(); 117 | const optOperands = newOperands.map((item) => 118 | optimizeProgram(item, evalAsProgram) 119 | ); 120 | const nonConstantCount = optOperands.filter( 121 | (item) => 122 | item.isCons && 123 | (item.first.isCons || !bytesEqual(item.first.atom, quoteAtom)) 124 | ).length; 125 | if (nonConstantCount < 1) { 126 | return Program.fromList(optOperands); 127 | } 128 | return program; 129 | } 130 | 131 | export function childrenOptimizer( 132 | program: Program, 133 | evalAsProgram: Eval 134 | ): Program { 135 | if (!program.isCons) { 136 | return program; 137 | } 138 | const operator = program.first; 139 | if (operator.isAtom && bytesEqual(operator.atom, quoteAtom)) { 140 | return program; 141 | } 142 | return Program.fromList( 143 | program.toList().map((item) => optimizeProgram(item, evalAsProgram)) 144 | ); 145 | } 146 | 147 | export function consOptimizer(program: Program, _evalAsProgram: Eval): Program { 148 | let matched = match( 149 | Program.fromSource('(f (c (: . first) (: . rest)))'), 150 | program 151 | ); 152 | if (matched) { 153 | return matched['first']; 154 | } 155 | matched = match( 156 | Program.fromSource('(r (c (: . first) (: . rest)))'), 157 | program 158 | ); 159 | if (matched) { 160 | return matched['rest']; 161 | } 162 | return program; 163 | } 164 | 165 | export function pathOptimizer(program: Program, _evalAsProgram: Eval): Program { 166 | let matched = match(Program.fromSource('(f ($ . atom))'), program); 167 | if (matched && !matched['atom'].isNull) { 168 | const node = new NodePath(matched['atom'].toBigInt()).add( 169 | NodePath.left 170 | ); 171 | return Program.fromBytes(node.asPath()); 172 | } 173 | matched = match(Program.fromSource('(r ($ . atom))'), program); 174 | if (matched && !matched['atom'].isNull) { 175 | const node = new NodePath(matched['atom'].toBigInt()).add( 176 | NodePath.right 177 | ); 178 | return Program.fromBytes(node.asPath()); 179 | } 180 | return program; 181 | } 182 | 183 | export function quoteNullOptimizer( 184 | program: Program, 185 | _evalAsProgram: Eval 186 | ): Program { 187 | const matched = match(Program.fromSource('(q . 0)'), program); 188 | if (matched) { 189 | return Program.nil; 190 | } 191 | return program; 192 | } 193 | 194 | export function applyNullOptimizer( 195 | program: Program, 196 | _evalAsProgram: Eval 197 | ): Program { 198 | const matched = match(Program.fromSource('(a 0 . (: . rest))'), program); 199 | if (matched) { 200 | return Program.nil; 201 | } 202 | return program; 203 | } 204 | 205 | export function optimizeProgram( 206 | program: Program, 207 | evalAsProgram: Eval 208 | ): Program { 209 | if (program.isAtom) { 210 | return program; 211 | } 212 | const optimizers = [ 213 | consOptimizer, 214 | constantOptimizer, 215 | consQuoteApplyOptimizer, 216 | varChangeOptimizerConsEval, 217 | childrenOptimizer, 218 | pathOptimizer, 219 | quoteNullOptimizer, 220 | applyNullOptimizer, 221 | ]; 222 | while (program.isCons) { 223 | const startProgram = program; 224 | for (const optimizer of optimizers) { 225 | program = optimizer(program, evalAsProgram); 226 | if (!startProgram.equals(program)) break; 227 | } 228 | if (startProgram.equals(program)) { 229 | return program; 230 | } 231 | } 232 | return program; 233 | } 234 | 235 | export function makeDoOpt(runProgram: Eval): Operator { 236 | return (args) => { 237 | return { 238 | value: optimizeProgram(args.first, runProgram), 239 | cost: 1n, 240 | }; 241 | }; 242 | } 243 | -------------------------------------------------------------------------------- /src/utils/parser.ts: -------------------------------------------------------------------------------- 1 | import { keywords } from '../constants/keywords'; 2 | import { ParserError } from '../types/ParserError'; 3 | import { Position } from '../types/Position'; 4 | import { Program } from '../types/Program'; 5 | import { Token } from '../types/Token'; 6 | 7 | export function next(tokens: Token[]): Token | undefined { 8 | tokens.shift(); 9 | return tokens[0]; 10 | } 11 | 12 | export function expect(source: string, tokens: Token[]): void { 13 | const token = tokens[0]; 14 | if (!next(tokens)) 15 | throw new ParserError( 16 | `Unexpected end of source at ${new Position(source, token.index)}.` 17 | ); 18 | } 19 | 20 | export function isSpace(char: string): boolean { 21 | return /^[\u0020\u202F\u205F\u2028\u2029\u3000\u0085\u1680\u00A0\u2000-\u200A\u0009-\u000D\u001C-\u001F]$/.test( 22 | char 23 | ); 24 | } 25 | 26 | export function consumeWhitespace(text: string, index: number): number { 27 | while (true) { 28 | while (index < text.length && isSpace(text[index])) index++; 29 | if (index >= text.length || text[index] !== ';') break; 30 | while (index < text.length && !'\n\r'.includes(text[index])) index++; 31 | } 32 | return index; 33 | } 34 | 35 | export function consumeUntilWhitespace(text: string, index: number): Token { 36 | const start = index; 37 | while (index < text.length && !isSpace(text[index]) && text[index] !== ')') 38 | index++; 39 | return { text: text.slice(start, index), index }; 40 | } 41 | 42 | export function tokenizeCons(source: string, tokens: Token[]): Program { 43 | let token = tokens[0]; 44 | if (token.text === ')') 45 | return Program.fromBytes(Uint8Array.from([])).at( 46 | new Position(source, token.index) 47 | ); 48 | const consStart = token.index; 49 | const first = tokenizeExpr(source, tokens); 50 | expect(source, tokens); 51 | token = tokens[0]; 52 | let rest: Program; 53 | if (token.text === '.') { 54 | const dotStart = token.index; 55 | expect(source, tokens); 56 | token = tokens[0]; 57 | rest = tokenizeExpr(source, tokens); 58 | expect(source, tokens); 59 | token = tokens[0]; 60 | if (token.text !== ')') 61 | throw new ParserError( 62 | `Illegal dot expression at ${new Position(source, dotStart)}.` 63 | ); 64 | } else rest = tokenizeCons(source, tokens); 65 | return Program.cons(first, rest).at(new Position(source, consStart)); 66 | } 67 | 68 | export function tokenizeInt(source: string, token: Token): Program | null { 69 | return /^[+\-]?[0-9]+(?:_[0-9]+)*$/.test(token.text) 70 | ? Program.fromBigInt(BigInt(token.text.replaceAll('_', ''))).at( 71 | new Position(source, token.index) 72 | ) 73 | : null; 74 | } 75 | 76 | export function tokenizeHex(source: string, token: Token): Program | null { 77 | if ( 78 | token.text.length >= 2 && 79 | token.text.slice(0, 2).toLowerCase() === '0x' 80 | ) { 81 | let hex = token.text.slice(2); 82 | if (hex.length % 2 === 1) hex = `0${hex}`; 83 | try { 84 | return Program.fromHex(hex).at(new Position(source, token.index)); 85 | } catch (e) { 86 | throw new ParserError( 87 | `Invalid hex ${JSON.stringify(token.text)} at ${new Position( 88 | source, 89 | token.index 90 | )}.` 91 | ); 92 | } 93 | } else return null; 94 | } 95 | 96 | export function tokenizeQuotes(source: string, token: Token): Program | null { 97 | if (token.text.length < 2) return null; 98 | const quote = token.text[0]; 99 | if (!'"\''.includes(quote)) return null; 100 | if (token.text[token.text.length - 1] !== quote) 101 | throw new ParserError( 102 | `Unterminated string ${JSON.stringify( 103 | token.text 104 | )} at ${new Position(source, token.index)}.` 105 | ); 106 | return Program.fromText(token.text.slice(1, token.text.length - 1)).at( 107 | new Position(source, token.index) 108 | ); 109 | } 110 | 111 | export function tokenizeSymbol(source: string, token: Token): Program | null { 112 | let text = token.text; 113 | if (text.startsWith('#')) text = text.slice(1); 114 | const keyword: bigint | undefined = keywords[text as keyof typeof keywords]; 115 | return ( 116 | keyword === undefined 117 | ? Program.fromText(text) 118 | : Program.fromBigInt(keyword) 119 | ).at(new Position(source, token.index)); 120 | } 121 | 122 | export function tokenizeExpr(source: string, tokens: Token[]): Program { 123 | const token = tokens[0]; 124 | if (token.text === '(') { 125 | expect(source, tokens); 126 | return tokenizeCons(source, tokens); 127 | } 128 | const result = 129 | tokenizeInt(source, token) ?? 130 | tokenizeHex(source, token) ?? 131 | tokenizeQuotes(source, token) ?? 132 | tokenizeSymbol(source, token); 133 | if (!result) 134 | throw new ParserError( 135 | `Invalid expression ${JSON.stringify(token.text)} at ${new Position( 136 | source, 137 | token.index 138 | )}.` 139 | ); 140 | return result; 141 | } 142 | 143 | export function* tokenStream(source: string): IterableIterator { 144 | let index = 0; 145 | while (index < source.length) { 146 | index = consumeWhitespace(source, index); 147 | if (index >= source.length) break; 148 | const char = source[index]; 149 | if ('(.)'.includes(char)) { 150 | yield { text: char, index }; 151 | index++; 152 | continue; 153 | } 154 | if ('"\''.includes(char)) { 155 | const start = index; 156 | const quote = source[index]; 157 | index++; 158 | while (index < source.length && source[index] !== quote) index++; 159 | if (index < source.length) { 160 | yield { text: source.slice(start, index + 1), index: start }; 161 | index++; 162 | continue; 163 | } else 164 | throw new ParserError( 165 | `Unterminated string at ${new Position(source, index)}.` 166 | ); 167 | } 168 | const token = consumeUntilWhitespace(source, index); 169 | yield { text: token.text, index }; 170 | index = token.index; 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /test/compile.ts: -------------------------------------------------------------------------------- 1 | import { assert, expect } from 'chai'; 2 | import { Program } from '../src'; 3 | 4 | type CompileInput = [puzzle: string, cost?: bigint, strict?: boolean]; 5 | 6 | type CompileOutput = [ 7 | output: string, 8 | cost?: bigint, 9 | dump?: boolean, 10 | showKeywords?: boolean 11 | ]; 12 | 13 | const compileTests: Map = new Map(); 14 | 15 | compileTests.set(['()'], ['()']); 16 | compileTests.set(['(list 100 200 300)'], ['(100 200 300)']); 17 | compileTests.set(['(if 1 100 200)'], ['100']); 18 | compileTests.set(['(/ 5 2)'], ['2']); 19 | compileTests.set(['(mod args (f args))'], ['2']); 20 | compileTests.set( 21 | [ 22 | '(mod () (defun factorial (number) (if (> number 2) (* number (factorial (- number 1))) number)) (factorial 5))', 23 | ], 24 | ['(q . 120)'] 25 | ); 26 | compileTests.set( 27 | ['(mod () (defconstant something "Hello") something)'], 28 | ['(q . "Hello")'] 29 | ); 30 | compileTests.set( 31 | ['(mod () (defun-inline mul (left right) (* left right)) (mul 5 10))'], 32 | ['(q . 50)'] 33 | ); 34 | compileTests.set( 35 | ['(mod () (defmacro mul (left right) (* left right)) (mul 5 10))'], 36 | ['(q . 50)', 29n] 37 | ); 38 | 39 | describe('Compile', () => { 40 | for (const [input, output] of compileTests.entries()) { 41 | const puzzle = input[0]; 42 | it(puzzle, () => { 43 | const cost = input[1]; 44 | const strict = input[2]; 45 | if (output === null) { 46 | expect(() => 47 | Program.fromSource(puzzle).compile({ 48 | maxCost: cost, 49 | strict, 50 | }) 51 | ).to.throw(); 52 | } else { 53 | const puzzleProgram = Program.fromSource(puzzle); 54 | const result = puzzleProgram.compile({ 55 | maxCost: cost, 56 | strict, 57 | }); 58 | const text = 59 | output[2] ?? false 60 | ? result.value.serializeHex() 61 | : result.value.toSource(output[3]); 62 | assert.equal(text, output[0], 'Wrong output.'); 63 | if (output[1] !== undefined) 64 | assert.equal(result.cost, output[1] + 182n, 'Wrong cost.'); 65 | } 66 | }); 67 | } 68 | }); 69 | -------------------------------------------------------------------------------- /test/deserialize.ts: -------------------------------------------------------------------------------- 1 | import { assert, expect } from 'chai'; 2 | import { Program } from '../src'; 3 | 4 | const deserializeTests: Map = new Map(); 5 | 6 | deserializeTests.set('80', '()'); 7 | deserializeTests.set('ff0101', '(q . 1)'); 8 | deserializeTests.set('ff01ff0180', '(q 1)'); 9 | deserializeTests.set('01', '1'); 10 | deserializeTests.set('85ffffabcdef', '0xffffabcdef'); 11 | deserializeTests.set('86616263646566', '"abcdef"'); 12 | deserializeTests.set( 13 | 'ff05ffff04ffff0114ffff011e8080', 14 | '(f (c (q . 20) (q . 30)))' 15 | ); 16 | deserializeTests.set( 17 | 'ff10ffbd200888489af9569930925255368b25e27749a2c3a5d54a31d90d45629b2e29348d5be73f72bf489e71df64000000000000000000000000000000000000ff8f13426172c74d822b878fe80000000080', 18 | '(+ 0x200888489af9569930925255368b25e27749a2c3a5d54a31d90d45629b2e29348d5be73f72bf489e71df64000000000000000000000000000000000000 0x13426172c74d822b878fe800000000)' 19 | ); 20 | deserializeTests.set( 21 | 'c04a4ad5c0c0203e6553d723e4e9c6861ec58934a33f237330d166d7e5b490595f999c5ae6a01836e022ecbe7b489f0584841ef8c7bb88ec9b6c63d8d9d4459c142a42632ae01a6022f08b57', 22 | '0x4ad5c0c0203e6553d723e4e9c6861ec58934a33f237330d166d7e5b490595f999c5ae6a01836e022ecbe7b489f0584841ef8c7bb88ec9b6c63d8d9d4459c142a42632ae01a6022f08b57' 23 | ); 24 | deserializeTests.set('ffffffff8080808080', '((((()))))'); 25 | 26 | describe('Deserialize', () => { 27 | for (const [input, output] of deserializeTests.entries()) { 28 | it(input, () => { 29 | if (output === null) { 30 | expect(() => Program.deserializeHex(input)).to.throw(); 31 | } else { 32 | const puzzleProgram = Program.deserializeHex(input); 33 | assert.equal(puzzleProgram.toSource(), output, 'Wrong output.'); 34 | } 35 | }); 36 | } 37 | }); 38 | -------------------------------------------------------------------------------- /test/serialize.ts: -------------------------------------------------------------------------------- 1 | import { assert, expect } from 'chai'; 2 | import { Program } from '../src'; 3 | 4 | const serializeTests: Map = new Map(); 5 | 6 | serializeTests.set('()', '80'); 7 | serializeTests.set('(q . 1)', 'ff0101'); 8 | serializeTests.set('(q . (q . ()))', 'ff01ff0180'); 9 | serializeTests.set('1', '01'); 10 | serializeTests.set('0xffffabcdef', '85ffffabcdef'); 11 | serializeTests.set('"abcdef"', '86616263646566'); 12 | serializeTests.set( 13 | '(f (c (q . 20) (q . 30)))', 14 | 'ff05ffff04ffff0114ffff011e8080' 15 | ); 16 | serializeTests.set( 17 | '(+ 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000000000000000000000000000000))', 18 | 'ff10ffbd200888489af9569930925255368b25e27749a2c3a5d54a31d90d45629b2e29348d5be73f72bf489e71df64000000000000000000000000000000000000ff8f13426172c74d822b878fe80000000080' 19 | ); 20 | serializeTests.set( 21 | '4738294723897492387408293747389479823749238749832748932748923745987326478623874623784679283747823649832756782374732864823764872364873264832764738264873648273648723648273649273687', 22 | 'c04a4ad5c0c0203e6553d723e4e9c6861ec58934a33f237330d166d7e5b490595f999c5ae6a01836e022ecbe7b489f0584841ef8c7bb88ec9b6c63d8d9d4459c142a42632ae01a6022f08b57' 23 | ); 24 | serializeTests.set('((((()))))', 'ffffffff8080808080'); 25 | 26 | describe('Serialize', () => { 27 | for (const [input, output] of serializeTests.entries()) { 28 | it(input, () => { 29 | if (output === null) { 30 | expect(() => { 31 | const puzzleProgram = Program.fromSource(input); 32 | puzzleProgram.serialize(); 33 | }).to.throw(); 34 | } else { 35 | const puzzleProgram = Program.fromSource(input); 36 | assert.equal( 37 | puzzleProgram.serializeHex(), 38 | output, 39 | 'Wrong output.' 40 | ); 41 | } 42 | }); 43 | } 44 | }); 45 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "ESNext", 5 | "module": "CommonJS", 6 | "downlevelIteration": true, 7 | "esModuleInterop": true, 8 | "declaration": true, 9 | "noImplicitAny": true, 10 | "noImplicitThis": true, 11 | "noImplicitOverride": true, 12 | "strict": true 13 | } 14 | } 15 | --------------------------------------------------------------------------------