Skip to content

Commit

Permalink
Add no_std support to wasm-encoder (bytecodealliance#1938)
Browse files Browse the repository at this point in the history
* Add `no_std` support to `wasm-encoder`

* Manual fmt

* Implement `Error` only with `std` enabled

* Fix error implementation

* Update MSRV comment
  • Loading branch information
ark0f authored Dec 7, 2024
1 parent ebb55ce commit 90bd0f0
Show file tree
Hide file tree
Showing 38 changed files with 110 additions and 27 deletions.
9 changes: 5 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@ version = "0.221.2"
# Current policy for wasm-tools is the same as Wasmtime which is that this
# number can be no larger than the current stable release of Rust minus 2.
#
# NB: if this number increases to 1.81-or-later delete the
# `crates/wasmparser/build.rs` script as it's no longer necessary.
# NB: if this number increases to 1.81-or-later delete
# `crates/wasmparser/build.rs` and `crates/wasm-encoder/build.rs` scripts
# as they are no longer necessary.
rust-version = "1.76.0"

[workspace.dependencies]
Expand Down Expand Up @@ -100,12 +101,12 @@ gimli = "0.30.0"
id-arena = "2"

wasm-compose = { version = "0.221.2", path = "crates/wasm-compose" }
wasm-encoder = { version = "0.221.2", path = "crates/wasm-encoder", default-features = false }
wasm-encoder = { version = "0.221.2", path = "crates/wasm-encoder", default-features = false, features = ["std"] }
wasm-metadata = { version = "0.221.2", path = "crates/wasm-metadata" }
wasm-mutate = { version = "0.221.2", path = "crates/wasm-mutate" }
wasm-shrink = { version = "0.221.2", path = "crates/wasm-shrink" }
wasm-smith = { version = "0.221.2", path = "crates/wasm-smith" }
wasmparser = { version = "0.221.2", path = "crates/wasmparser", default-features = false, features = ['std','simd'] }
wasmparser = { version = "0.221.2", path = "crates/wasmparser", default-features = false, features = ['std', 'simd'] }
wasmprinter = { version = "0.221.2", path = "crates/wasmprinter", default-features = false }
wast = { version = "221.0.2", path = "crates/wast", default-features = false }
wat = { version = "1.221.2", path = "crates/wat", default-features = false }
Expand Down
5 changes: 4 additions & 1 deletion crates/wasm-encoder/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ wasmparser = { path = "../wasmparser" }
wasmprinter = { workspace = true }

[features]
default = ['component-model']
default = ['std', 'component-model']

# A feature which enables implementations of `std::error::Error` as appropriate.
std = []

# On-by-default: conditional support for emitting components in addition to
# core modules.
Expand Down
27 changes: 27 additions & 0 deletions crates/wasm-encoder/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::process::Command;
use std::str;

fn main() {
// Temporary check to see if the rustc version >= 1.81 in which case the
// `Error` trait is always available. This is temporary because in the
// future the MSRV of this crate will be beyond 1.81 in which case this
// build script can be deleted.
let minor = rustc_minor_version().unwrap_or(0);
if minor >= 81 {
println!("cargo:rustc-cfg=core_error");
}
if minor >= 80 {
println!("cargo:rustc-check-cfg=cfg(core_error)");
}
}

fn rustc_minor_version() -> Option<u32> {
let rustc = std::env::var("RUSTC").unwrap();
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next() != Some("rustc 1") {
return None;
}
pieces.next()?.parse().ok()
}
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub use self::start::*;
pub use self::types::*;

use crate::{CustomSection, Encode, ProducersSection, RawCustomSection};
use alloc::vec::Vec;

// Core sorts extended by the component model
const CORE_TYPE_SORT: u8 = 0x10;
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/aliases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use super::{COMPONENT_SORT, CORE_MODULE_SORT, CORE_SORT, CORE_TYPE_SORT, TYPE_SO
use crate::{
encode_section, ComponentExportKind, ComponentSection, ComponentSectionId, Encode, ExportKind,
};
use alloc::vec::Vec;

/// Represents the kinds of outer aliasable items in a component.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
Expand Down
3 changes: 2 additions & 1 deletion crates/wasm-encoder/src/component/builder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::component::*;
use crate::{ExportKind, Module, RawSection, ValType};
use std::mem;
use alloc::vec::Vec;
use core::mem;

/// Convenience type to build a component incrementally and automatically keep
/// track of index spaces.
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/canonicals.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encode_section, ComponentSection, ComponentSectionId, Encode};
use alloc::vec::Vec;

/// Represents options for canonical function definitions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/components.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{Component, ComponentSection, ComponentSectionId, Encode};
use alloc::vec::Vec;

/// An encoder for the component section of WebAssembly components.
///
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::{
VALUE_SORT,
};
use crate::{encode_section, ComponentSection, ComponentSectionId, ComponentTypeRef, Encode};
use alloc::vec::Vec;

/// Represents the kind of an export from a WebAssembly component.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{
encode_section, ComponentExportKind, ComponentSection, ComponentSectionId, ComponentValType,
Encode,
};
use alloc::vec::Vec;

