Skip to content

Commit 5032b71

Browse files
Make wit-parser support no_std (#2415)
* make wit-parser support no_std temporarily use forked id-arena use alloc BTreeMap and BinaryHeap use alloc BTreeMap and BTreeSet instead of std HashMap and HashSet import misc items from core/alloc instead of std use core Error, FromStr, and Debug add std feature and gate things behind it use different IndexMap/IndexSet for std vs no_std misc alloc imports add cargo check update workspace anyhow fixes * use HashMap for std and IndexMap for no_std use new instead of default make HashMap newtype remove collections mod * use hashbrown instead of indexmap for internal collections usage * remove extra file, use to_str instead of display, use hashbrown hash builder instead of ahash's and remove ashash as a dep * use patched version of id-arena instead of fork * PackageSourceMap is now implemented with a no_std compat PackageSources which uses String instead of PathBuf * move fs (std) resolve functionality to resolve::fs and move resolve.rs to resolve/mod.rs cleanup move logic from PackageSourceMap to PackageSources make methods public to avoid no_std flag * enable indexmap feature std for crates that need it * fix doc tests
1 parent d4e317f commit 5032b71

File tree

23 files changed

+537
-360
lines changed

23 files changed

+537
-360
lines changed

.github/workflows/main.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ jobs:
265265
- run: cargo check --no-default-features --features wast
266266
- run: cargo check --no-default-features --features wit-dylib
267267
- run: cargo check --no-default-features -p wit-parser
268+
- run: cargo check --no-default-features -p wit-parser --target x86_64-unknown-none
268269
- run: cargo check --no-default-features -p wit-parser --features wat
269270
- run: cargo check --no-default-features -p wit-parser --features serde
270271
- run: cargo check --no-default-features -p wit-parser --features decoding

Cargo.lock

Lines changed: 3 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ rust-version = "1.81.0"
108108

109109
[workspace.dependencies]
110110
ahash = { version = "0.8.11", default-features = false }
111-
anyhow = "1.0.58"
111+
anyhow = { version = "1.0.58", default-features = false }
112112
arbitrary = "1.1.0"
113113
bitflags = "2.5.0"
114114
bytesize = "2.0.0"
@@ -119,7 +119,7 @@ criterion = { version = "0.5.1", default-features = false }
119119
env_logger = "0.11"
120120
gimli = "0.31.1"
121121
hashbrown = { version = "0.15.2", default-features = false, features = ['default-hasher'] }
122-
id-arena = "2"
122+
id-arena = { version = "2.3.0", default-features = false }
123123
indexmap = { version = "2.7.0", default-features = false }
124124
indoc = "2.0.5"
125125
leb128fmt = { version = "0.1.0", default-features = false }

crates/wasm-compose/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ workspace = true
1818
anyhow = { workspace = true }
1919
heck = "0.5.0"
2020
im-rc = "15.1.0"
21-
indexmap = { workspace = true, features = ["serde"] }
21+
indexmap = { workspace = true, features = ["std", "serde"] }
2222
log = { workspace = true }
2323
petgraph = "0.6.2"
2424
serde = { workspace = true }

crates/wasm-metadata/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ workspace = true
1313
[dependencies]
1414
anyhow = { workspace = true }
1515
clap = { workspace = true, optional = true }
16-
indexmap = { workspace = true, features = ["serde"] }
16+
indexmap = { workspace = true, features = ["std", "serde"] }
1717
serde = { workspace = true, optional = true }
1818
serde_derive = { workspace = true, optional = true }
1919
serde_json = { workspace = true, optional = true }

crates/wit-component/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ all-features = true
2222
[dependencies]
2323
anyhow = { workspace = true }
2424
bitflags = "2.3.3"
25-
indexmap = { workspace = true }
25+
indexmap = { workspace = true, features = ["std"] }
2626
log = "0.4.17"
2727
serde = { workspace = true }
2828
serde_derive = { workspace = true }

crates/wit-dylib/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ workspace = true
1717
[dependencies]
1818
wit-parser = { workspace = true }
1919
wasm-encoder = { workspace = true }
20-
indexmap = { workspace = true }
20+
indexmap = { workspace = true, features = ["std"] }
2121
clap = { workspace = true, optional = true }
2222
anyhow = { workspace = true }
2323

@@ -29,7 +29,7 @@ tempfile = { workspace = true }
2929
wit-smith = { workspace = true }
3030
arbitrary = { workspace = true }
3131
arbtest = "0.3.2"
32-
indexmap = { workspace = true }
32+
indexmap = { workspace = true, features = ["std"] }
3333
wit-component = { workspace = true }
3434
env_logger = { workspace = true }
3535
wasmparser = { workspace = true }

crates/wit-parser/Cargo.toml

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ workspace = true
1818

1919
[dependencies]
2020
anyhow = { workspace = true }
21+
hashbrown = { workspace = true }
2122
id-arena = { workspace = true }
22-
indexmap = { workspace = true, features = ['std'] }
23+
indexmap = { workspace = true }
2324
log = { workspace = true }
2425
semver = { workspace = true }
2526
serde = { workspace = true, optional = true }
@@ -30,15 +31,18 @@ wasmparser = { workspace = true, optional = true, features = ['std', 'validate',
3031
wat = { workspace = true, optional = true, features = ['component-model'] }
3132

3233
[features]
33-
default = ['serde', 'decoding']
34+
default = ['std', 'serde', 'decoding']
35+
36+
# Enables use of std::path::Path and filesystem-related APIs.
37+
std = []
3438

3539
# Enables support for `derive(Serialize, Deserialize)` on many structures, such
3640
# as `Resolve`, which can assist when encoding `Resolve` as JSON for example.
3741
serde = ['dep:serde', 'dep:serde_derive', 'indexmap/serde', 'serde_json']
3842

3943
# Enables support for decoding WIT from WebAssembly. This can be done to support
4044
# decoding a WIT package encoded as wasm automatically.
41-
decoding = ['dep:wasmparser']
45+
decoding = ['std', 'dep:wasmparser']
4246

4347
# Enables support for parsing the wasm text format in conjunction with the
4448
# `decoding` feature.

crates/wit-parser/src/abi.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::{Function, Handle, Int, Resolve, Type, TypeDefKind};
2+
use alloc::vec::Vec;
23

34
/// A core WebAssembly signature with params and results.
45
#[derive(Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]

crates/wit-parser/src/ast.rs

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
use crate::{Error, PackageNotFoundError, UnresolvedPackageGroup};
2+
use alloc::borrow::Cow;
3+
use alloc::boxed::Box;
4+
use alloc::format;
5+
use alloc::string::{String, ToString};
6+
use alloc::vec::Vec;
27
use anyhow::{Context, Result, bail};
8+
use core::fmt;
9+
use core::mem;
310
use lex::{Span, Token, Tokenizer};
411
use semver::Version;
5-
use std::borrow::Cow;
6-
use std::fmt;
7-
use std::mem;
8-
use std::path::{Path, PathBuf};
12+
#[cfg(feature = "std")]
13+
use std::path::Path;
914

1015
pub mod lex;
1116

@@ -1694,7 +1699,7 @@ pub struct SourceMap {
16941699
#[derive(Clone)]
16951700
struct Source {
16961701
offset: u32,
1697-
path: PathBuf,
1702+
path: String,
16981703
contents: String,
16991704
}
17001705

@@ -1711,6 +1716,7 @@ impl SourceMap {
17111716

17121717
/// Reads the file `path` on the filesystem and appends its contents to this
17131718
/// [`SourceMap`].
1719+
#[cfg(feature = "std")]
17141720
pub fn push_file(&mut self, path: &Path) -> Result<()> {
17151721
let contents = std::fs::read_to_string(path)
17161722
.with_context(|| format!("failed to read file {path:?}"))?;
@@ -1725,7 +1731,19 @@ impl SourceMap {
17251731
/// used to create the final parsed package namely by unioning all the
17261732
/// interfaces and worlds defined together. Note that each file has its own
17271733
/// personal namespace, however, for top-level `use` and such.
1734+
#[cfg(feature = "std")]
17281735
pub fn push(&mut self, path: &Path, contents: impl Into<String>) {
1736+
self.push_str(&path.display().to_string(), contents);
1737+
}
1738+
1739+
/// Appends the given contents with the given source name into this source map.
1740+
///
1741+
/// The `path` provided is not read from the filesystem and is instead only
1742+
/// used during error messages. Each file added to a [`SourceMap`] is
1743+
/// used to create the final parsed package namely by unioning all the
1744+
/// interfaces and worlds defined together. Note that each file has its own
1745+
/// personal namespace, however, for top-level `use` and such.
1746+
pub fn push_str(&mut self, path: &str, contents: impl Into<String>) {
17291747
let mut contents = contents.into();
17301748
// Guarantee that there's at least one character in these contents by
17311749
// appending a single newline to the end. This is excluded from
@@ -1736,7 +1754,7 @@ impl SourceMap {
17361754
let new_offset = self.offset + u32::try_from(contents.len()).unwrap();
17371755
self.sources.push(Source {
17381756
offset: self.offset,
1739-
path: path.to_path_buf(),
1757+
path: path.to_string(),
17401758
contents,
17411759
});
17421760
self.offset = new_offset;
@@ -1762,7 +1780,7 @@ impl SourceMap {
17621780
src.offset,
17631781
self.require_f32_f64,
17641782
)
1765-
.with_context(|| format!("failed to tokenize path: {}", src.path.display()))?;
1783+
.with_context(|| format!("failed to tokenize path: {}", src.path))?;
17661784
let mut file = PackageFile::parse(&mut tokens)?;
17671785

17681786
// Filter out any nested packages and resolve them separately.
@@ -1778,10 +1796,7 @@ impl SourceMap {
17781796
AstItem::Package(nested_pkg) => {
17791797
let mut resolve = Resolver::default();
17801798
resolve.push(nested_pkg).with_context(|| {
1781-
format!(
1782-
"failed to handle nested package in: {}",
1783-
src.path.display()
1784-
)
1799+
format!("failed to handle nested package in: {}", src.path)
17851800
})?;
17861801

17871802
nested.push(resolve.resolve()?);
@@ -1792,9 +1807,9 @@ impl SourceMap {
17921807

17931808
// With nested packages handled push this file into the
17941809
// resolver.
1795-
resolver.push(file).with_context(|| {
1796-
format!("failed to start resolving path: {}", src.path.display())
1797-
})?;
1810+
resolver
1811+
.push(file)
1812+
.with_context(|| format!("failed to start resolving path: {}", src.path))?;
17981813
}
17991814
Ok(resolver.resolve()?)
18001815
})?;
@@ -1877,7 +1892,7 @@ impl SourceMap {
18771892
{line:4} | {snippet}
18781893
| {marker:>0$}",
18791894
col + 1,
1880-
file = src.path.display(),
1895+
file = src.path,
18811896
line = line + 1,
18821897
col = col + 1,
18831898
marker = "^",
@@ -1898,7 +1913,7 @@ impl SourceMap {
18981913
let (line, col) = src.linecol(start);
18991914
format!(
19001915
"{file}:{line}:{col}",
1901-
file = src.path.display(),
1916+
file = src.path,
19021917
line = line + 1,
19031918
col = col + 1,
19041919
)
@@ -1913,8 +1928,14 @@ impl SourceMap {
19131928
}
19141929

19151930
/// Returns an iterator over all filenames added to this source map.
1931+
#[cfg(feature = "std")]
19161932
pub fn source_files(&self) -> impl Iterator<Item = &Path> {
1917-
self.sources.iter().map(|src| src.path.as_path())
1933+
self.sources.iter().map(|src| Path::new(&src.path))
1934+
}
1935+
1936+
/// Returns an iterator over all source names added to this source map.
1937+
pub fn source_names(&self) -> impl Iterator<Item = &str> {
1938+
self.sources.iter().map(|src| src.path.as_str())
19181939
}
19191940
}
19201941

0 commit comments

Comments
 (0)