├── .github
├── ISSUE_TEMPLATE
│ ├── a--compilation-error-or-crash.md
│ ├── b--incorrect-compilation-issue.md
│ ├── c--feature-request.md
│ └── other-issue.md
└── workflows
│ └── ci.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Cargo.lock
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── ci
├── README.md
└── publish.rs
├── crates
├── ast
│ ├── Cargo.toml
│ └── src
│ │ ├── component.rs
│ │ ├── expressions.rs
│ │ ├── lib.rs
│ │ ├── statements.rs
│ │ └── types.rs
├── codegen
│ ├── Cargo.toml
│ ├── allocator.wat
│ ├── build.rs
│ └── src
│ │ ├── builders
│ │ ├── component.rs
│ │ ├── mod.rs
│ │ └── module.rs
│ │ ├── code.rs
│ │ ├── expression.rs
│ │ ├── function.rs
│ │ ├── imports.rs
│ │ ├── lib.rs
│ │ ├── module.rs
│ │ ├── statement.rs
│ │ └── types.rs
├── common
│ ├── Cargo.toml
│ ├── src
│ │ ├── diagnostic.rs
│ │ ├── lib.rs
│ │ └── stack_map.rs
│ └── tests
│ │ └── miette.rs
├── lib
│ ├── Cargo.toml
│ ├── src
│ │ └── lib.rs
│ └── tests
│ │ ├── bad-programs
│ │ ├── adding-conflicting-types.claw
│ │ ├── adding-conflicting-types.error.txt
│ │ ├── global-without-annotation.claw
│ │ ├── global-without-annotation.error.txt
│ │ ├── global-without-initialization.claw
│ │ ├── global-without-initialization.error.txt
│ │ ├── invalid-token.claw
│ │ ├── invalid-token.error.txt
│ │ ├── modifying-immutable-global.claw
│ │ ├── modifying-immutable-global.error.txt
│ │ ├── modifying-immutable-local.claw
│ │ ├── modifying-immutable-local.error.txt
│ │ ├── param-local-type-mismatch.claw
│ │ ├── param-local-type-mismatch.error.txt
│ │ ├── using-unbound-name.claw
│ │ └── using-unbound-name.error.txt
│ │ ├── compile-error.rs
│ │ ├── programs
│ │ ├── arithmetic.claw
│ │ ├── compare.claw
│ │ ├── counter.claw
│ │ ├── factorial.claw
│ │ ├── identity.claw
│ │ ├── proxy_call.claw
│ │ ├── quadratic.claw
│ │ ├── strings.claw
│ │ ├── timer-proxy.claw
│ │ ├── unary.claw
│ │ └── wit
│ │ │ ├── claw.wit
│ │ │ └── deps
│ │ │ ├── clocks
│ │ │ └── monotonic-clock.wit
│ │ │ └── logging
│ │ │ └── logging.wit
│ │ └── runtime.rs
├── parser
│ ├── Cargo.toml
│ └── src
│ │ ├── component.rs
│ │ ├── expressions.rs
│ │ ├── lexer.rs
│ │ ├── lib.rs
│ │ ├── names.rs
│ │ ├── statements.rs
│ │ └── types.rs
└── resolver
│ ├── Cargo.toml
│ └── src
│ ├── expression.rs
│ ├── function.rs
│ ├── imports.rs
│ ├── lib.rs
│ ├── statement.rs
│ ├── types.rs
│ └── wit.rs
└── src
└── bin.rs
/.github/ISSUE_TEMPLATE/a--compilation-error-or-crash.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: A) Compilation error or crash
3 | about: Report an unexpected error or crash during compilation
4 | title: 'Compilation bug: *describe problem here*'
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 |
11 |
12 |
13 | **Reproduction case**
14 | The code you tried to compile or a minimal version of it that reproduces the error either inline as a snippet or as a link to a repository.
15 |
16 | **Compiler output**
17 | The full claw compiler error output.
18 |
19 | **Expected behavior**
20 | A clear and concise description of what you expected to happen.
21 |
22 | **Additional context**
23 | Add any other context about the problem here.
24 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/b--incorrect-compilation-issue.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: B) Incorrect compilation issue
3 | about: Report an issue with generated code
4 | title: 'Runtime bug: *describe problem here*'
5 | labels: incorrect-compilation
6 | assignees: ''
7 |
8 | ---
9 |
10 |
11 |
12 |
13 | **Reproduction case**
14 | The code you compiled or a minimal version of it that reproduces the incorrect behavior you've observed either inline as a snippet or as a link to a repository.
15 |
16 | **To Reproduce**
17 | Code for reproducing the incorrect behavior.
18 | Ideally something similar to the [claw runtime tests](https://github.com/esoterra/claw-lang/blob/main/tests/runtime.rs) using Wasmtime to instantiate the component, perform calls, and assert the expected behavior.
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Additional context**
24 | Add any other context about the problem here.
25 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/c--feature-request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: C) Feature request
3 | about: Suggest an addition to the claw compiler project
4 | title: ''
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Eg. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/other-issue.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Other issue
3 | about: For questions and issues without a dedicated template (e.g. docs problems)
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | pull_request:
7 | branches: [ "main" ]
8 |
9 | env:
10 | CARGO_TERM_COLOR: always
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v3
19 |
20 | - name: Info
21 | run: |
22 | rustc --version
23 | cargo --version
24 |
25 | - name: Build
26 | run: cargo build --workspace
27 |
28 | - name: Format
29 | run: cargo fmt --check
30 |
31 | - name: Lint
32 | run: cargo clippy -- -D warnings
33 |
34 | - name: Run tests
35 | run: cargo test --workspace
36 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | .vscode
3 |
4 | # So that files from debugging don't get committed
5 | # Only applies to claw, wat, and wasm files in root
6 | # Not e.g. crates/codegen/allocator.wat
7 | *.wat
8 | *.wasm
9 |
10 | # The compiled publish script
11 | publish
12 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting Robin Brown at [me@esoterra.dev](mailto:me@esoterra.dev). Please include in your email subject "Claw" and "CoC" or "Code of Conduct". Robin will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. Robin is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | As other maintainers join the project, Robin will divest personal oversight over CoC matters to a separate CoC team and this document will be updated. If this project becomes joins an organization, it will adopt the Code of Conduct process of that organization.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: https://www.contributor-covenant.org
46 | [version]: https://www.contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Claw
2 |
3 | #### Table of Contents
4 |
5 | * [Code of Conduct](#code-of-conduct)
6 | * [Getting Started Contributing](#getting-started-contributing)
7 |
8 | ## Code of Conduct
9 |
10 | This project and everyone participating in it is governed by the [Claw Contributor Covenant Code of Conduct][CoC]. By participating, you are expected to uphold this code. Please report unacceptable behavior to me@esoterra.dev.
11 |
12 | ## Getting Started Contributing
13 |
14 | The best way to start contributing is to become a user.
15 |
16 | As a user, you can then help by
17 |
18 | 1. Noticing problems with Claw or its docs and [filing issues][issues]
19 | * Please check if they've already been filed first!!
20 | * Focus on clear bugs, well-defined problems, obvious gaps, etc. here.
21 | 2. Participating in and starting [discussions] about potential new features
22 | * Let's keep open ended and [bikeshed]-style conversations here!
23 |
24 | Once you're familiar with the project and its code, it's a good time to look for code contributions to make.
25 |
26 | Try to find an issue with maintainer (@esoterra) approval (ideally a [good first issue]) and try to implement it.
27 |
28 | When you're ready, submit a Pull Request or Draft Pull Request and we'll take a look at it!
29 |
30 | [CoC]: ./CODE_OF_CONDUCT.md
31 | [issues]: https://github.com/esoterra/claw-lang/issues
32 | [discussions]: https://github.com/esoterra/claw-lang/discussions
33 | [bikeshed]: https://bikeshed.org/
34 | [good first issue]: https://github.com/esoterra/claw-lang/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22
35 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "claw-cli"
3 | description = "The compiler for the Claw language"
4 | readme = "README.md"
5 | version = { workspace = true }
6 | authors = { workspace = true }
7 | license = { workspace = true }
8 | edition = { workspace = true }
9 | repository = { workspace = true }
10 |
11 | [[bin]]
12 | name = "claw-cli"
13 | path = "src/bin.rs"
14 |
15 | [dependencies]
16 | claw-common = { workspace = true }
17 | claw-ast = { workspace = true }
18 | claw-parser = { workspace = true }
19 | claw-resolver = { workspace = true }
20 | claw-codegen = { workspace = true }
21 |
22 | clap = { workspace = true }
23 | thiserror = { workspace = true }
24 | miette = { workspace = true }
25 | logos = { workspace = true }
26 | wasm-encoder ={ workspace = true }
27 | cranelift-entity = { workspace = true }
28 | wat = { workspace = true }
29 | wit-parser = { workspace = true }
30 |
31 | [dev-dependencies]
32 | pretty_assertions = { workspace = true }
33 | wasmtime = { workspace = true }
34 | wasmprinter = { workspace = true }
35 |
36 | [workspace]
37 | members = [
38 | "crates/ast",
39 | "crates/codegen",
40 | "crates/common",
41 | "crates/lib",
42 | "crates/parser",
43 | "crates/resolver",
44 | ]
45 |
46 | [workspace.package]
47 | version = "0.2.6"
48 | authors = ["Robin Brown"]
49 | license = "MIT OR Apache-2.0"
50 | edition = "2018"
51 | homepage = "https://claw-lang.dev/"
52 | repository = "https://github.com/esoterra/claw-lang"
53 |
54 | [workspace.dependencies]
55 | claw-common = { path = "./crates/common", version = "0.2.6" }
56 | claw-ast = { path = "./crates/ast", version = "0.2.6" }
57 | claw-parser = { path = "./crates/parser", version = "0.2.6" }
58 | claw-resolver = { path = "./crates/resolver", version = "0.2.6" }
59 | claw-codegen = { path = "./crates/codegen", version = "0.2.6" }
60 |
61 | clap = { version = "3.0.0-rc.7", features = ["derive"] }
62 | thiserror = "1.0.30"
63 | miette = { version = "7.2.0", features = ["fancy"] }
64 | logos = "0.13.0"
65 | wasm-encoder = "0.207"
66 | cranelift-entity = "0.105.3"
67 | wat = "1.207"
68 | pretty_assertions = "1.1.0"
69 | wasmtime = "20"
70 | wasmprinter = "0.207"
71 | wit-parser = "0.207"
72 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
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 2021 Robin Brown
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 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Robin Brown
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
claw-cli
3 |
4 |
5 | The compiler for the Claw programming language
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | Claw is a programming language that compiles to Wasm Components.
21 | Values in Claw have the exact same types as Component model values and the imports/exports of a Claw source file represent a Component "World".
22 |
23 | This means that there's no bindings generators or indirection required.
24 | You can receive component values as arguments, operate on them, create them, and return them.
25 |
26 | ```js
27 | let mut counter: s64 = 0;
28 |
29 | export func increment() -> s64 {
30 | counter = counter + 1;
31 | return counter;
32 | }
33 |
34 | export func decrement() -> s64 {
35 | counter = counter - 1;
36 | return counter;
37 | }
38 | ```
39 |
40 | (support for the full range of component model values is still a WIP)
41 |
42 | ## Use Cases & Goals
43 |
44 | ### Component Testing
45 |
46 | Claw's ability to define component imports and simple logic easily will be well suited for writing Component tests.
47 |
48 | ```js
49 | import add: func(lhs: s32, rhs: s32) -> s32;
50 |
51 | export func test() -> result<(), string> {
52 | if add(1, 1) == 2 {
53 | return ok(());
54 | } else {
55 | return err("test failed");
56 | }
57 | }
58 | ```
59 |
60 | By adding a `check!(...)` builtin that returns `ok(())` when the condition is true and `err("")` when its false
61 | and a Rust-style `?` early return operator, we can make writing these tests a lot easier and make the output much better.
62 |
63 | ```js
64 | import add: func(lhs: s32, rhs: s32) -> s32;
65 |
66 | export tests: interface {
67 | func test() -> result<(), string> {
68 | check!(add(1, 1) == 2)?;
69 | ...
70 | return ok(());
71 | }
72 |
73 | ...
74 | }
75 | ```
76 |
77 | ### Adapters & Polyfills
78 |
79 | Sometimes users will have components written for one world but want to run them in another.
80 |
81 | Claw could make it easy to write simple adapters or polyfills so that users can run their existing code more places.
82 |
83 | ### Virtualizations & Mocks
84 |
85 | With components, we can achieve an incredible local dev experience where resources like message buses and key value stores
86 | can be implemented as simple components and used to run applications for testing and development.
87 |
88 | Claw can be well suited to writing simple in-memory virtualizations that make testing and development easy.
89 |
90 | ### Extensions
91 |
92 | Some applications (e.g. [database](https://docs.singlestore.com/cloud/reference/code-engine-powered-by-wasm/create-wasm-udfs/))
93 | can already be extended using Wasm and as this becomes more common users may want to write small pieces of logic that act as filters or policy,
94 | define how to process events, or implement missing math or domain functions.
95 |
96 | Claw can make writing these extensions easy while still generating really small Components that can stored, transmitted, and instantiated quickly.
97 |
98 | ### Simple Services
99 |
100 | TODO
101 |
102 | ## Relationship with Other Projects
103 |
104 | There are several projects for representing different aspects of the Component Model
105 |
106 | * [WIT](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md) - The official IDL for the Component Model
107 | * [WAC](https://github.com/peterhuene/wac/) - An extension of WIT that adds the ability to define how to wire components together
108 | * [WAVE](https://github.com/lann/wave) - A format for encoding Component-Model values in an idiomatic json-like way
109 |
110 | Claw will use WIT syntax for defining types, WAC syntax for defining composition, and WAVE syntax for literal expressions
111 | combining them all together so that it's intuitive to use these different tools.
112 |
113 | 
114 |
115 |
--------------------------------------------------------------------------------
/ci/README.md:
--------------------------------------------------------------------------------
1 | # Release Process
2 |
3 | ```
4 | rustc ci/publish.rs
5 | ./publish publish
6 | ```
--------------------------------------------------------------------------------
/ci/publish.rs:
--------------------------------------------------------------------------------
1 | //! Helper script to publish the warg suites of crates
2 | //!
3 | //! * `./publish bump` - bump crate versions in-tree
4 | //! * `./publish verify` - verify crates can be published to crates.io
5 | //! * `./publish publish` - actually publish crates to crates.io
6 |
7 | use std::collections::HashMap;
8 | use std::env;
9 | use std::fs;
10 | use std::path::{Path, PathBuf};
11 | use std::process::{Command, Stdio};
12 | use std::thread;
13 | use std::time::Duration;
14 |
15 | // note that this list must be topologically sorted by dependencies
16 | const CRATES_TO_PUBLISH: &[&str] = &[
17 | "claw-common",
18 | "claw-ast",
19 | "claw-parser",
20 | "claw-resolver",
21 | "claw-codegen",
22 | "compile-claw",
23 | "claw-cli",
24 | ];
25 |
26 | // Anything **not** mentioned in this array is required to have an `=a.b.c`
27 | // dependency requirement on it to enable breaking api changes even in "patch"
28 | // releases since everything not mentioned here is just an organizational detail
29 | // that no one else should rely on.
30 | const PUBLIC_CRATES: &[&str] = &[
31 | "claw-common",
32 | "claw-ast",
33 | "claw-parser",
34 | "claw-resolver",
35 | "claw-codegen",
36 | "compile-claw",
37 | "claw-cli",
38 | ];
39 |
40 | struct Workspace {
41 | version: String,
42 | }
43 |
44 | struct Crate {
45 | manifest: PathBuf,
46 | name: String,
47 | version: String,
48 | publish: bool,
49 | }
50 |
51 | fn main() {
52 | let mut crates = Vec::new();
53 | let root = read_crate(None, "./Cargo.toml".as_ref());
54 | let ws = Workspace {
55 | version: root.version.clone(),
56 | };
57 | crates.push(root);
58 | find_crates("crates".as_ref(), &ws, &mut crates);
59 |
60 | let pos = CRATES_TO_PUBLISH
61 | .iter()
62 | .enumerate()
63 | .map(|(i, c)| (*c, i))
64 | .collect::>();
65 | crates.sort_by_key(|krate| pos.get(&krate.name[..]));
66 |
67 | match &env::args().nth(1).expect("must have one argument")[..] {
68 | name @ "bump" | name @ "bump-patch" => {
69 | for krate in crates.iter() {
70 | bump_version(&krate, &crates, name == "bump-patch");
71 | }
72 | // update the lock file
73 | assert!(Command::new("cargo")
74 | .arg("fetch")
75 | .status()
76 | .unwrap()
77 | .success());
78 | }
79 |
80 | "publish" => {
81 | // We have so many crates to publish we're frequently either
82 | // rate-limited or we run into issues where crates can't publish
83 | // successfully because they're waiting on the index entries of
84 | // previously-published crates to propagate. This means we try to
85 | // publish in a loop and we remove crates once they're successfully
86 | // published. Failed-to-publish crates get enqueued for another try
87 | // later on.
88 | for _ in 0..10 {
89 | crates.retain(|krate| !publish(krate));
90 |
91 | if crates.is_empty() {
92 | break;
93 | }
94 |
95 | println!(
96 | "{} crates failed to publish, waiting for a bit to retry",
97 | crates.len(),
98 | );
99 | thread::sleep(Duration::from_secs(40));
100 | }
101 |
102 | assert!(crates.is_empty(), "failed to publish all crates");
103 |
104 | println!("");
105 | }
106 |
107 | "verify" => {
108 | verify(&crates);
109 | }
110 |
111 | s => panic!("unknown command: {}", s),
112 | }
113 | }
114 |
115 | fn find_crates(dir: &Path, ws: &Workspace, dst: &mut Vec) {
116 | if dir.join("Cargo.toml").exists() {
117 | let krate = read_crate(Some(ws), &dir.join("Cargo.toml"));
118 | if !krate.publish || CRATES_TO_PUBLISH.iter().any(|c| krate.name == *c) {
119 | dst.push(krate);
120 | } else {
121 | panic!("failed to find {:?} in whitelist or blacklist", krate.name);
122 | }
123 | }
124 |
125 | for entry in dir.read_dir().unwrap() {
126 | let entry = entry.unwrap();
127 | if entry.file_type().unwrap().is_dir() {
128 | find_crates(&entry.path(), ws, dst);
129 | }
130 | }
131 | }
132 |
133 | fn read_crate(ws: Option<&Workspace>, manifest: &Path) -> Crate {
134 | let mut name = None;
135 | let mut version = None;
136 | let mut publish = true;
137 | for line in fs::read_to_string(manifest).unwrap().lines() {
138 | if name.is_none() && line.starts_with("name = \"") {
139 | name = Some(
140 | line.replace("name = \"", "")
141 | .replace("\"", "")
142 | .trim()
143 | .to_string(),
144 | );
145 | }
146 | if version.is_none() && line.starts_with("version = \"") {
147 | version = Some(
148 | line.replace("version = \"", "")
149 | .replace("\"", "")
150 | .trim()
151 | .to_string(),
152 | );
153 | }
154 | if let Some(ws) = ws {
155 | if version.is_none() && (line.starts_with("version.workspace = true") || line.starts_with("version = { workspace = true }")) {
156 | version = Some(ws.version.clone());
157 | }
158 | }
159 | if line.starts_with("publish = false") {
160 | publish = false;
161 | }
162 | }
163 | let name = name.unwrap();
164 | let version = version.unwrap();
165 | Crate {
166 | manifest: manifest.to_path_buf(),
167 | name,
168 | version,
169 | publish,
170 | }
171 | }
172 |
173 | fn bump_version(krate: &Crate, crates: &[Crate], patch: bool) {
174 | let contents = fs::read_to_string(&krate.manifest).unwrap();
175 | let next_version = |krate: &Crate| -> String {
176 | if CRATES_TO_PUBLISH.contains(&&krate.name[..]) {
177 | bump(&krate.version, patch)
178 | } else {
179 | krate.version.clone()
180 | }
181 | };
182 |
183 | let mut new_manifest = String::new();
184 | let mut is_deps = false;
185 | for line in contents.lines() {
186 | let mut rewritten = false;
187 | if !is_deps && line.starts_with("version =") {
188 | if CRATES_TO_PUBLISH.contains(&&krate.name[..]) {
189 | println!(
190 | "bump `{}` {} => {}",
191 | krate.name,
192 | krate.version,
193 | next_version(krate),
194 | );
195 | new_manifest.push_str(&line.replace(&krate.version, &next_version(krate)));
196 | rewritten = true;
197 | }
198 | }
199 |
200 | is_deps = if line.starts_with("[") {
201 | line.contains("dependencies")
202 | } else {
203 | is_deps
204 | };
205 |
206 | for other in crates {
207 | // If `other` isn't a published crate then it's not going to get a
208 | // bumped version so we don't need to update anything in the
209 | // manifest.
210 | if !other.publish {
211 | continue;
212 | }
213 | if !is_deps || !line.starts_with(&format!("{} ", other.name)) {
214 | continue;
215 | }
216 | if !line.contains(&other.version) {
217 | if !line.contains("version =") || !krate.publish {
218 | continue;
219 | }
220 | panic!(
221 | "{:?} has a dep on {} but doesn't list version {}",
222 | krate.manifest, other.name, other.version
223 | );
224 | }
225 | if krate.publish {
226 | if PUBLIC_CRATES.contains(&other.name.as_str()) {
227 | assert!(
228 | !line.contains("\"="),
229 | "{} should not have an exact version requirement on {}",
230 | krate.name,
231 | other.name
232 | );
233 | } else {
234 | assert!(
235 | line.contains("\"="),
236 | "{} should have an exact version requirement on {}",
237 | krate.name,
238 | other.name
239 | );
240 | }
241 | }
242 | rewritten = true;
243 | new_manifest.push_str(&line.replace(&other.version, &next_version(other)));
244 | break;
245 | }
246 | if !rewritten {
247 | new_manifest.push_str(line);
248 | }
249 | new_manifest.push_str("\n");
250 | }
251 | fs::write(&krate.manifest, new_manifest).unwrap();
252 | }
253 |
254 | /// Performs a major version bump increment on the semver version `version`.
255 | ///
256 | /// This function will perform a semver-major-version bump on the `version`
257 | /// specified. This is used to calculate the next version of a crate in this
258 | /// repository since we're currently making major version bumps for all our
259 | /// releases. This may end up getting tweaked as we stabilize crates and start
260 | /// doing more minor/patch releases, but for now this should do the trick.
261 | fn bump(version: &str, patch_bump: bool) -> String {
262 | let mut iter = version.split('.').map(|s| s.parse::().unwrap());
263 | let major = iter.next().expect("major version");
264 | let minor = iter.next().expect("minor version");
265 | let patch = iter.next().expect("patch version");
266 |
267 | if patch_bump {
268 | return format!("{}.{}.{}", major, minor, patch + 1);
269 | }
270 | if major != 0 {
271 | format!("{}.0.0", major + 1)
272 | } else if minor != 0 {
273 | format!("0.{}.0", minor + 1)
274 | } else {
275 | format!("0.0.{}", patch + 1)
276 | }
277 | }
278 |
279 | fn publish(krate: &Crate) -> bool {
280 | if !CRATES_TO_PUBLISH.iter().any(|s| *s == krate.name) {
281 | return true;
282 | }
283 |
284 | // First make sure the crate isn't already published at this version. This
285 | // script may be re-run and there's no need to re-attempt previous work.
286 | let output = Command::new("curl")
287 | .arg(&format!("https://crates.io/api/v1/crates/{}", krate.name))
288 | .output()
289 | .expect("failed to invoke `curl`");
290 | if output.status.success()
291 | && String::from_utf8_lossy(&output.stdout)
292 | .contains(&format!("\"newest_version\":\"{}\"", krate.version))
293 | {
294 | println!(
295 | "skip publish {} because {} is latest version",
296 | krate.name, krate.version,
297 | );
298 | return true;
299 | }
300 |
301 | let status = Command::new("cargo")
302 | .arg("publish")
303 | .current_dir(krate.manifest.parent().unwrap())
304 | .arg("--no-verify")
305 | .status()
306 | .expect("failed to run cargo");
307 | if !status.success() {
308 | println!("FAIL: failed to publish `{}`: {}", krate.name, status);
309 | return false;
310 | }
311 |
312 | true
313 | }
314 |
315 | // Verify the current tree is publish-able to crates.io. The intention here is
316 | // that we'll run `cargo package` on everything which verifies the build as-if
317 | // it were published to crates.io. This requires using an incrementally-built
318 | // directory registry generated from `cargo vendor` because the versions
319 | // referenced from `Cargo.toml` may not exist on crates.io.
320 | fn verify(crates: &[Crate]) {
321 | drop(fs::remove_dir_all(".cargo"));
322 | drop(fs::remove_dir_all("vendor"));
323 | let vendor = Command::new("cargo")
324 | .arg("vendor")
325 | .stderr(Stdio::inherit())
326 | .output()
327 | .unwrap();
328 | assert!(vendor.status.success());
329 |
330 | fs::create_dir_all(".cargo").unwrap();
331 | fs::write(".cargo/config.toml", vendor.stdout).unwrap();
332 |
333 | for krate in crates {
334 | if !krate.publish {
335 | continue;
336 | }
337 | verify_and_vendor(&krate);
338 | }
339 |
340 | fn verify_and_vendor(krate: &Crate) {
341 | let mut cmd = Command::new("cargo");
342 | cmd.arg("package")
343 | .arg("--manifest-path")
344 | .arg(&krate.manifest)
345 | .env("CARGO_TARGET_DIR", "./target");
346 | let status = cmd.status().unwrap();
347 | assert!(status.success(), "failed to verify {:?}", &krate.manifest);
348 | let tar = Command::new("tar")
349 | .arg("xf")
350 | .arg(format!(
351 | "../target/package/{}-{}.crate",
352 | krate.name, krate.version
353 | ))
354 | .current_dir("./vendor")
355 | .status()
356 | .unwrap();
357 | assert!(tar.success());
358 | fs::write(
359 | format!(
360 | "./vendor/{}-{}/.cargo-checksum.json",
361 | krate.name, krate.version
362 | ),
363 | "{\"files\":{}}",
364 | )
365 | .unwrap();
366 | }
367 | }
368 |
--------------------------------------------------------------------------------
/crates/ast/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "claw-ast"
3 | description = "The Claw language Abstract Syntax Tree (AST)"
4 | version = { workspace = true }
5 | authors = { workspace = true }
6 | license = { workspace = true }
7 | edition = { workspace = true }
8 | repository = { workspace = true }
9 |
10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
11 |
12 | [dependencies]
13 | miette = { workspace = true }
14 | claw-common = { workspace = true }
15 | cranelift-entity = { workspace = true }
16 | wit-parser = { workspace = true }
17 |
--------------------------------------------------------------------------------
/crates/ast/src/component.rs:
--------------------------------------------------------------------------------
1 | //! Contains the [Component] struct which is the root
2 | //! of the AST and contains root items (e.g. import, function),
3 | //! inner AST nodes (e.g. expression), and the source code.
4 |
5 | use std::collections::HashMap;
6 |
7 | use cranelift_entity::{entity_impl, PrimaryMap};
8 |
9 | use crate::PackageName;
10 | use claw_common::Source;
11 |
12 | use super::{
13 | expressions::{Expression, ExpressionId},
14 | statements::{Statement, StatementId},
15 | types::{FnType, TypeDefId, TypeDefinition},
16 | NameId, Span, TypeId, ValType,
17 | };
18 |
19 | /// The unique ID of an Import item
20 | ///
21 | /// IDs must only be passed to the [Component] they were
22 | /// made by and this is not statically or dynamically validated.
23 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
24 | pub struct ImportId(u32);
25 | entity_impl!(ImportId, "import");
26 |
27 | /// The unique ID of a Global item
28 | ///
29 | /// IDs must only be passed to the [Component] they were
30 | /// made by and this is not statically or dynamically validated.
31 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
32 | pub struct GlobalId(u32);
33 | entity_impl!(GlobalId, "global");
34 |
35 | /// The unique ID of a Function item
36 | ///
37 | /// IDs must only be passed to the [Component] they were
38 | /// made by and this is not statically or dynamically validated.
39 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
40 | pub struct FunctionId(u32);
41 | entity_impl!(FunctionId, "func");
42 |
43 | /// Each Claw source file represents a Component
44 | /// and this struct represents the root of the AST.
45 | ///
46 | /// The different types of AST nodes each have a unique ID type,
47 | /// so it is impossible to try to retrieve an import as a function.
48 | ///
49 | /// No static or dynamic validation that an ID is from the correct
50 | /// AST is performed and if an ID from one AST is provided to another
51 | /// bad things will happen!
52 | #[derive(Debug)]
53 | pub struct Component {
54 | /// The source text that the component was created from.
55 | src: Source,
56 |
57 | // Top level items
58 | imports: PrimaryMap,
59 | type_defs: PrimaryMap,
60 | globals: PrimaryMap,
61 | functions: PrimaryMap,
62 |
63 | // Inner items
64 | types: PrimaryMap,
65 | type_spans: HashMap,
66 |
67 | statements: PrimaryMap,
68 | statement_spans: HashMap,
69 |
70 | expressions: PrimaryMap,
71 | expression_spans: HashMap,
72 |
73 | names: PrimaryMap,
74 | name_spans: HashMap,
75 | }
76 |
77 | impl Component {
78 | /// Create a new empty Component AST for a source file.
79 | ///
80 | /// This does not do any parsing!!!
81 | pub fn new(src: Source) -> Self {
82 | Self {
83 | src,
84 | imports: Default::default(),
85 | type_defs: Default::default(),
86 | globals: Default::default(),
87 | functions: Default::default(),
88 | types: Default::default(),
89 | type_spans: Default::default(),
90 | statements: Default::default(),
91 | statement_spans: Default::default(),
92 | expressions: Default::default(),
93 | expression_spans: Default::default(),
94 | names: Default::default(),
95 | name_spans: Default::default(),
96 | }
97 | }
98 |
99 | /// The source code that the AST represents.
100 | pub fn source(&self) -> Source {
101 | self.src.clone()
102 | }
103 |
104 | /// Add a top-level import item to the AST.
105 | pub fn push_import(&mut self, import: Import) -> ImportId {
106 | self.imports.push(import)
107 | }
108 |
109 | /// Iterate over the top-level import items.
110 | pub fn iter_imports(&self) -> impl Iterator {
111 | self.imports.iter()
112 | }
113 |
114 | /// Get a specific import item by its id.
115 | pub fn get_import(&self, import: ImportId) -> &Import {
116 | &self.imports[import]
117 | }
118 |
119 | /// Add a top-level type definition item to the AST.
120 | pub fn push_type_def(&mut self, type_def: TypeDefinition) -> TypeDefId {
121 | self.type_defs.push(type_def)
122 | }
123 |
124 | /// Iterate over the top-level type definition items.
125 | pub fn iter_type_defs(&self) -> impl Iterator {
126 | self.type_defs.iter()
127 | }
128 |
129 | /// Get a specific type definition item by its id.
130 | pub fn get_type_def(&self, type_def: TypeDefId) -> &TypeDefinition {
131 | &self.type_defs[type_def]
132 | }
133 |
134 | /// Add a top-level global item to the AST.
135 | pub fn push_global(&mut self, global: Global) -> GlobalId {
136 | self.globals.push(global)
137 | }
138 |
139 | /// Iterate over the top-level global items.
140 | pub fn iter_globals(&self) -> impl Iterator {
141 | self.globals.iter()
142 | }
143 |
144 | /// Get a specific global item by its id.
145 | pub fn get_global(&self, global: GlobalId) -> &Global {
146 | &self.globals[global]
147 | }
148 |
149 | /// Add a top-level function item to the AST.
150 | pub fn push_function(&mut self, function: Function) -> FunctionId {
151 | self.functions.push(function)
152 | }
153 |
154 | /// Iterate over the top-level function items.
155 | pub fn iter_functions(&self) -> impl Iterator {
156 | self.functions.iter()
157 | }
158 |
159 | /// Get a specific function item by its id.
160 | pub fn get_function(&self, function: FunctionId) -> &Function {
161 | &self.functions[function]
162 | }
163 |
164 | /// Create a new name AST node.
165 | pub fn new_name(&mut self, name: String, span: Span) -> NameId {
166 | let id = self.names.push(name);
167 | self.name_spans.insert(id, span);
168 | id
169 | }
170 |
171 | /// Get the value of a name.
172 | pub fn get_name(&self, id: NameId) -> &str {
173 | self.names.get(id).unwrap()
174 | }
175 |
176 | /// Get the source span for this name.
177 | pub fn name_span(&self, id: NameId) -> Span {
178 | *self.name_spans.get(&id).unwrap()
179 | }
180 |
181 | /// Create a new valtype AST node.
182 | pub fn new_type(&mut self, valtype: ValType, span: Span) -> TypeId {
183 | let id = self.types.push(valtype);
184 | self.type_spans.insert(id, span);
185 | id
186 | }
187 |
188 | /// Get the value of a valtype AST node.
189 | pub fn get_type(&self, id: TypeId) -> &ValType {
190 | self.types.get(id).unwrap()
191 | }
192 |
193 | /// Get the source span for this valtype.
194 | pub fn type_span(&self, id: TypeId) -> Span {
195 | *self.type_spans.get(&id).unwrap()
196 | }
197 |
198 | /// Create a new statement AST node.
199 | pub fn new_statement(&mut self, statement: Statement, span: Span) -> StatementId {
200 | let id = self.statements.push(statement);
201 | self.statement_spans.insert(id, span);
202 | id
203 | }
204 |
205 | /// Get the value of a statement AST node.
206 | pub fn get_statement(&self, id: StatementId) -> &Statement {
207 | self.statements.get(id).unwrap()
208 | }
209 |
210 | /// Get the source span for this statement.
211 | pub fn statement_span(&self, id: StatementId) -> Span {
212 | *self.statement_spans.get(&id).unwrap()
213 | }
214 |
215 | /// Create a new expression AST node.
216 | pub fn new_expression(&mut self, expression: Expression, span: Span) -> ExpressionId {
217 | let id = self.expressions.push(expression);
218 | self.expression_spans.insert(id, span);
219 | id
220 | }
221 |
222 | /// Get the value of a expression AST node.
223 | pub fn get_expression(&self, id: ExpressionId) -> &Expression {
224 | self.expressions.get(id).unwrap()
225 | }
226 |
227 | /// Get the source span for this expression.
228 | pub fn expression_span(&self, id: ExpressionId) -> Span {
229 | *self.expression_spans.get(&id).unwrap()
230 | }
231 | }
232 |
233 | /// Import AST node (Claw)
234 | ///
235 | /// There are two versions: plain and import-from.
236 | #[derive(Debug, PartialEq, Eq, Clone)]
237 | pub enum Import {
238 | Plain(PlainImport),
239 | ImportFrom(ImportFrom),
240 | }
241 |
242 | /// Plain Import AST node (Claw)
243 | ///
244 | /// ```claw
245 | /// import foo: func() -> u32;
246 | /// ```
247 | #[derive(Debug, PartialEq, Eq, Clone)]
248 | pub struct PlainImport {
249 | /// The name of the item to import.
250 | pub ident: NameId,
251 | /// The name given to the imported item.
252 | /// Defaults to the specified name if omitted.
253 | pub alias: Option,
254 | /// The type of the imported item.
255 | pub external_type: ExternalType,
256 | }
257 |
258 | /// Import From AST node (Claw)
259 | ///
260 | /// ```claw
261 | /// import { foo } from bar;
262 | /// ```
263 | #[derive(Debug, PartialEq, Eq, Clone)]
264 | pub struct ImportFrom {
265 | /// The first name is the imported item's name
266 | /// The second optional name is an alias
267 | pub items: Vec<(NameId, Option)>,
268 | /// The package being imported from
269 | pub package: PackageName,
270 | /// Which interface from the package to import
271 | pub interface: String,
272 | }
273 |
274 | /// External Type AST node (Claw)
275 | ///
276 | /// ```claw
277 | /// func(foo: string) -> bool
278 | /// ```
279 | #[derive(Debug, PartialEq, Eq, Clone)]
280 | pub enum ExternalType {
281 | Function(FnType),
282 | }
283 |
284 | /// Global Item AST node (Claw)
285 | ///
286 | /// ```claw
287 | /// let foo: u32 = 1;
288 | /// ```
289 | #[derive(Debug, Clone)]
290 | pub struct Global {
291 | /// Whether the global is exported.
292 | ///
293 | /// Indicated by the keyword `export` in front
294 | /// of the global item.
295 | pub exported: bool,
296 | /// Whether the global is mutable.
297 | ///
298 | /// Indicated by the `mut` keyword before after `let`.
299 | pub mutable: bool,
300 | /// The name of the global.
301 | pub ident: NameId,
302 | /// The type of the global.
303 | pub type_id: TypeId,
304 | /// The initialization expression for the global.
305 | pub init_value: ExpressionId,
306 | }
307 |
308 | /// Function Item AST node (Claw)
309 | ///
310 | /// ```claw
311 | /// func always-false() -> bool {
312 | /// return false;
313 | /// }
314 | /// ```
315 | #[derive(Debug)]
316 | pub struct Function {
317 | /// Whether the global is exported.
318 | ///
319 | /// Indicated by the keyword `export` in front
320 | /// of the function item.
321 | pub exported: bool,
322 | /// The name of the function.
323 | pub ident: NameId,
324 | /// The function's parameters.
325 | ///
326 | /// Each parameter has a name and type.
327 | pub params: Vec<(NameId, TypeId)>,
328 | /// The result type of the function.
329 | ///
330 | /// Result type is unit if omitted.
331 | pub results: Option,
332 | /// The body of the function.
333 | pub body: Vec,
334 | }
335 |
--------------------------------------------------------------------------------
/crates/ast/src/expressions.rs:
--------------------------------------------------------------------------------
1 | use super::NameId;
2 | use cranelift_entity::entity_impl;
3 |
4 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
5 | pub struct ExpressionId(u32);
6 | entity_impl!(ExpressionId, "expression");
7 |
8 | pub trait ContextEq {
9 | fn context_eq(&self, other: &Self, context: &Context) -> bool;
10 | }
11 |
12 | #[derive(Debug, PartialEq, Clone)]
13 | pub enum Expression {
14 | Identifier(Identifier),
15 | Enum(EnumLiteral),
16 | Literal(Literal),
17 | Call(Call),
18 | Unary(UnaryExpression),
19 | Binary(BinaryExpression),
20 | }
21 |
22 | impl ContextEq for ExpressionId {
23 | fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
24 | let self_span = context.expression_span(*self);
25 | let other_span = context.expression_span(*other);
26 | if self_span != other_span {
27 | dbg!(self_span, other_span);
28 | return false;
29 | }
30 |
31 | let self_expr = context.get_expression(*self);
32 | let other_expr = context.get_expression(*other);
33 | if !self_expr.context_eq(other_expr, context) {
34 | dbg!(self_expr, other_expr);
35 | return false;
36 | }
37 | true
38 | }
39 | }
40 |
41 | impl ContextEq for Expression {
42 | fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
43 | match (self, other) {
44 | (Expression::Identifier(left), Expression::Identifier(right)) => {
45 | left.context_eq(right, context)
46 | }
47 | (Expression::Literal(left), Expression::Literal(right)) => {
48 | left.context_eq(right, context)
49 | }
50 | (Expression::Call(left), Expression::Call(right)) => left.context_eq(right, context),
51 | (Expression::Unary(left), Expression::Unary(right)) => left.context_eq(right, context),
52 | (Expression::Binary(left), Expression::Binary(right)) => {
53 | left.context_eq(right, context)
54 | }
55 | _ => false,
56 | }
57 | }
58 | }
59 |
60 | #[derive(Debug, PartialEq, Clone)]
61 | pub struct Identifier {
62 | pub ident: NameId,
63 | }
64 |
65 | impl From for Expression {
66 | fn from(val: Identifier) -> Self {
67 | Expression::Identifier(val)
68 | }
69 | }
70 |
71 | impl ContextEq for Identifier {
72 | fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
73 | context.get_name(self.ident) == context.get_name(other.ident)
74 | }
75 | }
76 |
77 | #[derive(Debug, PartialEq, Clone)]
78 | pub struct EnumLiteral {
79 | pub enum_name: NameId,
80 | pub case_name: NameId,
81 | }
82 |
83 | impl From for Expression {
84 | fn from(val: EnumLiteral) -> Self {
85 | Expression::Enum(val)
86 | }
87 | }
88 |
89 | impl ContextEq for EnumLiteral {
90 | fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
91 | context.get_name(self.enum_name) == context.get_name(other.enum_name)
92 | && context.get_name(self.case_name) == context.get_name(other.case_name)
93 | }
94 | }
95 |
96 | #[derive(Debug, PartialEq, Clone)]
97 | pub enum Literal {
98 | Integer(u64),
99 | Float(f64),
100 | String(String),
101 | }
102 |
103 | impl From for Expression {
104 | fn from(val: Literal) -> Self {
105 | Expression::Literal(val)
106 | }
107 | }
108 |
109 | impl ContextEq for Literal {
110 | fn context_eq(&self, other: &Self, _context: &super::Component) -> bool {
111 | self == other
112 | }
113 | }
114 |
115 | #[derive(Debug, PartialEq, Clone)]
116 | pub struct Call {
117 | pub ident: NameId,
118 | pub args: Vec,
119 | }
120 |
121 | impl From for Expression {
122 | fn from(val: Call) -> Self {
123 | Expression::Call(val)
124 | }
125 | }
126 |
127 | impl ContextEq for Call {
128 | fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
129 | let ident_eq = self.ident.context_eq(&other.ident, context);
130 | let args_eq = self
131 | .args
132 | .iter()
133 | .zip(other.args.iter())
134 | .map(|(l, r)| l.context_eq(r, context))
135 | .all(|v| v);
136 |
137 | ident_eq && args_eq
138 | }
139 | }
140 |
141 | // Unary Operators
142 |
143 | #[derive(Debug, PartialEq, Clone, Copy)]
144 | pub enum UnaryOp {
145 | Negate,
146 | }
147 |
148 | #[derive(Debug, PartialEq, Clone)]
149 | pub struct UnaryExpression {
150 | pub op: UnaryOp,
151 | pub inner: ExpressionId,
152 | }
153 |
154 | impl From for Expression {
155 | fn from(val: UnaryExpression) -> Self {
156 | Expression::Unary(val)
157 | }
158 | }
159 |
160 | impl ContextEq for UnaryExpression {
161 | fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
162 | let self_inner = context.get_expression(self.inner);
163 | let other_inner = context.get_expression(other.inner);
164 | self_inner.context_eq(other_inner, context)
165 | }
166 | }
167 |
168 | // Binary Operators
169 |
170 | #[derive(Debug, PartialEq, Clone, Copy)]
171 | pub enum BinaryOp {
172 | // Arithmetic Operations
173 | Multiply,
174 | Divide,
175 | Modulo,
176 | Add,
177 | Subtract,
178 |
179 | // Shifting Operations
180 | BitShiftL,
181 | BitShiftR,
182 | ArithShiftR,
183 |
184 | // Comparisons
185 | LessThan,
186 | LessThanEqual,
187 | GreaterThan,
188 | GreaterThanEqual,
189 | Equals,
190 | NotEquals,
191 |
192 | // Bitwise Operations
193 | BitOr,
194 | BitXor,
195 | BitAnd,
196 |
197 | // Logical Operations
198 | LogicalOr,
199 | LogicalAnd,
200 | }
201 |
202 | #[derive(Debug, PartialEq, Clone)]
203 | pub struct BinaryExpression {
204 | pub op: BinaryOp,
205 | pub left: ExpressionId,
206 | pub right: ExpressionId,
207 | }
208 |
209 | impl From for Expression {
210 | fn from(val: BinaryExpression) -> Self {
211 | Expression::Binary(val)
212 | }
213 | }
214 |
215 | impl ContextEq for BinaryExpression {
216 | fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
217 | let self_left = context.get_expression(self.left);
218 | let other_left = context.get_expression(other.left);
219 | let left_eq = self_left.context_eq(other_left, context);
220 |
221 | let self_right = context.get_expression(self.right);
222 | let other_right = context.get_expression(other.right);
223 | let right_eq = self_right.context_eq(other_right, context);
224 |
225 | left_eq && right_eq
226 | }
227 | }
228 |
229 | impl BinaryExpression {
230 | pub fn is_relation(&self) -> bool {
231 | use BinaryOp as BE;
232 | matches!(
233 | self.op,
234 | BE::LessThan
235 | | BE::LessThanEqual
236 | | BE::GreaterThan
237 | | BE::GreaterThanEqual
238 | | BE::Equals
239 | | BE::NotEquals
240 | )
241 | }
242 | }
243 |
--------------------------------------------------------------------------------
/crates/ast/src/lib.rs:
--------------------------------------------------------------------------------
1 | pub mod component;
2 | pub mod expressions;
3 | pub mod statements;
4 | pub mod types;
5 |
6 | use cranelift_entity::entity_impl;
7 | use miette::SourceSpan;
8 |
9 | pub use wit_parser::PackageName;
10 |
11 | pub type Span = SourceSpan;
12 |
13 | pub use component::*;
14 | pub use expressions::*;
15 | pub use statements::*;
16 | pub use types::*;
17 |
18 | pub fn merge(left: &Span, right: &Span) -> Span {
19 | let left_most = left.offset();
20 | let right_most = right.offset() + right.len();
21 | let len = right_most - left_most;
22 | Span::from((left_most, len))
23 | }
24 |
25 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
26 | pub struct NameId(u32);
27 | entity_impl!(NameId, "name");
28 |
29 | impl ContextEq for NameId {
30 | fn context_eq(&self, other: &Self, context: &Component) -> bool {
31 | let self_str = context.get_name(*self);
32 | let other_str = context.get_name(*other);
33 | let str_eq = self_str == other_str;
34 |
35 | let self_span = context.name_span(*self);
36 | let other_span = context.name_span(*other);
37 | let span_eq = self_span == other_span;
38 |
39 | str_eq && span_eq
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/crates/ast/src/statements.rs:
--------------------------------------------------------------------------------
1 | use cranelift_entity::entity_impl;
2 |
3 | use super::{expressions::ExpressionId, types::TypeId, Call, NameId};
4 |
5 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
6 | pub struct StatementId(u32);
7 | entity_impl!(StatementId, "name");
8 |
9 | #[derive(Debug, PartialEq, Clone)]
10 | pub enum Statement {
11 | Let(Let),
12 | Assign(Assign),
13 | Call(Call),
14 | If(If),
15 | Return(Return),
16 | }
17 |
18 | #[derive(Debug, PartialEq, Clone)]
19 | pub struct Let {
20 | pub mutable: bool,
21 | pub ident: NameId,
22 | pub annotation: Option,
23 | pub expression: ExpressionId,
24 | }
25 |
26 | #[derive(Debug, PartialEq, Clone)]
27 | pub struct Assign {
28 | pub ident: NameId,
29 | pub expression: ExpressionId,
30 | }
31 |
32 | #[derive(Debug, PartialEq, Clone)]
33 | pub struct If {
34 | pub condition: ExpressionId,
35 | pub block: Vec,
36 | }
37 |
38 | #[derive(Debug, PartialEq, Clone)]
39 | pub struct Return {
40 | pub expression: Option,
41 | }
42 |
--------------------------------------------------------------------------------
/crates/ast/src/types.rs:
--------------------------------------------------------------------------------
1 | use cranelift_entity::entity_impl;
2 |
3 | use super::{Component, NameId};
4 |
5 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
6 | pub struct TypeId(u32);
7 | entity_impl!(TypeId, "type");
8 |
9 | #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
10 | pub struct TypeDefId(u32);
11 | entity_impl!(TypeDefId, "typedef");
12 |
13 | /// The type for all values
14 | #[derive(Debug, Hash, Clone)]
15 | pub enum ValType {
16 | Result(ResultType),
17 | Primitive(PrimitiveType),
18 | }
19 |
20 | #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
21 | pub enum PrimitiveType {
22 | // The boolean type
23 | Bool,
24 | // 8-bit Integers
25 | U8,
26 | S8,
27 | // 16-bit Integers
28 | U16,
29 | S16,
30 | // 32-bit Integers
31 | U32,
32 | S32,
33 | // 64-bit Integers
34 | U64,
35 | S64,
36 | // Floating Point Numbers
37 | F32,
38 | F64,
39 | // String type
40 | String,
41 | }
42 |
43 | #[derive(Debug, Hash, Clone)]
44 | pub struct ResultType {
45 | pub ok: TypeId,
46 | pub err: TypeId,
47 | }
48 |
49 | impl ValType {
50 | pub fn eq(&self, other: &Self, comp: &Component) -> bool {
51 | match (self, other) {
52 | (ValType::Result(left), ValType::Result(right)) => {
53 | let l_ok = comp.get_type(left.ok);
54 | let r_ok = comp.get_type(right.ok);
55 | let ok_eq = l_ok.eq(r_ok, comp);
56 |
57 | let l_err = comp.get_type(left.err);
58 | let r_err = comp.get_type(right.err);
59 | let err_eq = l_err.eq(r_err, comp);
60 |
61 | ok_eq && err_eq
62 | }
63 | (ValType::Primitive(left), ValType::Primitive(right)) => left == right,
64 | _ => false,
65 | }
66 | }
67 | }
68 |
69 | #[derive(Debug, PartialEq, Eq, Hash, Clone)]
70 | pub enum TypeDefinition {
71 | Record(RecordTypeDef),
72 | }
73 |
74 | #[derive(Debug, PartialEq, Eq, Hash, Clone)]
75 | pub struct RecordTypeDef {
76 | fields: Vec<(NameId, TypeId)>,
77 | }
78 |
79 | #[derive(Debug, PartialEq, Eq, Hash, Clone)]
80 | pub struct FnType {
81 | pub params: Vec<(NameId, TypeId)>,
82 | pub results: Option,
83 | }
84 |
--------------------------------------------------------------------------------
/crates/codegen/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "claw-codegen"
3 | description = "The Claw language Wasm code generator"
4 | version = { workspace = true }
5 | authors = { workspace = true }
6 | license = { workspace = true }
7 | edition = { workspace = true }
8 | repository = { workspace = true }
9 |
10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
11 |
12 | [dependencies]
13 | miette = { workspace = true }
14 | thiserror = { workspace = true }
15 | claw-ast = { workspace = true }
16 | claw-resolver = { workspace = true }
17 | wasm-encoder = { workspace = true }
18 | cranelift-entity = { workspace = true }
19 | wat = { workspace = true }
20 |
21 | [build-dependencies]
22 | wat = { workspace = true }
23 |
--------------------------------------------------------------------------------
/crates/codegen/allocator.wat:
--------------------------------------------------------------------------------
1 | (module
2 | (memory $memory (export "memory") 1)
3 | (global $last (mut i32) (i32.const 8))
4 | (func $realloc (export "realloc")
5 | (param $old_ptr i32)
6 | (param $old_size i32)
7 | (param $align i32)
8 | (param $new_size i32)
9 | (result i32)
10 | (local $ret i32)
11 | ;; Test if the old pointer is non-null
12 | local.get $old_ptr
13 | if
14 | ;; If the old size is bigger than the new size then
15 | ;; this is a shrink and transparently allow it
16 | local.get $old_size
17 | local.get $new_size
18 | i32.gt_u
19 | if
20 | local.get $old_ptr
21 | return
22 | end
23 | ;; otherwise fall through to allocate a new chunk which will later
24 | ;; copy data over
25 | end
26 | ;; align up `$last`
27 | (global.set $last
28 | (i32.and
29 | (i32.add
30 | (global.get $last)
31 | (i32.add
32 | (local.get $align)
33 | (i32.const -1)))
34 | (i32.xor
35 | (i32.add
36 | (local.get $align)
37 | (i32.const -1))
38 | (i32.const -1))))
39 | ;; save the current value of `$last` as the return value
40 | global.get $last
41 | local.set $ret
42 | ;; bump our pointer
43 | (global.set $last
44 | (i32.add
45 | (global.get $last)
46 | (local.get $new_size)))
47 | ;; while `memory.size` is less than `$last`, grow memory
48 | ;; by one page
49 | (loop $loop
50 | (if
51 | (i32.lt_u
52 | (i32.mul (memory.size) (i32.const 65536))
53 | (global.get $last))
54 | (then
55 | i32.const 1
56 | memory.grow
57 | ;; test to make sure growth succeeded
58 | i32.const -1
59 | i32.eq
60 | if unreachable end
61 | br $loop)))
62 | ;; ensure anything necessary is set to valid data by spraying a bit
63 | ;; pattern that is invalid
64 | local.get $ret
65 | i32.const 0xde
66 | local.get $new_size
67 | memory.fill
68 | ;; If the old pointer is present then that means this was a reallocation
69 | ;; of an existing chunk which means the existing data must be copied.
70 | local.get $old_ptr
71 | if
72 | local.get $ret ;; destination
73 | local.get $old_ptr ;; source
74 | local.get $old_size ;; size
75 | memory.copy
76 | end
77 | local.get $ret
78 | )
79 | (func $clear (export "clear")
80 | i32.const 8
81 | global.set $last
82 | )
83 | )
--------------------------------------------------------------------------------
/crates/codegen/build.rs:
--------------------------------------------------------------------------------
1 | use std::{env, fs, path::Path};
2 |
3 | fn main() {
4 | let out_dir = env::var_os("OUT_DIR").unwrap();
5 | let dest_path = Path::new(&out_dir).join("allocator.wasm");
6 |
7 | let wat = include_str!("./allocator.wat");
8 | let wasm = wat::parse_str(wat).unwrap();
9 |
10 | fs::write(dest_path, wasm).unwrap();
11 | println!("cargo:rerun-if-changed=build.rs");
12 | println!("cargo:rerun-if-changed=allocator.wat");
13 | }
14 |
--------------------------------------------------------------------------------
/crates/codegen/src/builders/component.rs:
--------------------------------------------------------------------------------
1 | use wasm_encoder as enc;
2 |
3 | #[derive(Default)]
4 | pub struct ComponentBuilder {
5 | component: enc::Component,
6 |
7 | num_types: u32,
8 | num_funcs: u32,
9 | num_core_funcs: u32,
10 | num_core_mems: u32,
11 | num_modules: u32,
12 | num_module_instances: u32,
13 | num_instances: u32,
14 | }
15 |
16 | #[derive(Clone, Copy, Debug)]
17 | pub struct ComponentInstanceIndex(u32);
18 |
19 | #[derive(Clone, Copy, Debug)]
20 | pub struct ComponentModuleIndex(u32);
21 |
22 | #[derive(Clone, Copy, Debug)]
23 | pub struct ComponentModuleInstanceIndex(u32);
24 |
25 | #[derive(Clone, Copy, Debug)]
26 | pub struct ComponentTypeIndex(u32);
27 |
28 | #[derive(Clone, Copy, Debug)]
29 | pub struct ComponentFunctionIndex(u32);
30 |
31 | #[derive(Clone, Copy, Debug)]
32 | pub struct ComponentCoreFunctionIndex(u32);
33 |
34 | #[derive(Clone, Copy, Debug)]
35 | pub struct ComponentCoreMemoryIndex(u32);
36 |
37 | pub enum InlineExportItem {
38 | Func(ComponentCoreFunctionIndex),
39 | }
40 |
41 | pub enum ModuleInstantiateArgs {
42 | Instance(ComponentModuleInstanceIndex),
43 | }
44 |
45 | impl ComponentBuilder {
46 | pub fn module(&mut self, module: enc::Module) -> ComponentModuleIndex {
47 | self.component.section(&enc::ModuleSection(&module));
48 | self.next_mod_idx()
49 | }
50 |
51 | pub fn module_bytes(&mut self, bytes: &[u8]) -> ComponentModuleIndex {
52 | self.component.section(&enc::RawSection {
53 | id: enc::ComponentSectionId::CoreModule.into(),
54 | data: bytes,
55 | });
56 | self.next_mod_idx()
57 | }
58 |
59 | #[allow(dead_code)]
60 | pub fn inline_export(
61 | &mut self,
62 | exports: &[(String, InlineExportItem)],
63 | ) -> ComponentModuleInstanceIndex {
64 | let exports: Vec<(String, enc::ExportKind, u32)> = exports
65 | .iter()
66 | .map(|(name, arg)| match arg {
67 | InlineExportItem::Func(func) => (name.to_owned(), enc::ExportKind::Func, func.0),
68 | })
69 | .collect();
70 | let mut section = enc::InstanceSection::new();
71 | section.export_items(exports);
72 | self.component.section(§ion);
73 | self.next_mod_instance_idx()
74 | }
75 |
76 | pub fn instantiate(
77 | &mut self,
78 | module: ComponentModuleIndex,
79 | args: Vec<(S, ModuleInstantiateArgs)>,
80 | ) -> ComponentModuleInstanceIndex
81 | where
82 | S: AsRef,
83 | {
84 | let args: Vec<_> = args
85 | .into_iter()
86 | .map(|(name, arg)| match arg {
87 | ModuleInstantiateArgs::Instance(instance) => {
88 | (name, enc::ModuleArg::Instance(instance.0))
89 | }
90 | })
91 | .collect();
92 | let mut section = enc::InstanceSection::new();
93 | section.instantiate(module.0, args);
94 | self.component.section(§ion);
95 | self.next_mod_instance_idx()
96 | }
97 |
98 | pub fn func_type<'b, P>(
99 | &mut self,
100 | params: P,
101 | results: Option,
102 | ) -> ComponentTypeIndex
103 | where
104 | P: IntoIterator,
105 | P::IntoIter: ExactSizeIterator,
106 | {
107 | let mut section = enc::ComponentTypeSection::new();
108 | let mut builder = section.function();
109 | builder.params(params);
110 | match results {
111 | Some(return_type) => {
112 | builder.result(return_type);
113 | }
114 | None => {
115 | builder.results([] as [(&str, enc::ComponentValType); 0]);
116 | }
117 | }
118 | self.component.section(§ion);
119 | self.next_type_idx()
120 | }
121 |
122 | pub fn instance_type(&mut self, instance_type: &enc::InstanceType) -> ComponentTypeIndex {
123 | let mut section = enc::ComponentTypeSection::new();
124 | section.instance(instance_type);
125 | self.component.section(§ion);
126 | self.next_type_idx()
127 | }
128 |
129 | pub fn import_func(
130 | &mut self,
131 | name: &str,
132 | fn_type: ComponentTypeIndex,
133 | ) -> ComponentFunctionIndex {
134 | let mut section = enc::ComponentImportSection::new();
135 | let ty = enc::ComponentTypeRef::Func(fn_type.0);
136 | section.import(name, ty);
137 | self.component.section(§ion);
138 | self.next_func_idx()
139 | }
140 |
141 | pub fn import_instance(
142 | &mut self,
143 | name: &str,
144 | instance_type_index: ComponentTypeIndex,
145 | ) -> ComponentInstanceIndex {
146 | let mut section = enc::ComponentImportSection::new();
147 | let ty = enc::ComponentTypeRef::Instance(instance_type_index.0);
148 | section.import(name, ty);
149 | self.component.section(§ion);
150 | self.next_instance_idx()
151 | }
152 |
153 | pub fn lower_func(
154 | &mut self,
155 | func: ComponentFunctionIndex,
156 | memory: ComponentCoreMemoryIndex,
157 | realloc: ComponentCoreFunctionIndex,
158 | ) -> ComponentCoreFunctionIndex {
159 | let options: [enc::CanonicalOption; 2] = [
160 | enc::CanonicalOption::Memory(memory.0),
161 | enc::CanonicalOption::Realloc(realloc.0),
162 | ];
163 | let mut section = enc::CanonicalFunctionSection::new();
164 | section.lower(func.0, options);
165 | self.component.section(§ion);
166 | self.next_core_func_idx()
167 | }
168 |
169 | pub fn alias_memory(
170 | &mut self,
171 | instance: ComponentModuleInstanceIndex,
172 | name: &str,
173 | ) -> ComponentCoreMemoryIndex {
174 | let mut section = enc::ComponentAliasSection::new();
175 | section.alias(enc::Alias::CoreInstanceExport {
176 | instance: instance.0,
177 | kind: enc::ExportKind::Memory,
178 | name,
179 | });
180 | self.component.section(§ion);
181 | self.next_core_memory_idx()
182 | }
183 |
184 | pub fn alias_core_func(
185 | &mut self,
186 | instance: ComponentModuleInstanceIndex,
187 | name: &str,
188 | ) -> ComponentCoreFunctionIndex {
189 | let mut section = enc::ComponentAliasSection::new();
190 | section.alias(enc::Alias::CoreInstanceExport {
191 | instance: instance.0,
192 | kind: enc::ExportKind::Func,
193 | name,
194 | });
195 | self.component.section(§ion);
196 | self.next_core_func_idx()
197 | }
198 |
199 | pub fn alias_func(
200 | &mut self,
201 | instance: ComponentInstanceIndex,
202 | name: &str,
203 | ) -> ComponentFunctionIndex {
204 | let mut section = enc::ComponentAliasSection::new();
205 | section.alias(enc::Alias::InstanceExport {
206 | instance: instance.0,
207 | kind: enc::ComponentExportKind::Func,
208 | name,
209 | });
210 | self.component.section(§ion);
211 | self.next_func_idx()
212 | }
213 |
214 | pub fn lift_func(
215 | &mut self,
216 | func: ComponentCoreFunctionIndex,
217 | fn_type: ComponentTypeIndex,
218 | memory: ComponentCoreMemoryIndex,
219 | realloc: ComponentCoreFunctionIndex,
220 | post_return: ComponentCoreFunctionIndex,
221 | ) -> ComponentFunctionIndex {
222 | let mut section = enc::CanonicalFunctionSection::new();
223 | let options: [enc::CanonicalOption; 3] = [
224 | enc::CanonicalOption::Memory(memory.0),
225 | enc::CanonicalOption::Realloc(realloc.0),
226 | enc::CanonicalOption::PostReturn(post_return.0),
227 | ];
228 | section.lift(func.0, fn_type.0, options);
229 | self.component.section(§ion);
230 | self.next_func_idx()
231 | }
232 |
233 | pub fn export_func(
234 | &mut self,
235 | name: &str,
236 | func: ComponentFunctionIndex,
237 | fn_type: ComponentTypeIndex,
238 | ) -> ComponentFunctionIndex {
239 | let mut section = enc::ComponentExportSection::new();
240 | section.export(
241 | name,
242 | enc::ComponentExportKind::Func,
243 | func.0,
244 | Some(enc::ComponentTypeRef::Func(fn_type.0)),
245 | );
246 | self.component.section(§ion);
247 | self.next_func_idx()
248 | }
249 |
250 | pub fn finalize(self) -> enc::Component {
251 | self.component
252 | }
253 |
254 | fn next_mod_idx(&mut self) -> ComponentModuleIndex {
255 | let index = ComponentModuleIndex(self.num_modules);
256 | self.num_modules += 1;
257 | index
258 | }
259 |
260 | fn next_mod_instance_idx(&mut self) -> ComponentModuleInstanceIndex {
261 | let index = ComponentModuleInstanceIndex(self.num_module_instances);
262 | self.num_module_instances += 1;
263 | index
264 | }
265 |
266 | fn next_type_idx(&mut self) -> ComponentTypeIndex {
267 | let index = ComponentTypeIndex(self.num_types);
268 | self.num_types += 1;
269 | index
270 | }
271 |
272 | fn next_func_idx(&mut self) -> ComponentFunctionIndex {
273 | let index = ComponentFunctionIndex(self.num_funcs);
274 | self.num_funcs += 1;
275 | index
276 | }
277 |
278 | fn next_instance_idx(&mut self) -> ComponentInstanceIndex {
279 | let index = ComponentInstanceIndex(self.num_instances);
280 | self.num_instances += 1;
281 | index
282 | }
283 |
284 | fn next_core_func_idx(&mut self) -> ComponentCoreFunctionIndex {
285 | let index = ComponentCoreFunctionIndex(self.num_core_funcs);
286 | self.num_core_funcs += 1;
287 | index
288 | }
289 |
290 | fn next_core_memory_idx(&mut self) -> ComponentCoreMemoryIndex {
291 | let index = ComponentCoreMemoryIndex(self.num_core_mems);
292 | self.num_core_mems += 1;
293 | index
294 | }
295 | }
296 |
--------------------------------------------------------------------------------
/crates/codegen/src/builders/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod component;
2 | pub mod module;
3 |
--------------------------------------------------------------------------------
/crates/codegen/src/builders/module.rs:
--------------------------------------------------------------------------------
1 | use wasm_encoder as enc;
2 |
3 | #[derive(Default)]
4 | pub struct ModuleBuilder {
5 | types: enc::TypeSection,
6 | imports: enc::ImportSection,
7 | funcs: enc::FunctionSection,
8 | globals: enc::GlobalSection,
9 | exports: enc::ExportSection,
10 | data: enc::DataSection,
11 |
12 | code: Vec