/// Represents the possible type bounds for type references.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/instances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use super::CORE_INSTANCE_SORT;
use crate::{
encode_section, ComponentExportKind, ComponentSection, ComponentSectionId, Encode, ExportKind,
};
use alloc::vec::Vec;

/// Represents an argument to a module instantiation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/modules.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{ComponentSection, ComponentSectionId, Encode, Module};
use alloc::vec::Vec;

/// An encoder for the module section of WebAssembly components.
///
Expand Down
3 changes: 2 additions & 1 deletion crates/wasm-encoder/src/component/names.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::borrow::Cow;
use alloc::borrow::Cow;
use alloc::vec::Vec;

use super::*;
use crate::{encoding_size, ExportKind, NameMap, SectionId};
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/start.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{ComponentSection, ComponentSectionId, Encode};
use alloc::vec::Vec;

/// An encoder for the start section of WebAssembly components.
///
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/component/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{
encode_section, Alias, ComponentExportKind, ComponentOuterAliasKind, ComponentSection,
ComponentSectionId, ComponentTypeRef, CoreTypeEncoder, Encode, EntityType, ValType,
};
use alloc::vec::Vec;

/// Represents the type of a core module.
#[derive(Debug, Clone, Default)]
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub use tags::*;
pub use types::*;

use crate::Encode;
use alloc::vec::Vec;

pub(crate) const CORE_FUNCTION_SORT: u8 = 0x00;
pub(crate) const CORE_TABLE_SORT: u8 = 0x01;
Expand Down
3 changes: 2 additions & 1 deletion crates/wasm-encoder/src/core/branch_hints.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{CustomSection, Encode, Section, SectionId};
use std::borrow::Cow;
use alloc::borrow::Cow;
use alloc::vec::Vec;

/// Helper structure to encode the `metadata.code.branch_hint` custom section.
///
Expand Down
4 changes: 3 additions & 1 deletion crates/wasm-encoder/src/core/code.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::{encode_section, Encode, HeapType, RefType, Section, SectionId, ValType};
use std::borrow::Cow;
use alloc::borrow::Cow;
use alloc::vec;
use alloc::vec::Vec;

/// An encoder for the code section.
///
Expand Down
5 changes: 3 additions & 2 deletions crates/wasm-encoder/src/core/custom.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::borrow::Cow;

use crate::{encoding_size, Encode, Section, SectionId};
use alloc::borrow::Cow;
use alloc::vec::Vec;

/// A custom section holding arbitrary data.
#[derive(Clone, Debug, PartialEq)]
Expand Down Expand Up @@ -47,6 +47,7 @@ impl Section for RawCustomSection<'_> {
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;

#[test]
fn test_custom_section() {
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/data.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encode_section, encoding_size, ConstExpr, Encode, Section, SectionId};
use alloc::vec::Vec;

/// An encoder for the data section.
///
Expand Down
6 changes: 4 additions & 2 deletions crates/wasm-encoder/src/core/dump.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::borrow::Cow;

use crate::{CustomSection, Encode, Section};
use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;

/// The "core" custom section for coredumps, as described in the
/// [tool-conventions
Expand Down
3 changes: 2 additions & 1 deletion crates/wasm-encoder/src/core/elements.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{encode_section, ConstExpr, Encode, RefType, Section, SectionId};
use std::borrow::Cow;
use alloc::borrow::Cow;
use alloc::vec::Vec;

/// An encoder for the element section.
///
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use super::{
CORE_FUNCTION_SORT, CORE_GLOBAL_SORT, CORE_MEMORY_SORT, CORE_TABLE_SORT, CORE_TAG_SORT,
};
use crate::{encode_section, Encode, Section, SectionId};
use alloc::vec::Vec;

/// Represents the kind of an export from a WebAssembly module.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/functions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encode_section, Encode, Section, SectionId};
use alloc::vec::Vec;

/// An encoder for the function section of WebAssembly modules.
///
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/globals.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encode_section, ConstExpr, Encode, Section, SectionId, ValType};
use alloc::vec::Vec;

/// An encoder for the global section.
///
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{
encode_section, Encode, GlobalType, MemoryType, Section, SectionId, TableType, TagType,
CORE_FUNCTION_SORT, CORE_GLOBAL_SORT, CORE_MEMORY_SORT, CORE_TABLE_SORT, CORE_TAG_SORT,
};
use alloc::vec::Vec;

/// The type of an entity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down
5 changes: 3 additions & 2 deletions crates/wasm-encoder/src/core/linking.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::borrow::Cow;

use crate::{encode_section, CustomSection, Encode, Section, SectionId};
use alloc::borrow::Cow;
use alloc::vec;
use alloc::vec::Vec;

const VERSION: u32 = 2;

Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/memories.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encode_section, Encode, Section, SectionId};
use alloc::vec::Vec;

/// An encoder for the memory section.
///
Expand Down
5 changes: 3 additions & 2 deletions crates/wasm-encoder/src/core/names.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::borrow::Cow;

use crate::{encoding_size, CustomSection, Encode, Section, SectionId};
use alloc::borrow::Cow;
use alloc::vec;
use alloc::vec::Vec;

/// An encoder for the custom `name` section.
///
Expand Down
4 changes: 2 additions & 2 deletions crates/wasm-encoder/src/core/producers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::borrow::Cow;

use crate::{CustomSection, Encode, Section, SectionId};
use alloc::borrow::Cow;
use alloc::vec::Vec;

/// An encoder for the [producers custom
/// section](https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md).
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/start.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encoding_size, Encode, Section, SectionId};
use alloc::vec::Vec;

/// An encoder for the start section of WebAssembly modules.
///
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/tables.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encode_section, ConstExpr, Encode, RefType, Section, SectionId, ValType};
use alloc::vec::Vec;

/// An encoder for the table section.
///
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/core/tags.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{encode_section, Encode, Section, SectionId};
use alloc::vec::Vec;

/// An encoder for the tag section.
///
Expand Down
2 changes: 2 additions & 0 deletions crates/wasm-encoder/src/core/types.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::{encode_section, Encode, Section, SectionId};
use alloc::boxed::Box;
use alloc::vec::Vec;

/// Represents a subtype of possible other types in a WebAssembly module.
#[derive(Debug, Clone)]
Expand Down
8 changes: 8 additions & 0 deletions crates/wasm-encoder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,14 @@
//! ```
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![no_std]
#![deny(missing_docs, missing_debug_implementations)]

extern crate alloc;
#[cfg(feature = "std")]
#[macro_use]
extern crate std;

#[cfg(feature = "component-model")]
mod component;
mod core;
Expand All @@ -83,6 +89,8 @@ pub use self::component::*;
pub use self::core::*;
pub use self::raw::*;

use alloc::vec::Vec;

/// Implemented by types that can be encoded into a byte sink.
pub trait Encode {
/// Encode the type into the given byte sink.
Expand Down
1 change: 1 addition & 0 deletions crates/wasm-encoder/src/raw.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{Encode, Section};
use alloc::vec::Vec;

/// A section made up of uninterpreted, raw bytes.
///
Expand Down
21 changes: 14 additions & 7 deletions crates/wasm-encoder/src/reencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@
//! The [`RoundtripReencoder`] allows encoding identical wasm to the parsed
//! input.
#[cfg(all(not(feature = "std"), core_error))]
use core::error::Error as StdError;
#[cfg(feature = "std")]
use std::error::Error as StdError;

use crate::CoreTypeEncoder;
use std::convert::Infallible;
use core::convert::Infallible;

#[cfg(feature = "component-model")]
mod component;
Expand Down Expand Up @@ -546,8 +551,8 @@ impl<E> From<wasmparser::BinaryReaderError> for Error<E> {
}
}

impl<E: std::fmt::Display> std::fmt::Display for Error<E> {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
impl<E: core::fmt::Display> core::fmt::Display for Error<E> {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
match self {
Self::ParseError(_e) => {
write!(fmt, "There was an error when parsing")
Expand All @@ -574,8 +579,9 @@ impl<E: std::fmt::Display> std::fmt::Display for Error<E> {
}
}

impl<E: 'static + std::error::Error> std::error::Error for Error<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
#[cfg(any(feature = "std", core_error))]
impl<E: 'static + StdError> StdError for Error<E> {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Self::ParseError(e) => Some(e),
Self::UserError(e) => Some(e),
Expand All @@ -602,7 +608,8 @@ impl Reencode for RoundtripReencoder {
pub mod utils {
use super::{Error, Reencode};
use crate::{CoreTypeEncoder, Encode};
use std::ops::Range;
use alloc::vec::Vec;
use core::ops::Range;

pub fn parse_core_module<T: ?Sized + Reencode>(
reencoder: &mut T,
Expand All @@ -616,7 +623,7 @@ pub mod utils {
last_section: &mut Option<crate::SectionId>,
next_section: Option<crate::SectionId>,
) -> Result<(), Error<T::Error>> {
let after = std::mem::replace(last_section, next_section);
let after = core::mem::replace(last_section, next_section);
let before = next_section;
reencoder.intersperse_section_hook(module, after, before)
}
Expand Down
Loading

0 comments on commit 90bd0f0

Please sign in to comment.