From ddea68e1606115eaece180e6376092cd7501f12d Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Thu, 13 Aug 2026 16:40:23 -0700 Subject: [PATCH 1/8] checkpoint --- crates/wit-component/Cargo.toml | 1 + crates/wit-component/src/encoding.rs | 38 ++- crates/wit-component/src/encoding/wit.rs | 17 +- crates/wit-component/src/encoding/world.rs | 3 + crates/wit-parser/Cargo.toml | 6 + crates/wit-parser/src/lib.rs | 148 ++++++++++- crates/wit-parser/src/resolve/mod.rs | 294 ++++++++++++++++++++- 7 files changed, 497 insertions(+), 10 deletions(-) diff --git a/crates/wit-component/Cargo.toml b/crates/wit-component/Cargo.toml index 86b0a5ccda..0972f5b0f7 100644 --- a/crates/wit-component/Cargo.toml +++ b/crates/wit-component/Cargo.toml @@ -51,6 +51,7 @@ wasmtime = { workspace = true } dummy-module = ['dep:wat'] wat = ['dep:wast', 'dep:wat'] semver-check = ['dummy-module'] +canon-names = ['wit-parser/canon-names'] [[test]] name = "components" diff --git a/crates/wit-component/src/encoding.rs b/crates/wit-component/src/encoding.rs index 5e29ced9eb..b4c93df178 100644 --- a/crates/wit-component/src/encoding.rs +++ b/crates/wit-component/src/encoding.rs @@ -577,12 +577,17 @@ impl<'a> EncodingState<'a> { let instance_type_idx = self .component .type_instance(Some(&format!("ty-{name}")), &ty); + #[cfg(feature = "canon-names")] + let version_suffix = resolve.version_suffix_of(interface_id); + #[cfg(not(feature = "canon-names"))] + let version_suffix: Option = None; + let instance_idx = self.component.import( wasm_encoder::ComponentExternName { name: name.into(), implements: info.implements.as_deref().map(|s| s.into()), external_id: info.external_id.as_deref().map(|s| s.into()), - version_suffix: None, + version_suffix: version_suffix.as_deref().map(|s| s.into()), }, ComponentTypeRef::Instance(instance_type_idx), ); @@ -746,6 +751,9 @@ impl<'a> EncodingState<'a> { let world = &resolve.worlds[self.info.encoder.metadata.world]; for export_name in exports { + #[cfg(feature = "canon-names")] + let export_string = resolve.name_canonicalized_world_key(export_name); + #[cfg(not(feature = "canon-names"))] let export_string = resolve.name_world_key(export_name); match &world.exports[export_name] { WorldItem::Function(func) => { @@ -977,12 +985,17 @@ impl<'a> EncodingState<'a> { component_index, imports, ); + #[cfg(feature = "canon-names")] + let version_suffix = resolve.version_suffix_of(export); + #[cfg(not(feature = "canon-names"))] + let version_suffix: Option = None; + let idx = self.component.export( wasm_encoder::ComponentExternName { name: export_name.into(), implements: resolve.implements_value(key, item).map(|s| s.into()), external_id: resolve.external_id_value(key, item).map(|s| s.into()), - version_suffix: None, + version_suffix: version_suffix.as_deref().map(|s| s.into()), }, ComponentExportKind::Instance, instance_index, @@ -1808,7 +1821,12 @@ impl<'a> EncodingState<'a> { self.materialize_wit_import( shims, for_module, - iface.map(|_| resolve.name_world_key(key)), + iface.map(|_| { + #[cfg(feature = "canon-names")] + { resolve.name_canonicalized_world_key(key) } + #[cfg(not(feature = "canon-names"))] + { resolve.name_world_key(key) } + }), &format!("{name}_drop"), key, AbiVariant::GuestImport, @@ -1978,7 +1996,12 @@ impl<'a> EncodingState<'a> { Import::InterfaceFunc(key, _, name, abi) => self.materialize_wit_import( shims, for_module, - Some(resolve.name_world_key(key)), + Some({ + #[cfg(feature = "canon-names")] + { resolve.name_canonicalized_world_key(key) } + #[cfg(not(feature = "canon-names"))] + { resolve.name_world_key(key) } + }), name, key, *abi, @@ -3025,7 +3048,12 @@ impl<'a> Shims<'a> { field, key, name, - Some(resolve.name_world_key(key)), + Some({ + #[cfg(feature = "canon-names")] + { resolve.name_canonicalized_world_key(key) } + #[cfg(not(feature = "canon-names"))] + { resolve.name_world_key(key) } + }), *abi, )?; } diff --git a/crates/wit-component/src/encoding/wit.rs b/crates/wit-component/src/encoding/wit.rs index a70f90cc38..3ec0d44740 100644 --- a/crates/wit-component/src/encoding/wit.rs +++ b/crates/wit-component/src/encoding/wit.rs @@ -126,11 +126,24 @@ fn component_extern_name( key: &WorldKey, item: &WorldItem, ) -> wasm_encoder::ComponentExternName<'static> { + #[cfg(feature = "canon-names")] + let (name, version_suffix) = { + let name = resolve.name_canonicalized_world_key(key); + let suffix = match key { + WorldKey::Interface(id) => resolve.version_suffix_of(*id), + WorldKey::Name(_) => None, + }; + (name, suffix) + }; + #[cfg(not(feature = "canon-names"))] + let (name, version_suffix): (String, Option) = + (resolve.name_world_key(key), None); + ComponentExternName { - name: resolve.name_world_key(key).into(), + name: name.into(), implements: resolve.implements_value(key, item).map(|s| s.into()), external_id: resolve.external_id_value(key, item).map(|s| s.into()), - version_suffix: None, + version_suffix: version_suffix.map(|s| s.into()), } } diff --git a/crates/wit-component/src/encoding/world.rs b/crates/wit-component/src/encoding/world.rs index f5c6d32e69..fe69891d66 100644 --- a/crates/wit-component/src/encoding/world.rs +++ b/crates/wit-component/src/encoding/world.rs @@ -265,6 +265,9 @@ impl<'a> ComponentWorld<'a> { item: &WorldItem, required: &Required<'_>, ) -> Result<()> { + #[cfg(feature = "canon-names")] + let name = resolve.name_canonicalized_world_key(key); + #[cfg(not(feature = "canon-names"))] let name = resolve.name_world_key(key); log::trace!("register import `{name}`"); let import_map_key = match item { diff --git a/crates/wit-parser/Cargo.toml b/crates/wit-parser/Cargo.toml index 830ac0ff5b..feaadafac2 100644 --- a/crates/wit-parser/Cargo.toml +++ b/crates/wit-parser/Cargo.toml @@ -36,6 +36,12 @@ default = ['std', 'serde', 'decoding'] # Enables use of std::path::Path and filesystem-related APIs. std = ['semver/std'] +# Enables canonical interface name support where PackageName equality uses the +# canonical version prefix (from canon_version_split) rather than the full +# semver version. This allows packages on the same canonical version track to +# be merged, keeping the largest version. +canon-names = [] + # Enables support for `derive(Serialize, Deserialize)` on many structures, such # as `Resolve`, which can assist when encoding `Resolve` as JSON for example. serde = ['dep:serde', 'dep:serde_derive', 'indexmap/serde', 'serde_json'] diff --git a/crates/wit-parser/src/lib.rs b/crates/wit-parser/src/lib.rs index d1aece5a81..61cb75ab01 100644 --- a/crates/wit-parser/src/lib.rs +++ b/crates/wit-parser/src/lib.rs @@ -232,7 +232,7 @@ pub enum AstItem { /// /// This is directly encoded as an "ID" in the binary component representation /// with an interfaced tacked on as well. -#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +#[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(Serialize))] #[cfg_attr(feature = "serde", serde(into = "String"))] pub struct PackageName { @@ -244,6 +244,71 @@ pub struct PackageName { pub version: Option, } +impl PackageName { + /// Returns the canonical version prefix for comparison purposes. + /// + /// When `canon-names` is enabled, this returns only the canonical prefix + /// from [`PackageName::canon_version_split`]. Otherwise returns the full + /// version string. + fn version_key(&self) -> Option { + let version = self.version.as_ref()?; + #[cfg(feature = "canon-names")] + { + let (prefix, _) = Self::canon_version_split(version); + Some(prefix) + } + #[cfg(not(feature = "canon-names"))] + { + Some(version.to_string()) + } + } +} + +impl core::hash::Hash for PackageName { + fn hash(&self, state: &mut H) { + self.namespace.hash(state); + self.name.hash(state); + self.version_key().hash(state); + } +} + +impl PartialEq for PackageName { + fn eq(&self, other: &Self) -> bool { + self.namespace == other.namespace + && self.name == other.name + && self.version_key() == other.version_key() + } +} + +impl Eq for PackageName {} + +impl PartialOrd for PackageName { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for PackageName { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.namespace + .cmp(&other.namespace) + .then_with(|| self.name.cmp(&other.name)) + .then_with(|| self.version_key().cmp(&other.version_key())) + } +} + +impl PackageName { + /// Compares the full version of two package names. + /// + /// Unlike `Ord` (which may compare only canonical prefixes when + /// `canon-names` is enabled), this always compares the complete semver + /// version. Useful for determining which package has the larger version + /// during merging. + pub fn full_version_cmp(&self, other: &Self) -> core::cmp::Ordering { + self.version.cmp(&other.version) + } +} + impl From for String { fn from(name: PackageName) -> String { name.to_string() @@ -308,6 +373,30 @@ impl PackageName { } version.to_string() } + + /// Splits a semver version into a canonical version prefix and a version + /// suffix according to the component model spec. + /// + /// The split point is: + /// - If `major > 0`: split after major (e.g. `1.2.3` → `("1", ".2.3")`) + /// - If `major == 0` and `minor > 0`: split after minor + /// (e.g. `0.2.6-rc.1` → `("0.2", ".6-rc.1")`) + /// - Otherwise: split after patch (e.g. `0.0.1-alpha` → `("0.0.1", "-alpha")`) + pub fn canon_version_split(version: &Version) -> (String, String) { + let s = version.to_string(); + let split_pos = if version.major > 0 { + version.major.to_string().len() + } else if version.minor > 0 { + // "0.".len() + minor digits + 2 + version.minor.to_string().len() + } else { + // "0.0.".len() + patch digits + 4 + version.patch.to_string().len() + }; + let prefix = s[..split_pos].to_string(); + let suffix = s[split_pos..].to_string(); + (prefix, suffix) + } } impl fmt::Display for PackageName { @@ -1572,4 +1661,61 @@ mod test { assert_eq!(t1, found[1]); assert_eq!(t2, found[2]); } + + #[test] + fn test_canon_version_split() { + use semver::Version; + + // major > 0: split after major + let v = Version::parse("1.2.3").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("1".to_string(), ".2.3".to_string()) + ); + + let v = Version::parse("2.0.0").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("2".to_string(), ".0.0".to_string()) + ); + + let v = Version::parse("10.20.30").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("10".to_string(), ".20.30".to_string()) + ); + + // major == 0, minor > 0: split after minor + let v = Version::parse("0.2.6-rc.1").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("0.2".to_string(), ".6-rc.1".to_string()) + ); + + let v = Version::parse("0.1.0").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("0.1".to_string(), ".0".to_string()) + ); + + // major == 0, minor == 0: split after patch + let v = Version::parse("0.0.1-alpha").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("0.0.1".to_string(), "-alpha".to_string()) + ); + + let v = Version::parse("0.0.0").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("0.0.0".to_string(), "".to_string()) + ); + + // Pre-release on major > 0 + let v = Version::parse("1.0.0-beta.1").unwrap(); + assert_eq!( + PackageName::canon_version_split(&v), + ("1".to_string(), ".0.0-beta.1".to_string()) + ); + } } diff --git a/crates/wit-parser/src/resolve/mod.rs b/crates/wit-parser/src/resolve/mod.rs index 388e2767b7..3f4714a1be 100644 --- a/crates/wit-parser/src/resolve/mod.rs +++ b/crates/wit-parser/src/resolve/mod.rs @@ -515,6 +515,8 @@ impl Resolve { let mut map = MergeMap::new(&resolve, &self); map.build()?; + #[cfg(feature = "canon-names")] + let version_upgrades = map.version_upgrades.clone(); let MergeMap { package_map, interface_map, @@ -714,6 +716,16 @@ impl Resolve { } } + // When canon-names is enabled and a package from `from` had a larger + // version than the matching package in `into`, upgrade the version + // stored on the `into` package and update the `package_names` index. + #[cfg(feature = "canon-names")] + for (into_id, version) in version_upgrades { + let pkg = &mut self.packages[into_id]; + pkg.name.version = Some(version); + self.package_names.insert(pkg.name.clone(), into_id); + } + // Fixup all "parent" links now. // // Note that this is only done for items that are actually moved from @@ -1293,8 +1305,16 @@ impl Resolve { base.push_str(name); if let Some(version) = &package.name.version { base.push_str("@"); - let string = PackageName::version_compat_track_string(version); - base.push_str(&string); + #[cfg(feature = "canon-names")] + { + let (prefix, _) = PackageName::canon_version_split(version); + base.push_str(&prefix); + } + #[cfg(not(feature = "canon-names"))] + { + let string = PackageName::version_compat_track_string(version); + base.push_str(&string); + } } base } @@ -1550,6 +1570,20 @@ impl Resolve { } } + /// Returns the version suffix for the given interface's package, if any. + /// + /// This is the second element of [`PackageName::canon_version_split`]: + /// e.g. for version `2.0.1` the canonical name uses `@2` and this + /// returns `Some(".0.1")`. Returns `None` only if the package has no + /// version. + pub fn version_suffix_of(&self, interface: InterfaceId) -> Option { + let iface = &self.interfaces[interface]; + let pkg = &self.packages[iface.package?]; + let version = pkg.name.version.as_ref()?; + let (_, suffix) = PackageName::canon_version_split(version); + Some(suffix) + } + /// Returns the component model `implements` value for the world import of /// `key` and `item`. /// @@ -4469,6 +4503,12 @@ struct MergeMap<'a> { interfaces_to_add: Vec<(String, PackageId, InterfaceId)>, worlds_to_add: Vec<(String, PackageId, WorldId)>, + /// Packages in `into` whose version should be upgraded because `from` + /// had a larger version on the same canonical track. Maps `into` package + /// ID to the larger version from `from`. + #[cfg(feature = "canon-names")] + version_upgrades: HashMap, + /// Which `Resolve` is being merged from. from: &'a Resolve, @@ -4485,6 +4525,8 @@ impl<'a> MergeMap<'a> { world_map: Default::default(), interfaces_to_add: Default::default(), worlds_to_add: Default::default(), + #[cfg(feature = "canon-names")] + version_upgrades: Default::default(), from, into, } @@ -4505,6 +4547,16 @@ impl<'a> MergeMap<'a> { }; log::trace!("merging duplicate package {}", from.name); + #[cfg(feature = "canon-names")] + { + let into = &self.into.packages[into_id]; + if from.name.full_version_cmp(&into.name).is_gt() { + if let Some(version) = from.name.version.clone() { + self.version_upgrades.insert(into_id, version); + } + } + } + self.build_package(from_id, into_id).with_context(|| { format!("failed to merge package `{}` into existing copy", from.name) })?; @@ -6075,4 +6127,242 @@ interface iface { Ok(()) } + + #[cfg(feature = "canon-names")] + #[test] + fn canon_names_merge_keeps_larger_version() -> Result<()> { + let mut resolve1 = Resolve::default(); + resolve1.push_str( + "a.wit", + r#" + package foo:bar@2.0.0; + + interface my-iface { + type my-type = u32; + my-func: func(); + } + "#, + )?; + + let mut resolve2 = Resolve::default(); + resolve2.push_str( + "b.wit", + r#" + package foo:bar@2.0.1; + + interface my-iface { + type my-type = u32; + my-func: func(); + } + "#, + )?; + + resolve1.merge(resolve2)?; + + // Should have exactly one package (merged on canonical prefix "2") + assert_eq!(resolve1.packages.len(), 1); + let (_, pkg) = resolve1.packages.iter().next().unwrap(); + assert_eq!( + pkg.name.version.as_ref().unwrap().to_string(), + "2.0.1", + "should keep the larger version" + ); + + // Interface should be present with its type and function + let iface_id = pkg.interfaces["my-iface"]; + assert!(resolve1.interfaces[iface_id].types.contains_key("my-type")); + assert!(resolve1.interfaces[iface_id] + .functions + .contains_key("my-func")); + + Ok(()) + } + + #[cfg(feature = "canon-names")] + #[test] + fn canon_names_merge_larger_into_smaller() -> Result<()> { + // The larger version (from) is merged into the smaller (into). + // Extra types/functions from the larger version should appear in the result. + let mut resolve1 = Resolve::default(); + resolve1.push_str( + "a.wit", + r#" + package foo:bar@1.0.0; + + interface my-iface { + type base-type = u32; + base-func: func(); + } + "#, + )?; + + let mut resolve2 = Resolve::default(); + resolve2.push_str( + "b.wit", + r#" + package foo:bar@1.2.3; + + interface my-iface { + type base-type = u32; + base-func: func(); + type new-type = string; + new-func: func() -> string; + } + "#, + )?; + + resolve1.merge(resolve2)?; + + assert_eq!(resolve1.packages.len(), 1); + let (_, pkg) = resolve1.packages.iter().next().unwrap(); + assert_eq!(pkg.name.version.as_ref().unwrap().to_string(), "1.2.3"); + + let iface_id = pkg.interfaces["my-iface"]; + let iface = &resolve1.interfaces[iface_id]; + assert!(iface.types.contains_key("base-type")); + assert!(iface.types.contains_key("new-type")); + assert!(iface.functions.contains_key("base-func")); + assert!(iface.functions.contains_key("new-func")); + + Ok(()) + } + + #[cfg(feature = "canon-names")] + #[test] + fn canon_names_merge_smaller_into_larger() -> Result<()> { + // The smaller version (from) is merged into the larger (into). + // The larger version's content should be preserved as-is. + let mut resolve1 = Resolve::default(); + resolve1.push_str( + "a.wit", + r#" + package foo:bar@1.2.3; + + interface my-iface { + type base-type = u32; + base-func: func(); + type new-type = string; + new-func: func() -> string; + } + "#, + )?; + + let mut resolve2 = Resolve::default(); + resolve2.push_str( + "b.wit", + r#" + package foo:bar@1.0.0; + + interface my-iface { + type base-type = u32; + base-func: func(); + } + "#, + )?; + + resolve1.merge(resolve2)?; + + assert_eq!(resolve1.packages.len(), 1); + let (_, pkg) = resolve1.packages.iter().next().unwrap(); + assert_eq!( + pkg.name.version.as_ref().unwrap().to_string(), + "1.2.3", + "should keep the larger version already in into" + ); + + let iface_id = pkg.interfaces["my-iface"]; + let iface = &resolve1.interfaces[iface_id]; + assert!(iface.types.contains_key("base-type")); + assert!(iface.types.contains_key("new-type")); + assert!(iface.functions.contains_key("base-func")); + assert!(iface.functions.contains_key("new-func")); + + Ok(()) + } + + #[cfg(feature = "canon-names")] + #[test] + fn canon_names_different_tracks_not_merged() -> Result<()> { + // Packages on different canonical tracks should NOT merge. + // 0.1.x and 0.2.x have different canonical prefixes ("0.1" vs "0.2"). + let mut resolve1 = Resolve::default(); + resolve1.push_str( + "a.wit", + r#" + package foo:bar@0.1.0; + + interface iface-a { + type-a: func(); + } + "#, + )?; + + let mut resolve2 = Resolve::default(); + resolve2.push_str( + "b.wit", + r#" + package foo:bar@0.2.0; + + interface iface-b { + type-b: func(); + } + "#, + )?; + + resolve1.merge(resolve2)?; + + // Should have two separate packages + assert_eq!(resolve1.packages.len(), 2); + + Ok(()) + } + + #[cfg(feature = "canon-names")] + #[test] + fn canon_names_merge_with_extra_interface() -> Result<()> { + // When the larger version adds a new interface, it should be added + // to the merged package. + let mut resolve1 = Resolve::default(); + resolve1.push_str( + "a.wit", + r#" + package foo:bar@3.0.0; + + interface existing { + base-func: func(); + } + "#, + )?; + + let mut resolve2 = Resolve::default(); + resolve2.push_str( + "b.wit", + r#" + package foo:bar@3.1.0; + + interface existing { + base-func: func(); + } + + interface added { + new-func: func(); + } + "#, + )?; + + resolve1.merge(resolve2)?; + + assert_eq!(resolve1.packages.len(), 1); + let (_, pkg) = resolve1.packages.iter().next().unwrap(); + assert_eq!(pkg.name.version.as_ref().unwrap().to_string(), "3.1.0"); + assert!(pkg.interfaces.contains_key("existing")); + assert!(pkg.interfaces.contains_key("added")); + + let added_id = pkg.interfaces["added"]; + assert!(resolve1.interfaces[added_id] + .functions + .contains_key("new-func")); + + Ok(()) + } } From 73f74f69311b450c847bf75ba9feee7bbbde00da Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Thu, 13 Aug 2026 17:37:52 -0700 Subject: [PATCH 2/8] tests --- crates/wit-component/src/encoding/wit.rs | 23 +- crates/wit-component/tests/components.rs | 24 +- .../components/canon-names-cm32/component.wat | 366 ++++++++ .../canon-names-cm32/component.wit.print | 25 + .../components/canon-names-cm32/module.wat | 32 + .../components/canon-names-cm32/module.wit | 30 + .../component.wat | 125 +++ .../component.wit.print | 5 + .../error.txt | 1 + .../module.wat | 15 + .../module.wit | 30 + .../adapt-old.wat | 10 + .../adapt-old.wit | 19 + .../component.wat | 104 +++ .../component.wit.print | 5 + .../module.wat | 9 + .../module.wit | 14 + crates/wit-component/tests/interfaces.rs | 3 + .../tests/interfaces/canon-names-merge.wat | 27 + .../interfaces/canon-names-merge/app.wit | 5 + .../canon-names-merge/app.wit.print | 5 + .../canon-names-merge/deps/lib-v1/lib.wit | 6 + .../canon-names-merge/deps/lib-v2/lib.wit | 7 + .../interfaces/canon-names-wasi-http.wat | 881 ++++++++++++++++++ .../deps/cli/command.wit | 7 + .../deps/cli/environment.wit | 18 + .../canon-names-wasi-http/deps/cli/exit.wit | 4 + .../deps/cli/imports.wit | 20 + .../canon-names-wasi-http/deps/cli/run.wit | 4 + .../canon-names-wasi-http/deps/cli/stdio.wit | 17 + .../deps/cli/terminal.wit | 47 + .../deps/clocks/monotonic-clock.wit | 45 + .../deps/clocks/wall-clock.wit | 42 + .../deps/clocks/world.wit | 6 + .../deps/filesystem/preopens.wit | 8 + .../deps/filesystem/types.wit | 634 +++++++++++++ .../deps/filesystem/world.wit | 6 + .../canon-names-wasi-http/deps/io/error.wit | 34 + .../canon-names-wasi-http/deps/io/poll.wit | 41 + .../canon-names-wasi-http/deps/io/streams.wit | 251 +++++ .../canon-names-wasi-http/deps/io/world.wit | 6 + .../deps/random/insecure-seed.wit | 25 + .../deps/random/insecure.wit | 22 + .../deps/random/random.wit | 26 + .../deps/random/world.wit | 7 + .../deps/sockets/instance-network.wit | 9 + .../deps/sockets/ip-name-lookup.wit | 51 + .../deps/sockets/network.wit | 147 +++ .../deps/sockets/tcp-create-socket.wit | 26 + .../deps/sockets/tcp.wit | 321 +++++++ .../deps/sockets/udp-create-socket.wit | 26 + .../deps/sockets/udp.wit | 277 ++++++ .../deps/sockets/world.wit | 11 + .../canon-names-wasi-http/handler.wit | 43 + .../canon-names-wasi-http/http.wit.print | 583 ++++++++++++ .../canon-names-wasi-http/proxy.wit | 32 + .../canon-names-wasi-http/types.wit | 570 +++++++++++ crates/wit-parser/src/lib.rs | 40 +- crates/wit-parser/src/resolve/mod.rs | 55 +- crates/wit-parser/tests/all.rs | 4 + .../ui/canon-names-nested-with-semver.wit | 24 + .../canon-names-nested-with-semver.wit.json | 75 ++ .../tests/ui/canon-names-version-syntax.wit | 10 + .../ui/canon-names-version-syntax.wit.json | 17 + 64 files changed, 5333 insertions(+), 29 deletions(-) create mode 100644 crates/wit-component/tests/components/canon-names-cm32/component.wat create mode 100644 crates/wit-component/tests/components/canon-names-cm32/component.wit.print create mode 100644 crates/wit-component/tests/components/canon-names-cm32/module.wat create mode 100644 crates/wit-component/tests/components/canon-names-cm32/module.wit create mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wat create mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wit.print create mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt create mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat create mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit create mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat create mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit create mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wat create mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print create mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat create mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge.wat create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/app.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http.wat create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/http.wit.print create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit create mode 100644 crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit create mode 100644 crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit.json create mode 100644 crates/wit-parser/tests/ui/canon-names-version-syntax.wit create mode 100644 crates/wit-parser/tests/ui/canon-names-version-syntax.wit.json diff --git a/crates/wit-component/src/encoding/wit.rs b/crates/wit-component/src/encoding/wit.rs index 3ec0d44740..ac853441f8 100644 --- a/crates/wit-component/src/encoding/wit.rs +++ b/crates/wit-component/src/encoding/wit.rs @@ -210,11 +210,28 @@ impl Encoder<'_> { for interface in interfaces { encoder.interface = Some(interface); let iface = &self.resolve.interfaces[interface]; - let name = self.resolve.id_of(interface).unwrap(); + #[cfg(feature = "canon-names")] + let extern_name = { + let name = self.resolve.canonicalized_id_of(interface).unwrap(); + let suffix = self.resolve.version_suffix_of(interface); + ComponentExternName { + name: name.into(), + implements: None, + external_id: None, + version_suffix: suffix.map(|s| s.into()), + } + }; + #[cfg(not(feature = "canon-names"))] + let extern_name = ComponentExternName { + name: self.resolve.id_of(interface).unwrap().into(), + implements: None, + external_id: None, + version_suffix: None, + }; if interface == id { let idx = encoder.encode_instance(interface)?; log::trace!("exporting self as {idx}"); - encoder.outer.export(name, ComponentTypeRef::Instance(idx)); + encoder.outer.export(extern_name, ComponentTypeRef::Instance(idx)); } else { encoder.push_instance(); for (_, id) in iface.types.iter() { @@ -225,7 +242,7 @@ impl Encoder<'_> { encoder.outer.ty().instance(&instance); encoder.import_map.insert(interface, encoder.instances); encoder.instances += 1; - encoder.outer.import(name, ComponentTypeRef::Instance(idx)); + encoder.outer.import(extern_name, ComponentTypeRef::Instance(idx)); } } diff --git a/crates/wit-component/tests/components.rs b/crates/wit-component/tests/components.rs index 7f3d79e93b..b2acb4bdee 100644 --- a/crates/wit-component/tests/components.rs +++ b/crates/wit-component/tests/components.rs @@ -62,6 +62,10 @@ fn main() -> Result<()> { if !path.is_dir() { continue; } + let name = path.file_name().unwrap().to_str().unwrap(); + if cfg!(feature = "canon-names") != name.starts_with("canon-names-") { + continue; + } trials.push(Trial::test(path.to_str().unwrap().to_string(), move || { run_test(&path).map_err(|e| format!("{e:?}").into()) @@ -75,10 +79,24 @@ fn main() -> Result<()> { libtest_mimic::run(&args, trials).exit(); } +fn is_error_test(test_case: &str) -> bool { + test_case.starts_with("error-") || test_case.starts_with("canon-names-error-") +} + fn run_test(path: &Path) -> Result<()> { let test_case = path.file_stem().unwrap().to_str().unwrap(); let mut resolve = Resolve::default(); - let (pkg_id, _) = resolve.push_dir(&path)?; + let (pkg_id, _) = match resolve.push_dir(&path) { + Ok(v) => v, + Err(err) => { + if !is_error_test(test_case) { + return Err(err.into()); + } + let error_path = path.join("error.txt"); + assert_output(&format!("{err:#}"), &error_path)?; + return Ok(()); + } + }; // If this test case contained multiple packages, create separate sub-directories for // each. @@ -142,13 +160,13 @@ fn run_test(path: &Path) -> Result<()> { let bytes = match result { Ok(bytes) => { - if test_case.starts_with("error-") { + if is_error_test(test_case) { bail!("expected an error but got success"); } bytes } Err(err) => { - if !test_case.starts_with("error-") { + if !is_error_test(test_case) { return Err(err); } assert_output(&format!("{err:#}"), &error_path)?; diff --git a/crates/wit-component/tests/components/canon-names-cm32/component.wat b/crates/wit-component/tests/components/canon-names-cm32/component.wat new file mode 100644 index 0000000000..1bdf10cbe7 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-cm32/component.wat @@ -0,0 +1,366 @@ +(component + (type $ty-ns:pkg/i@0.2 (;0;) + (instance + (export (;0;) "r" (type (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (param "s" string) (result 1))) + (export (;0;) "[constructor]r" (func (type 2))) + (type (;3;) (borrow 0)) + (type (;4;) (func (param "self" 3) (result string))) + (export (;1;) "[method]r.m" (func (type 4))) + (type (;5;) (func (param "in" 1) (result 1))) + (export (;2;) "frob" (func (type 5))) + ) + ) + (import "ns:pkg/i@0.2" (versionsuffix ".1") (instance $ns:pkg/i@0.2 (;0;) (type $ty-ns:pkg/i@0.2))) + (type $ty-j (;1;) + (instance + (export (;0;) "r" (type (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (param "s" string) (result 1))) + (export (;0;) "[constructor]r" (func (type 2))) + (type (;3;) (borrow 0)) + (type (;4;) (func (param "self" 3) (result string))) + (export (;1;) "[method]r.m" (func (type 4))) + (type (;5;) (func (param "in" 1) (result 1))) + (export (;2;) "frob" (func (type 5))) + ) + ) + (import "j" (instance $j (;1;) (type $ty-j))) + (type (;2;) (func (result string))) + (import "f" (func $f (;0;) (type 2))) + (core module $main (;0;) + (type (;0;) (func (param i32))) + (type (;1;) (func (param i32 i32) (result i32))) + (type (;2;) (func (param i32 i32))) + (type (;3;) (func (param i32) (result i32))) + (type (;4;) (func (result i32))) + (type (;5;) (func (param i32 i32 i32 i32) (result i32))) + (type (;6;) (func)) + (import "cm32p2" "f" (func (;0;) (type 0))) + (import "cm32p2|ns:pkg/i@0.2" "[constructor]r" (func (;1;) (type 1))) + (import "cm32p2|ns:pkg/i@0.2" "[method]r.m" (func (;2;) (type 2))) + (import "cm32p2|ns:pkg/i@0.2" "frob" (func (;3;) (type 3))) + (import "cm32p2|ns:pkg/i@0.2" "r_drop" (func (;4;) (type 0))) + (import "cm32p2|j" "[constructor]r" (func (;5;) (type 1))) + (import "cm32p2|j" "[method]r.m" (func (;6;) (type 2))) + (import "cm32p2|j" "frob" (func (;7;) (type 3))) + (import "cm32p2|j" "r_drop" (func (;8;) (type 0))) + (import "cm32p2|_ex_ns:pkg/i@0.2" "r_drop" (func (;9;) (type 0))) + (import "cm32p2|_ex_ns:pkg/i@0.2" "r_new" (func (;10;) (type 3))) + (import "cm32p2|_ex_ns:pkg/i@0.2" "r_rep" (func (;11;) (type 3))) + (import "cm32p2|_ex_j" "r_drop" (func (;12;) (type 0))) + (import "cm32p2|_ex_j" "r_new" (func (;13;) (type 3))) + (import "cm32p2|_ex_j" "r_rep" (func (;14;) (type 3))) + (memory (;0;) 0) + (export "cm32p2_memory" (memory 0)) + (export "cm32p2||g" (func 15)) + (export "cm32p2||g_post" (func 16)) + (export "cm32p2|ns:pkg/i@0.2|[constructor]r" (func 17)) + (export "cm32p2|ns:pkg/i@0.2|[method]r.m" (func 18)) + (export "cm32p2|ns:pkg/i@0.2|frob" (func 19)) + (export "cm32p2|ns:pkg/i@0.2|r_dtor" (func 20)) + (export "cm32p2|j|[constructor]r" (func 21)) + (export "cm32p2|j|[method]r.m" (func 22)) + (export "cm32p2|j|frob" (func 23)) + (export "cm32p2|j|r_dtor" (func 24)) + (export "cm32p2_realloc" (func 25)) + (export "cm32p2_initialize" (func 26)) + (func (;15;) (type 4) (result i32) + unreachable + ) + (func (;16;) (type 0) (param i32) + unreachable + ) + (func (;17;) (type 1) (param i32 i32) (result i32) + unreachable + ) + (func (;18;) (type 3) (param i32) (result i32) + unreachable + ) + (func (;19;) (type 3) (param i32) (result i32) + unreachable + ) + (func (;20;) (type 0) (param i32) + unreachable + ) + (func (;21;) (type 1) (param i32 i32) (result i32) + unreachable + ) + (func (;22;) (type 3) (param i32) (result i32) + unreachable + ) + (func (;23;) (type 3) (param i32) (result i32) + unreachable + ) + (func (;24;) (type 0) (param i32) + unreachable + ) + (func (;25;) (type 5) (param i32 i32 i32 i32) (result i32) + unreachable + ) + (func (;26;) (type 6)) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + (processed-by "my-fake-bindgen" "123.45") + ) + ) + (core module $wit-component-shim-module (;1;) + (type (;0;) (func (param i32))) + (type (;1;) (func (param i32 i32) (result i32))) + (type (;2;) (func (param i32 i32))) + (type (;3;) (func (param i32))) + (table (;0;) 7 7 funcref) + (export "0" (func $indirect-cm32p2-f)) + (export "1" (func $"indirect-cm32p2|ns:pkg/i@0.2-[constructor]r")) + (export "2" (func $"indirect-cm32p2|ns:pkg/i@0.2-[method]r.m")) + (export "3" (func $"indirect-cm32p2|j-[constructor]r")) + (export "4" (func $"indirect-cm32p2|j-[method]r.m")) + (export "5" (func $dtor-r)) + (export "6" (func $"#func6 dtor-r")) + (export "$imports" (table 0)) + (func $indirect-cm32p2-f (;0;) (type 0) (param i32) + local.get 0 + i32.const 0 + call_indirect (type 0) + ) + (func $"indirect-cm32p2|ns:pkg/i@0.2-[constructor]r" (;1;) (type 1) (param i32 i32) (result i32) + local.get 0 + local.get 1 + i32.const 1 + call_indirect (type 1) + ) + (func $"indirect-cm32p2|ns:pkg/i@0.2-[method]r.m" (;2;) (type 2) (param i32 i32) + local.get 0 + local.get 1 + i32.const 2 + call_indirect (type 2) + ) + (func $"indirect-cm32p2|j-[constructor]r" (;3;) (type 1) (param i32 i32) (result i32) + local.get 0 + local.get 1 + i32.const 3 + call_indirect (type 1) + ) + (func $"indirect-cm32p2|j-[method]r.m" (;4;) (type 2) (param i32 i32) + local.get 0 + local.get 1 + i32.const 4 + call_indirect (type 2) + ) + (func $dtor-r (;5;) (type 3) (param i32) + local.get 0 + i32.const 5 + call_indirect (type 3) + ) + (func $"#func6 dtor-r" (@name "dtor-r") (;6;) (type 3) (param i32) + local.get 0 + i32.const 6 + call_indirect (type 3) + ) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) + ) + (core module $wit-component-fixup (;2;) + (type (;0;) (func (param i32))) + (type (;1;) (func (param i32 i32) (result i32))) + (type (;2;) (func (param i32 i32))) + (type (;3;) (func (param i32))) + (import "" "0" (func (;0;) (type 0))) + (import "" "1" (func (;1;) (type 1))) + (import "" "2" (func (;2;) (type 2))) + (import "" "3" (func (;3;) (type 1))) + (import "" "4" (func (;4;) (type 2))) + (import "" "5" (func (;5;) (type 3))) + (import "" "6" (func (;6;) (type 3))) + (import "" "$imports" (table (;0;) 7 7 funcref)) + (elem (;0;) (i32.const 0) func 0 1 2 3 4 5 6) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) + ) + (core instance $wit-component-shim-instance (;0;) (instantiate $wit-component-shim-module)) + (alias core export $wit-component-shim-instance "5" (core func $dtor-r (;0;))) + (type $r (;3;) (resource (rep i32) (dtor $dtor-r))) + (alias core export $wit-component-shim-instance "6" (core func $"#core-func1 dtor-r" (@name "dtor-r") (;1;))) + (type $"#type4 r" (@name "r") (;4;) (resource (rep i32) (dtor $"#core-func1 dtor-r"))) + (alias core export $wit-component-shim-instance "0" (core func $indirect-cm32p2-f (;2;))) + (core instance $cm32p2 (;1;) + (export "f" (func $indirect-cm32p2-f)) + ) + (alias core export $wit-component-shim-instance "1" (core func $"indirect-cm32p2|ns:pkg/i@0.2-[constructor]r" (;3;))) + (alias core export $wit-component-shim-instance "2" (core func $"indirect-cm32p2|ns:pkg/i@0.2-[method]r.m" (;4;))) + (alias export $ns:pkg/i@0.2 "frob" (func $frob (;1;))) + (core func $frob (;5;) (canon lower (func $frob))) + (alias export $ns:pkg/i@0.2 "r" (type $"#type5 r" (@name "r") (;5;))) + (core func $resource.drop (;6;) (canon resource.drop $"#type5 r")) + (core instance $cm32p2|ns:pkg/i@0.2 (;2;) + (export "[constructor]r" (func $"indirect-cm32p2|ns:pkg/i@0.2-[constructor]r")) + (export "[method]r.m" (func $"indirect-cm32p2|ns:pkg/i@0.2-[method]r.m")) + (export "frob" (func $frob)) + (export "r_drop" (func $resource.drop)) + ) + (alias core export $wit-component-shim-instance "3" (core func $"indirect-cm32p2|j-[constructor]r" (;7;))) + (alias core export $wit-component-shim-instance "4" (core func $"indirect-cm32p2|j-[method]r.m" (;8;))) + (alias export $j "frob" (func $"#func2 frob" (@name "frob") (;2;))) + (core func $"#core-func9 frob" (@name "frob") (;9;) (canon lower (func $"#func2 frob"))) + (alias export $j "r" (type $"#type6 r" (@name "r") (;6;))) + (core func $"#core-func10 resource.drop" (@name "resource.drop") (;10;) (canon resource.drop $"#type6 r")) + (core instance $cm32p2|j (;3;) + (export "[constructor]r" (func $"indirect-cm32p2|j-[constructor]r")) + (export "[method]r.m" (func $"indirect-cm32p2|j-[method]r.m")) + (export "frob" (func $"#core-func9 frob")) + (export "r_drop" (func $"#core-func10 resource.drop")) + ) + (core func $"#core-func11 resource.drop" (@name "resource.drop") (;11;) (canon resource.drop $r)) + (core func $resource.new (;12;) (canon resource.new $r)) + (core func $resource.rep (;13;) (canon resource.rep $r)) + (core instance $cm32p2|_ex_ns:pkg/i@0.2 (;4;) + (export "r_drop" (func $"#core-func11 resource.drop")) + (export "r_new" (func $resource.new)) + (export "r_rep" (func $resource.rep)) + ) + (core func $"#core-func14 resource.drop" (@name "resource.drop") (;14;) (canon resource.drop $"#type4 r")) + (core func $"#core-func15 resource.new" (@name "resource.new") (;15;) (canon resource.new $"#type4 r")) + (core func $"#core-func16 resource.rep" (@name "resource.rep") (;16;) (canon resource.rep $"#type4 r")) + (core instance $cm32p2|_ex_j (;5;) + (export "r_drop" (func $"#core-func14 resource.drop")) + (export "r_new" (func $"#core-func15 resource.new")) + (export "r_rep" (func $"#core-func16 resource.rep")) + ) + (core instance $main (;6;) (instantiate $main + (with "cm32p2" (instance $cm32p2)) + (with "cm32p2|ns:pkg/i@0.2" (instance $cm32p2|ns:pkg/i@0.2)) + (with "cm32p2|j" (instance $cm32p2|j)) + (with "cm32p2|_ex_ns:pkg/i@0.2" (instance $cm32p2|_ex_ns:pkg/i@0.2)) + (with "cm32p2|_ex_j" (instance $cm32p2|_ex_j)) + ) + ) + (alias core export $main "cm32p2_memory" (core memory $memory (;0;))) + (alias core export $wit-component-shim-instance "$imports" (core table $"shim table" (;0;))) + (alias core export $main "cm32p2_realloc" (core func $realloc (;17;))) + (core func $"#core-func18 indirect-cm32p2-f" (@name "indirect-cm32p2-f") (;18;) (canon lower (func $f) (memory $memory) (realloc $realloc) string-encoding=utf8)) + (alias export $ns:pkg/i@0.2 "[constructor]r" (func $"[constructor]r" (;3;))) + (core func $"#core-func19 indirect-cm32p2|ns:pkg/i@0.2-[constructor]r" (@name "indirect-cm32p2|ns:pkg/i@0.2-[constructor]r") (;19;) (canon lower (func $"[constructor]r") (memory $memory) string-encoding=utf8)) + (alias export $ns:pkg/i@0.2 "[method]r.m" (func $"[method]r.m" (;4;))) + (core func $"#core-func20 indirect-cm32p2|ns:pkg/i@0.2-[method]r.m" (@name "indirect-cm32p2|ns:pkg/i@0.2-[method]r.m") (;20;) (canon lower (func $"[method]r.m") (memory $memory) (realloc $realloc) string-encoding=utf8)) + (alias export $j "[constructor]r" (func $"#func5 [constructor]r" (@name "[constructor]r") (;5;))) + (core func $"#core-func21 indirect-cm32p2|j-[constructor]r" (@name "indirect-cm32p2|j-[constructor]r") (;21;) (canon lower (func $"#func5 [constructor]r") (memory $memory) string-encoding=utf8)) + (alias export $j "[method]r.m" (func $"#func6 [method]r.m" (@name "[method]r.m") (;6;))) + (core func $"#core-func22 indirect-cm32p2|j-[method]r.m" (@name "indirect-cm32p2|j-[method]r.m") (;22;) (canon lower (func $"#func6 [method]r.m") (memory $memory) (realloc $realloc) string-encoding=utf8)) + (alias core export $main "cm32p2|ns:pkg/i@0.2|r_dtor" (core func $cm32p2|ns:pkg/i@0.2|r_dtor (;23;))) + (alias core export $main "cm32p2|j|r_dtor" (core func $cm32p2|j|r_dtor (;24;))) + (core instance $fixup-args (;7;) + (export "$imports" (table $"shim table")) + (export "0" (func $"#core-func18 indirect-cm32p2-f")) + (export "1" (func $"#core-func19 indirect-cm32p2|ns:pkg/i@0.2-[constructor]r")) + (export "2" (func $"#core-func20 indirect-cm32p2|ns:pkg/i@0.2-[method]r.m")) + (export "3" (func $"#core-func21 indirect-cm32p2|j-[constructor]r")) + (export "4" (func $"#core-func22 indirect-cm32p2|j-[method]r.m")) + (export "5" (func $cm32p2|ns:pkg/i@0.2|r_dtor)) + (export "6" (func $cm32p2|j|r_dtor)) + ) + (core instance $fixup (;8;) (instantiate $wit-component-fixup + (with "" (instance $fixup-args)) + ) + ) + (alias core export $main "cm32p2_initialize" (core func $start (;25;))) + (core module $start-shim-module (;3;) + (type (;0;) (func)) + (import "" "" (func (;0;) (type 0))) + (start 0) + ) + (core instance $start-shim-args (;9;) + (export "" (func $start)) + ) + (core instance $start-shim-instance (;10;) (instantiate $start-shim-module + (with "" (instance $start-shim-args)) + ) + ) + (alias core export $main "cm32p2||g" (core func $cm32p2||g (;26;))) + (alias core export $main "cm32p2||g_post" (core func $cm32p2||g_post (;27;))) + (func $g (;7;) (type 2) (canon lift (core func $cm32p2||g) (memory $memory) string-encoding=utf8 (post-return $cm32p2||g_post))) + (export $"#func8 g" (@name "g") (;8;) "g" (func $g)) + (type (;7;) (own $r)) + (type (;8;) (func (param "s" string) (result 7))) + (alias core export $main "cm32p2|ns:pkg/i@0.2|[constructor]r" (core func $"cm32p2|ns:pkg/i@0.2|[constructor]r" (;28;))) + (func $"#func9 [constructor]r" (@name "[constructor]r") (;9;) (type 8) (canon lift (core func $"cm32p2|ns:pkg/i@0.2|[constructor]r") (memory $memory) (realloc $realloc) string-encoding=utf8)) + (type (;9;) (borrow $r)) + (type (;10;) (func (param "self" 9) (result string))) + (alias core export $main "cm32p2|ns:pkg/i@0.2|[method]r.m" (core func $"cm32p2|ns:pkg/i@0.2|[method]r.m" (;29;))) + (func $"#func10 [method]r.m" (@name "[method]r.m") (;10;) (type 10) (canon lift (core func $"cm32p2|ns:pkg/i@0.2|[method]r.m") (memory $memory) string-encoding=utf8)) + (type (;11;) (func (param "in" 7) (result 7))) + (alias core export $main "cm32p2|ns:pkg/i@0.2|frob" (core func $cm32p2|ns:pkg/i@0.2|frob (;30;))) + (func $"#func11 frob" (@name "frob") (;11;) (type 11) (canon lift (core func $cm32p2|ns:pkg/i@0.2|frob))) + (component $ns:pkg/i@0.2-shim-component (;0;) + (import "import-type-r" (type (;0;) (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (param "s" string) (result 1))) + (import "import-constructor-r" (func (;0;) (type 2))) + (type (;3;) (borrow 0)) + (type (;4;) (func (param "self" 3) (result string))) + (import "import-method-r-m" (func (;1;) (type 4))) + (type (;5;) (func (param "in" 1) (result 1))) + (import "import-func-frob" (func (;2;) (type 5))) + (export (;6;) "r" (type 0)) + (type (;7;) (own 6)) + (type (;8;) (func (param "s" string) (result 7))) + (export (;3;) "[constructor]r" (func 0) (func (type 8))) + (type (;9;) (borrow 6)) + (type (;10;) (func (param "self" 9) (result string))) + (export (;4;) "[method]r.m" (func 1) (func (type 10))) + (type (;11;) (func (param "in" 7) (result 7))) + (export (;5;) "frob" (func 2) (func (type 11))) + ) + (instance $ns:pkg/i@0.2-shim-instance (;2;) (instantiate $ns:pkg/i@0.2-shim-component + (with "import-constructor-r" (func $"#func9 [constructor]r")) + (with "import-method-r-m" (func $"#func10 [method]r.m")) + (with "import-func-frob" (func $"#func11 frob")) + (with "import-type-r" (type $r)) + ) + ) + (export $"#instance3 ns:pkg/i@0.2" (@name "ns:pkg/i@0.2") (;3;) "ns:pkg/i@0.2" (versionsuffix ".1") (instance $ns:pkg/i@0.2-shim-instance)) + (type (;12;) (own $"#type4 r")) + (type (;13;) (func (param "s" string) (result 12))) + (alias core export $main "cm32p2|j|[constructor]r" (core func $"cm32p2|j|[constructor]r" (;31;))) + (func $"#func12 [constructor]r" (@name "[constructor]r") (;12;) (type 13) (canon lift (core func $"cm32p2|j|[constructor]r") (memory $memory) (realloc $realloc) string-encoding=utf8)) + (type (;14;) (borrow $"#type4 r")) + (type (;15;) (func (param "self" 14) (result string))) + (alias core export $main "cm32p2|j|[method]r.m" (core func $"cm32p2|j|[method]r.m" (;32;))) + (func $"#func13 [method]r.m" (@name "[method]r.m") (;13;) (type 15) (canon lift (core func $"cm32p2|j|[method]r.m") (memory $memory) string-encoding=utf8)) + (type (;16;) (func (param "in" 12) (result 12))) + (alias core export $main "cm32p2|j|frob" (core func $cm32p2|j|frob (;33;))) + (func $"#func14 frob" (@name "frob") (;14;) (type 16) (canon lift (core func $cm32p2|j|frob))) + (component $j-shim-component (;1;) + (import "import-type-r" (type (;0;) (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (param "s" string) (result 1))) + (import "import-constructor-r" (func (;0;) (type 2))) + (type (;3;) (borrow 0)) + (type (;4;) (func (param "self" 3) (result string))) + (import "import-method-r-m" (func (;1;) (type 4))) + (type (;5;) (func (param "in" 1) (result 1))) + (import "import-func-frob" (func (;2;) (type 5))) + (export (;6;) "r" (type 0)) + (type (;7;) (own 6)) + (type (;8;) (func (param "s" string) (result 7))) + (export (;3;) "[constructor]r" (func 0) (func (type 8))) + (type (;9;) (borrow 6)) + (type (;10;) (func (param "self" 9) (result string))) + (export (;4;) "[method]r.m" (func 1) (func (type 10))) + (type (;11;) (func (param "in" 7) (result 7))) + (export (;5;) "frob" (func 2) (func (type 11))) + ) + (instance $j-shim-instance (;4;) (instantiate $j-shim-component + (with "import-constructor-r" (func $"#func12 [constructor]r")) + (with "import-method-r-m" (func $"#func13 [method]r.m")) + (with "import-func-frob" (func $"#func14 frob")) + (with "import-type-r" (type $"#type4 r")) + ) + ) + (export $"#instance5 j" (@name "j") (;5;) "j" (instance $j-shim-instance)) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) +) diff --git a/crates/wit-component/tests/components/canon-names-cm32/component.wit.print b/crates/wit-component/tests/components/canon-names-cm32/component.wit.print new file mode 100644 index 0000000000..a01bff8de2 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-cm32/component.wit.print @@ -0,0 +1,25 @@ +package root:component; + +world root { + import ns:pkg/i@0.2.1; + import j: interface { + resource r { + constructor(s: string); + m: func() -> string; + } + + frob: func(in: r) -> r; + } + import f: func() -> string; + + export g: func() -> string; + export ns:pkg/i@0.2.1; + export j: interface { + resource r { + constructor(s: string); + m: func() -> string; + } + + frob: func(in: r) -> r; + } +} diff --git a/crates/wit-component/tests/components/canon-names-cm32/module.wat b/crates/wit-component/tests/components/canon-names-cm32/module.wat new file mode 100644 index 0000000000..6b1b47b5d4 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-cm32/module.wat @@ -0,0 +1,32 @@ +(module + (import "cm32p2" "f" (func (param i32))) + (import "cm32p2|ns:pkg/i@0.2" "[constructor]r" (func (param i32 i32) (result i32))) + (import "cm32p2|ns:pkg/i@0.2" "[method]r.m" (func (param i32 i32))) + (import "cm32p2|ns:pkg/i@0.2" "frob" (func (param i32) (result i32))) + (import "cm32p2|ns:pkg/i@0.2" "r_drop" (func (param i32))) + (import "cm32p2|j" "[constructor]r" (func (param i32 i32) (result i32))) + (import "cm32p2|j" "[method]r.m" (func (param i32 i32))) + (import "cm32p2|j" "frob" (func (param i32) (result i32))) + (import "cm32p2|j" "r_drop" (func (param i32))) + (import "cm32p2|_ex_ns:pkg/i@0.2" "r_drop" (func (param i32))) + (import "cm32p2|_ex_ns:pkg/i@0.2" "r_new" (func (param i32) (result i32))) + (import "cm32p2|_ex_ns:pkg/i@0.2" "r_rep" (func (param i32) (result i32))) + (import "cm32p2|_ex_j" "r_drop" (func (param i32))) + (import "cm32p2|_ex_j" "r_new" (func (param i32) (result i32))) + (import "cm32p2|_ex_j" "r_rep" (func (param i32) (result i32))) + + (memory (export "cm32p2_memory") 0) + + (func (export "cm32p2||g") (result i32) unreachable) + (func (export "cm32p2||g_post") (param i32) unreachable) + (func (export "cm32p2|ns:pkg/i@0.2|[constructor]r") (param i32 i32) (result i32) unreachable) + (func (export "cm32p2|ns:pkg/i@0.2|[method]r.m") (param i32) (result i32) unreachable) + (func (export "cm32p2|ns:pkg/i@0.2|frob") (param i32) (result i32) unreachable) + (func (export "cm32p2|ns:pkg/i@0.2|r_dtor") (param i32) unreachable) + (func (export "cm32p2|j|[constructor]r") (param i32 i32) (result i32) unreachable) + (func (export "cm32p2|j|[method]r.m") (param i32) (result i32) unreachable) + (func (export "cm32p2|j|frob") (param i32) (result i32) unreachable) + (func (export "cm32p2|j|r_dtor") (param i32) unreachable) + (func (export "cm32p2_realloc") (param i32 i32 i32 i32) (result i32) unreachable) + (func (export "cm32p2_initialize")) +) diff --git a/crates/wit-component/tests/components/canon-names-cm32/module.wit b/crates/wit-component/tests/components/canon-names-cm32/module.wit new file mode 100644 index 0000000000..32d8820e8f --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-cm32/module.wit @@ -0,0 +1,30 @@ +package ns:pkg@0.2.1; + +interface i { + resource r { + constructor(s: string); + m: func() -> string; + } + frob: func(in: r) -> r; +} + +world module { + import f: func() -> string; + import i; + import j: interface { + resource r { + constructor(s: string); + m: func() -> string; + } + frob: func(in: r) -> r; + } + export g: func() -> string; + export i; + export j: interface { + resource r { + constructor(s: string); + m: func() -> string; + } + frob: func(in: r) -> r; + } +} diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wat b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wat new file mode 100644 index 0000000000..9ed9267bc7 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wat @@ -0,0 +1,125 @@ +(component + (type $ty-a:b/c@0.1 (;0;) + (instance + (export (;0;) "r" (type (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (result 1))) + (export (;0;) "[constructor]r" (func (type 2))) + (type (;3;) (borrow 0)) + (type (;4;) (func (param "self" 3))) + (export (;1;) "[method]r.x" (func (type 4))) + (type (;5;) (func (param "x" string))) + (export (;2;) "x" (func (type 5))) + (export (;3;) "x2" (func (type 5))) + (type (;6;) (func)) + (export (;4;) "y" (func (type 6))) + ) + ) + (import "a:b/c@0.1" (versionsuffix ".1") (instance $a:b/c@0.1 (;0;) (type $ty-a:b/c@0.1))) + (core module $main (;0;) + (type (;0;) (func (result i32))) + (type (;1;) (func (param i32))) + (type (;2;) (func (param i32 i32))) + (type (;3;) (func)) + (import "a:b/c@0.1.0" "[constructor]r" (func (;0;) (type 0))) + (import "a:b/c@0.1.0" "[resource-drop]r" (func (;1;) (type 1))) + (import "a:b/c@0.1.0" "x" (func (;2;) (type 2))) + (import "a:b/c@0.1.0" "x2" (func (;3;) (type 2))) + (import "a:b/c@0.1.1" "[constructor]r" (func (;4;) (type 0))) + (import "a:b/c@0.1.1" "[resource-drop]r" (func (;5;) (type 1))) + (import "a:b/c@0.1.1" "[method]r.x" (func (;6;) (type 1))) + (import "a:b/c@0.1.1" "x" (func (;7;) (type 2))) + (import "a:b/c@0.1.1" "x2" (func (;8;) (type 2))) + (import "a:b/c@0.1.1" "y" (func (;9;) (type 3))) + (memory (;0;) 1) + (export "memory" (memory 0)) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + (processed-by "my-fake-bindgen" "123.45") + ) + ) + (core module $wit-component-shim-module (;1;) + (type (;0;) (func (param i32 i32))) + (table (;0;) 2 2 funcref) + (export "0" (func $indirect-a:b/c@0.1.0-x)) + (export "1" (func $indirect-a:b/c@0.1.0-x2)) + (export "$imports" (table 0)) + (func $indirect-a:b/c@0.1.0-x (;0;) (type 0) (param i32 i32) + local.get 0 + local.get 1 + i32.const 0 + call_indirect (type 0) + ) + (func $indirect-a:b/c@0.1.0-x2 (;1;) (type 0) (param i32 i32) + local.get 0 + local.get 1 + i32.const 1 + call_indirect (type 0) + ) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) + ) + (core module $wit-component-fixup (;2;) + (type (;0;) (func (param i32 i32))) + (import "" "0" (func (;0;) (type 0))) + (import "" "1" (func (;1;) (type 0))) + (import "" "$imports" (table (;0;) 2 2 funcref)) + (elem (;0;) (i32.const 0) func 0 1) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) + ) + (core instance $wit-component-shim-instance (;0;) (instantiate $wit-component-shim-module)) + (alias export $a:b/c@0.1 "[constructor]r" (func $"[constructor]r" (;0;))) + (core func $"[constructor]r" (;0;) (canon lower (func $"[constructor]r"))) + (alias export $a:b/c@0.1 "r" (type $r (;1;))) + (core func $resource.drop (;1;) (canon resource.drop $r)) + (alias core export $wit-component-shim-instance "0" (core func $indirect-a:b/c@0.1.0-x (;2;))) + (alias core export $wit-component-shim-instance "1" (core func $indirect-a:b/c@0.1.0-x2 (;3;))) + (core instance $a:b/c@0.1.0 (;1;) + (export "[constructor]r" (func $"[constructor]r")) + (export "[resource-drop]r" (func $resource.drop)) + (export "x" (func $indirect-a:b/c@0.1.0-x)) + (export "x2" (func $indirect-a:b/c@0.1.0-x2)) + ) + (alias export $a:b/c@0.1 "[constructor]r" (func $"#func1 [constructor]r" (@name "[constructor]r") (;1;))) + (core func $"#core-func4 [constructor]r" (@name "[constructor]r") (;4;) (canon lower (func $"#func1 [constructor]r"))) + (alias export $a:b/c@0.1 "r" (type $"#type2 r" (@name "r") (;2;))) + (core func $"#core-func5 resource.drop" (@name "resource.drop") (;5;) (canon resource.drop $"#type2 r")) + (alias export $a:b/c@0.1 "[method]r.x" (func $"[method]r.x" (;2;))) + (core func $"[method]r.x" (;6;) (canon lower (func $"[method]r.x"))) + (alias export $a:b/c@0.1 "y" (func $y (;3;))) + (core func $y (;7;) (canon lower (func $y))) + (core instance $a:b/c@0.1.1 (;2;) + (export "[constructor]r" (func $"#core-func4 [constructor]r")) + (export "[resource-drop]r" (func $"#core-func5 resource.drop")) + (export "[method]r.x" (func $"[method]r.x")) + (export "x" (func $indirect-a:b/c@0.1.0-x)) + (export "x2" (func $indirect-a:b/c@0.1.0-x2)) + (export "y" (func $y)) + ) + (core instance $main (;3;) (instantiate $main + (with "a:b/c@0.1.0" (instance $a:b/c@0.1.0)) + (with "a:b/c@0.1.1" (instance $a:b/c@0.1.1)) + ) + ) + (alias core export $main "memory" (core memory $memory (;0;))) + (alias core export $wit-component-shim-instance "$imports" (core table $"shim table" (;0;))) + (alias export $a:b/c@0.1 "x" (func $x (;4;))) + (core func $"#core-func8 indirect-a:b/c@0.1.0-x" (@name "indirect-a:b/c@0.1.0-x") (;8;) (canon lower (func $x) (memory $memory) string-encoding=utf8)) + (alias export $a:b/c@0.1 "x2" (func $x2 (;5;))) + (core func $"#core-func9 indirect-a:b/c@0.1.0-x2" (@name "indirect-a:b/c@0.1.0-x2") (;9;) (canon lower (func $x2) (memory $memory) string-encoding=utf8)) + (core instance $fixup-args (;4;) + (export "$imports" (table $"shim table")) + (export "0" (func $"#core-func8 indirect-a:b/c@0.1.0-x")) + (export "1" (func $"#core-func9 indirect-a:b/c@0.1.0-x2")) + ) + (core instance $fixup (;5;) (instantiate $wit-component-fixup + (with "" (instance $fixup-args)) + ) + ) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) +) diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wit.print b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wit.print new file mode 100644 index 0000000000..1a2ed3c569 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wit.print @@ -0,0 +1,5 @@ +package root:component; + +world root { + import a:b/c@0.1.1; +} diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt new file mode 100644 index 0000000000..bc870c544b --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt @@ -0,0 +1 @@ +failed to parse package: tests/components/canon-names-error-merge-import-versions: interface cannot be imported more than once \ No newline at end of file diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat new file mode 100644 index 0000000000..b23e81cc96 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat @@ -0,0 +1,15 @@ +(module + (import "a:b/c@0.1.0" "[constructor]r" (func (result i32))) + (import "a:b/c@0.1.0" "[resource-drop]r" (func (param i32))) + (import "a:b/c@0.1.0" "x" (func (param i32 i32))) + (import "a:b/c@0.1.0" "x2" (func (param i32 i32))) + + (import "a:b/c@0.1.1" "[constructor]r" (func (result i32))) + (import "a:b/c@0.1.1" "[resource-drop]r" (func (param i32))) + (import "a:b/c@0.1.1" "[method]r.x" (func (param i32))) + (import "a:b/c@0.1.1" "x" (func (param i32 i32))) + (import "a:b/c@0.1.1" "x2" (func (param i32 i32))) + (import "a:b/c@0.1.1" "y" (func)) + + (memory (export "memory") 1) +) diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit new file mode 100644 index 0000000000..63dacf4115 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit @@ -0,0 +1,30 @@ +package foo:foo; + +world module { + import a:b/c@0.1.0; + import a:b/c@0.1.1; +} + +package a:b@0.1.0 { + interface c { + resource r { + constructor(); + } + x: func(x: string); + x2: func(x: string); + } +} + +package a:b@0.1.1 { + interface c { + x: func(x: string); + x2: func(x: string); + y: func(); + + resource r { + constructor(); + + x: func(); + } + } +} diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat new file mode 100644 index 0000000000..6a32ffa471 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat @@ -0,0 +1,10 @@ +(module + (import "a:b/c@0.1.1" "[constructor]r" (func (result i32))) + (import "a:b/c@0.1.1" "[resource-drop]r" (func (param i32))) + (import "a:b/c@0.1.1" "[method]r.x" (func (param i32))) + (import "a:b/c@0.1.1" "x" (func (param i32 i32))) + (import "a:b/c@0.1.1" "y" (func)) + + (func (export "f")) +) + diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit new file mode 100644 index 0000000000..842ec11b64 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit @@ -0,0 +1,19 @@ +package foo:foo; + +world adapt-old { + import a:b/c@0.1.1; +} + +package a:b@0.1.1 { + interface c { + x: func(x: string); + y: func(); + + resource r { + constructor(); + + x: func(); + } + } +} + diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wat b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wat new file mode 100644 index 0000000000..cff4614b2d --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wat @@ -0,0 +1,104 @@ +(component + (type $ty-a:b/c@0.1 (;0;) + (instance + (export (;0;) "r" (type (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (result 1))) + (export (;0;) "[constructor]r" (func (type 2))) + (type (;3;) (func (param "x" string))) + (export (;1;) "x" (func (type 3))) + ) + ) + (import "a:b/c@0.1" (versionsuffix ".1") (instance $a:b/c@0.1 (;0;) (type $ty-a:b/c@0.1))) + (core module $main (;0;) + (type (;0;) (func)) + (type (;1;) (func (result i32))) + (type (;2;) (func (param i32))) + (type (;3;) (func (param i32 i32))) + (import "old" "f" (func (;0;) (type 0))) + (import "a:b/c@0.1.0" "[constructor]r" (func (;1;) (type 1))) + (import "a:b/c@0.1.0" "[resource-drop]r" (func (;2;) (type 2))) + (import "a:b/c@0.1.0" "x" (func (;3;) (type 3))) + (memory (;0;) 1) + (export "memory" (memory 0)) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + (processed-by "my-fake-bindgen" "123.45") + ) + ) + (core module $wit-component:adapter:old (;1;) + (type (;0;) (func)) + (export "f" (func 0)) + (func (;0;) (type 0)) + ) + (core module $wit-component-shim-module (;2;) + (type (;0;) (func)) + (type (;1;) (func (param i32 i32))) + (table (;0;) 2 2 funcref) + (export "0" (func $adapt-old-f)) + (export "1" (func $indirect-a:b/c@0.1.0-x)) + (export "$imports" (table 0)) + (func $adapt-old-f (;0;) (type 0) + i32.const 0 + call_indirect (type 0) + ) + (func $indirect-a:b/c@0.1.0-x (;1;) (type 1) (param i32 i32) + local.get 0 + local.get 1 + i32.const 1 + call_indirect (type 1) + ) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) + ) + (core module $wit-component-fixup (;3;) + (type (;0;) (func)) + (type (;1;) (func (param i32 i32))) + (import "" "0" (func (;0;) (type 0))) + (import "" "1" (func (;1;) (type 1))) + (import "" "$imports" (table (;0;) 2 2 funcref)) + (elem (;0;) (i32.const 0) func 0 1) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) + ) + (core instance $wit-component-shim-instance (;0;) (instantiate $wit-component-shim-module)) + (alias core export $wit-component-shim-instance "0" (core func $adapt-old-f (;0;))) + (core instance $old (;1;) + (export "f" (func $adapt-old-f)) + ) + (alias export $a:b/c@0.1 "[constructor]r" (func $"[constructor]r" (;0;))) + (core func $"[constructor]r" (;1;) (canon lower (func $"[constructor]r"))) + (alias export $a:b/c@0.1 "r" (type $r (;1;))) + (core func $resource.drop (;2;) (canon resource.drop $r)) + (alias core export $wit-component-shim-instance "1" (core func $indirect-a:b/c@0.1.0-x (;3;))) + (core instance $a:b/c@0.1.0 (;2;) + (export "[constructor]r" (func $"[constructor]r")) + (export "[resource-drop]r" (func $resource.drop)) + (export "x" (func $indirect-a:b/c@0.1.0-x)) + ) + (core instance $main (;3;) (instantiate $main + (with "old" (instance $old)) + (with "a:b/c@0.1.0" (instance $a:b/c@0.1.0)) + ) + ) + (alias core export $main "memory" (core memory $memory (;0;))) + (core instance $"#core-instance4 old" (@name "old") (;4;) (instantiate $wit-component:adapter:old)) + (alias core export $wit-component-shim-instance "$imports" (core table $"shim table" (;0;))) + (alias core export $"#core-instance4 old" "f" (core func $f (;4;))) + (alias export $a:b/c@0.1 "x" (func $x (;1;))) + (core func $"#core-func5 indirect-a:b/c@0.1.0-x" (@name "indirect-a:b/c@0.1.0-x") (;5;) (canon lower (func $x) (memory $memory) string-encoding=utf8)) + (core instance $fixup-args (;5;) + (export "$imports" (table $"shim table")) + (export "0" (func $f)) + (export "1" (func $"#core-func5 indirect-a:b/c@0.1.0-x")) + ) + (core instance $fixup (;6;) (instantiate $wit-component-fixup + (with "" (instance $fixup-args)) + ) + ) + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) +) diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print new file mode 100644 index 0000000000..1a2ed3c569 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print @@ -0,0 +1,5 @@ +package root:component; + +world root { + import a:b/c@0.1.1; +} diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat new file mode 100644 index 0000000000..dafd15681a --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat @@ -0,0 +1,9 @@ +(module + (import "old" "f" (func)) + + (import "a:b/c@0.1.0" "[constructor]r" (func (result i32))) + (import "a:b/c@0.1.0" "[resource-drop]r" (func (param i32))) + (import "a:b/c@0.1.0" "x" (func (param i32 i32))) + + (memory (export "memory") 1) +) diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit new file mode 100644 index 0000000000..6e60c34822 --- /dev/null +++ b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit @@ -0,0 +1,14 @@ +package foo:foo; + +world module { + import a:b/c@0.1.0; +} + +package a:b@0.1.0 { + interface c { + resource r { + constructor(); + } + x: func(x: string); + } +} diff --git a/crates/wit-component/tests/interfaces.rs b/crates/wit-component/tests/interfaces.rs index d89676df1b..6881228062 100644 --- a/crates/wit-component/tests/interfaces.rs +++ b/crates/wit-component/tests/interfaces.rs @@ -30,6 +30,9 @@ fn main() -> Result<()> { }; let is_dir = path.is_dir(); let is_test = is_dir || name.ends_with(".wit"); + if cfg!(feature = "canon-names") != name.starts_with("canon-names-") { + continue; + } if is_test { trials.push(Trial::test(name.to_string(), move || { run_test(&path, is_dir) diff --git a/crates/wit-component/tests/interfaces/canon-names-merge.wat b/crates/wit-component/tests/interfaces/canon-names-merge.wat new file mode 100644 index 0000000000..53265b6c7d --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge.wat @@ -0,0 +1,27 @@ +(component + (type (;0;) + (component + (type (;0;) + (component + (type (;0;) + (instance + (type (;0;) u32) + (export (;1;) "my-type" (type (eq 0))) + (type (;2;) (func (result 1))) + (export (;0;) "my-func" (func (type 2))) + (type (;3;) (func (param "x" 1) (result string))) + (export (;1;) "added-func" (func (type 3))) + ) + ) + (import "test:lib/types@1" (versionsuffix ".2.0") (instance (;0;) (type 0))) + ) + ) + (export (;0;) "test:app/my-world@1.0.0" (component (type 0))) + ) + ) + (export (;1;) "my-world" (type 0)) + (@custom "package-docs" "\01{}") + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) +) diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/app.wit b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit new file mode 100644 index 0000000000..11c930f5eb --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit @@ -0,0 +1,5 @@ +package test:app@1.0.0; + +world my-world { + import test:lib/types@1.2.0; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print new file mode 100644 index 0000000000..3d8b6b204e --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print @@ -0,0 +1,5 @@ +package test:app@1.0.0; + +world my-world { + import test:lib/types@1.2.0; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit new file mode 100644 index 0000000000..e7d5c0e8d3 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit @@ -0,0 +1,6 @@ +package test:lib@1.0.0; + +interface types { + type my-type = u32; + my-func: func() -> my-type; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit new file mode 100644 index 0000000000..d0945528cf --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit @@ -0,0 +1,7 @@ +package test:lib@1.2.0; + +interface types { + type my-type = u32; + my-func: func() -> my-type; + added-func: func(x: my-type) -> string; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http.wat b/crates/wit-component/tests/interfaces/canon-names-wasi-http.wat new file mode 100644 index 0000000000..5bc86427c0 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http.wat @@ -0,0 +1,881 @@ +(component + (type (;0;) + (component + (type (;0;) + (instance + (export (;0;) "pollable" (type (sub resource))) + ) + ) + (import "wasi:io/poll@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;0;) (type 0))) + (alias export 0 "pollable" (type (;1;))) + (type (;2;) + (instance + (alias outer 1 1 (type (;0;))) + (export (;1;) "pollable" (type (eq 0))) + (type (;2;) u64) + (export (;3;) "instant" (type (eq 2))) + (type (;4;) u64) + (export (;5;) "duration" (type (eq 4))) + ) + ) + (import "wasi:clocks/monotonic-clock@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;1;) (type 2))) + (type (;3;) + (instance + (export (;0;) "error" (type (sub resource))) + ) + ) + (import "wasi:io/error@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;2;) (type 3))) + (alias export 2 "error" (type (;4;))) + (type (;5;) + (instance + (alias outer 1 4 (type (;0;))) + (export (;1;) "error" (type (eq 0))) + (alias outer 1 1 (type (;2;))) + (export (;3;) "pollable" (type (eq 2))) + (type (;4;) (own 1)) + (type (;5;) (variant (case "last-operation-failed" 4) (case "closed"))) + (export (;6;) "stream-error" (type (eq 5))) + (export (;7;) "input-stream" (type (sub resource))) + (export (;8;) "output-stream" (type (sub resource))) + ) + ) + (import "wasi:io/streams@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;3;) (type 5))) + (alias export 1 "duration" (type (;6;))) + (alias export 3 "input-stream" (type (;7;))) + (alias export 3 "output-stream" (type (;8;))) + (type (;9;) + (instance + (alias outer 1 6 (type (;0;))) + (export (;1;) "duration" (type (eq 0))) + (alias outer 1 7 (type (;2;))) + (export (;3;) "input-stream" (type (eq 2))) + (alias outer 1 8 (type (;4;))) + (export (;5;) "output-stream" (type (eq 4))) + (alias outer 1 4 (type (;6;))) + (export (;7;) "io-error" (type (eq 6))) + (alias outer 1 1 (type (;8;))) + (export (;9;) "pollable" (type (eq 8))) + (type (;10;) (variant (case "get") (case "head") (case "post") (case "put") (case "delete") (case "connect") (case "options") (case "trace") (case "patch") (case "other" string))) + (export (;11;) "method" (type (eq 10))) + (type (;12;) (variant (case "HTTP") (case "HTTPS") (case "other" string))) + (export (;13;) "scheme" (type (eq 12))) + (type (;14;) (option string)) + (type (;15;) (option u16)) + (type (;16;) (record (field "rcode" 14) (field "info-code" 15))) + (export (;17;) "DNS-error-payload" (type (eq 16))) + (type (;18;) (option u8)) + (type (;19;) (record (field "alert-id" 18) (field "alert-message" 14))) + (export (;20;) "TLS-alert-received-payload" (type (eq 19))) + (type (;21;) (option u32)) + (type (;22;) (record (field "field-name" 14) (field "field-size" 21))) + (export (;23;) "field-size-payload" (type (eq 22))) + (type (;24;) (option u64)) + (type (;25;) (option 23)) + (type (;26;) (variant (case "DNS-timeout") (case "DNS-error" 17) (case "destination-not-found") (case "destination-unavailable") (case "destination-IP-prohibited") (case "destination-IP-unroutable") (case "connection-refused") (case "connection-terminated") (case "connection-timeout") (case "connection-read-timeout") (case "connection-write-timeout") (case "connection-limit-reached") (case "TLS-protocol-error") (case "TLS-certificate-error") (case "TLS-alert-received" 20) (case "HTTP-request-denied") (case "HTTP-request-length-required") (case "HTTP-request-body-size" 24) (case "HTTP-request-method-invalid") (case "HTTP-request-URI-invalid") (case "HTTP-request-URI-too-long") (case "HTTP-request-header-section-size" 21) (case "HTTP-request-header-size" 25) (case "HTTP-request-trailer-section-size" 21) (case "HTTP-request-trailer-size" 23) (case "HTTP-response-incomplete") (case "HTTP-response-header-section-size" 21) (case "HTTP-response-header-size" 23) (case "HTTP-response-body-size" 24) (case "HTTP-response-trailer-section-size" 21) (case "HTTP-response-trailer-size" 23) (case "HTTP-response-transfer-coding" 14) (case "HTTP-response-content-coding" 14) (case "HTTP-response-timeout") (case "HTTP-upgrade-failed") (case "HTTP-protocol-error") (case "loop-detected") (case "configuration-error") (case "internal-error" 14))) + (export (;27;) "error-code" (type (eq 26))) + (type (;28;) (variant (case "invalid-syntax") (case "forbidden") (case "immutable"))) + (export (;29;) "header-error" (type (eq 28))) + (type (;30;) string) + (export (;31;) "field-key" (type (eq 30))) + (type (;32;) (list u8)) + (export (;33;) "field-value" (type (eq 32))) + (export (;34;) "fields" (type (sub resource))) + (export (;35;) "headers" (type (eq 34))) + (export (;36;) "trailers" (type (eq 34))) + (export (;37;) "incoming-request" (type (sub resource))) + (export (;38;) "outgoing-request" (type (sub resource))) + (export (;39;) "request-options" (type (sub resource))) + (export (;40;) "response-outparam" (type (sub resource))) + (type (;41;) u16) + (export (;42;) "status-code" (type (eq 41))) + (export (;43;) "incoming-response" (type (sub resource))) + (export (;44;) "incoming-body" (type (sub resource))) + (export (;45;) "future-trailers" (type (sub resource))) + (export (;46;) "outgoing-response" (type (sub resource))) + (export (;47;) "outgoing-body" (type (sub resource))) + (export (;48;) "future-incoming-response" (type (sub resource))) + (type (;49;) (own 34)) + (type (;50;) (func (result 49))) + (export (;0;) "[constructor]fields" (func (type 50))) + (type (;51;) (tuple 31 33)) + (type (;52;) (list 51)) + (type (;53;) (result 49 (error 29))) + (type (;54;) (func (param "entries" 52) (result 53))) + (export (;1;) "[static]fields.from-list" (func (type 54))) + (type (;55;) (borrow 34)) + (type (;56;) (list 33)) + (type (;57;) (func (param "self" 55) (param "name" 31) (result 56))) + (export (;2;) "[method]fields.get" (func (type 57))) + (type (;58;) (func (param "self" 55) (param "name" 31) (result bool))) + (export (;3;) "[method]fields.has" (func (type 58))) + (type (;59;) (result (error 29))) + (type (;60;) (func (param "self" 55) (param "name" 31) (param "value" 56) (result 59))) + (export (;4;) "[method]fields.set" (func (type 60))) + (type (;61;) (func (param "self" 55) (param "name" 31) (result 59))) + (export (;5;) "[method]fields.delete" (func (type 61))) + (type (;62;) (func (param "self" 55) (param "name" 31) (param "value" 33) (result 59))) + (export (;6;) "[method]fields.append" (func (type 62))) + (type (;63;) (func (param "self" 55) (result 52))) + (export (;7;) "[method]fields.entries" (func (type 63))) + (type (;64;) (func (param "self" 55) (result 49))) + (export (;8;) "[method]fields.clone" (func (type 64))) + (type (;65;) (borrow 37)) + (type (;66;) (func (param "self" 65) (result 11))) + (export (;9;) "[method]incoming-request.method" (func (type 66))) + (type (;67;) (func (param "self" 65) (result 14))) + (export (;10;) "[method]incoming-request.path-with-query" (func (type 67))) + (type (;68;) (option 13)) + (type (;69;) (func (param "self" 65) (result 68))) + (export (;11;) "[method]incoming-request.scheme" (func (type 69))) + (export (;12;) "[method]incoming-request.authority" (func (type 67))) + (type (;70;) (own 35)) + (type (;71;) (func (param "self" 65) (result 70))) + (export (;13;) "[method]incoming-request.headers" (func (type 71))) + (type (;72;) (own 44)) + (type (;73;) (result 72)) + (type (;74;) (func (param "self" 65) (result 73))) + (export (;14;) "[method]incoming-request.consume" (func (type 74))) + (type (;75;) (own 38)) + (type (;76;) (func (param "headers" 70) (result 75))) + (export (;15;) "[constructor]outgoing-request" (func (type 76))) + (type (;77;) (borrow 38)) + (type (;78;) (own 47)) + (type (;79;) (result 78)) + (type (;80;) (func (param "self" 77) (result 79))) + (export (;16;) "[method]outgoing-request.body" (func (type 80))) + (type (;81;) (func (param "self" 77) (result 11))) + (export (;17;) "[method]outgoing-request.method" (func (type 81))) + (type (;82;) (result)) + (type (;83;) (func (param "self" 77) (param "method" 11) (result 82))) + (export (;18;) "[method]outgoing-request.set-method" (func (type 83))) + (type (;84;) (func (param "self" 77) (result 14))) + (export (;19;) "[method]outgoing-request.path-with-query" (func (type 84))) + (type (;85;) (func (param "self" 77) (param "path-with-query" 14) (result 82))) + (export (;20;) "[method]outgoing-request.set-path-with-query" (func (type 85))) + (type (;86;) (func (param "self" 77) (result 68))) + (export (;21;) "[method]outgoing-request.scheme" (func (type 86))) + (type (;87;) (func (param "self" 77) (param "scheme" 68) (result 82))) + (export (;22;) "[method]outgoing-request.set-scheme" (func (type 87))) + (export (;23;) "[method]outgoing-request.authority" (func (type 84))) + (type (;88;) (func (param "self" 77) (param "authority" 14) (result 82))) + (export (;24;) "[method]outgoing-request.set-authority" (func (type 88))) + (type (;89;) (func (param "self" 77) (result 70))) + (export (;25;) "[method]outgoing-request.headers" (func (type 89))) + (type (;90;) (own 39)) + (type (;91;) (func (result 90))) + (export (;26;) "[constructor]request-options" (func (type 91))) + (type (;92;) (borrow 39)) + (type (;93;) (option 1)) + (type (;94;) (func (param "self" 92) (result 93))) + (export (;27;) "[method]request-options.connect-timeout" (func (type 94))) + (type (;95;) (func (param "self" 92) (param "duration" 93) (result 82))) + (export (;28;) "[method]request-options.set-connect-timeout" (func (type 95))) + (export (;29;) "[method]request-options.first-byte-timeout" (func (type 94))) + (export (;30;) "[method]request-options.set-first-byte-timeout" (func (type 95))) + (export (;31;) "[method]request-options.between-bytes-timeout" (func (type 94))) + (export (;32;) "[method]request-options.set-between-bytes-timeout" (func (type 95))) + (type (;96;) (own 40)) + (type (;97;) (own 46)) + (type (;98;) (result 97 (error 27))) + (type (;99;) (func (param "param" 96) (param "response" 98))) + (export (;33;) "[static]response-outparam.set" (func (type 99))) + (type (;100;) (borrow 43)) + (type (;101;) (func (param "self" 100) (result 42))) + (export (;34;) "[method]incoming-response.status" (func (type 101))) + (type (;102;) (func (param "self" 100) (result 70))) + (export (;35;) "[method]incoming-response.headers" (func (type 102))) + (type (;103;) (func (param "self" 100) (result 73))) + (export (;36;) "[method]incoming-response.consume" (func (type 103))) + (type (;104;) (borrow 44)) + (type (;105;) (own 3)) + (type (;106;) (result 105)) + (type (;107;) (func (param "self" 104) (result 106))) + (export (;37;) "[method]incoming-body.stream" (func (type 107))) + (type (;108;) (own 45)) + (type (;109;) (func (param "this" 72) (result 108))) + (export (;38;) "[static]incoming-body.finish" (func (type 109))) + (type (;110;) (borrow 45)) + (type (;111;) (own 9)) + (type (;112;) (func (param "self" 110) (result 111))) + (export (;39;) "[method]future-trailers.subscribe" (func (type 112))) + (type (;113;) (own 36)) + (type (;114;) (option 113)) + (type (;115;) (result 114 (error 27))) + (type (;116;) (result 115)) + (type (;117;) (option 116)) + (type (;118;) (func (param "self" 110) (result 117))) + (export (;40;) "[method]future-trailers.get" (func (type 118))) + (type (;119;) (func (param "headers" 70) (result 97))) + (export (;41;) "[constructor]outgoing-response" (func (type 119))) + (type (;120;) (borrow 46)) + (type (;121;) (func (param "self" 120) (result 42))) + (export (;42;) "[method]outgoing-response.status-code" (func (type 121))) + (type (;122;) (func (param "self" 120) (param "status-code" 42) (result 82))) + (export (;43;) "[method]outgoing-response.set-status-code" (func (type 122))) + (type (;123;) (func (param "self" 120) (result 70))) + (export (;44;) "[method]outgoing-response.headers" (func (type 123))) + (type (;124;) (func (param "self" 120) (result 79))) + (export (;45;) "[method]outgoing-response.body" (func (type 124))) + (type (;125;) (borrow 47)) + (type (;126;) (own 5)) + (type (;127;) (result 126)) + (type (;128;) (func (param "self" 125) (result 127))) + (export (;46;) "[method]outgoing-body.write" (func (type 128))) + (type (;129;) (result (error 27))) + (type (;130;) (func (param "this" 78) (param "trailers" 114) (result 129))) + (export (;47;) "[static]outgoing-body.finish" (func (type 130))) + (type (;131;) (borrow 48)) + (type (;132;) (func (param "self" 131) (result 111))) + (export (;48;) "[method]future-incoming-response.subscribe" (func (type 132))) + (type (;133;) (own 43)) + (type (;134;) (result 133 (error 27))) + (type (;135;) (result 134)) + (type (;136;) (option 135)) + (type (;137;) (func (param "self" 131) (result 136))) + (export (;49;) "[method]future-incoming-response.get" (func (type 137))) + (type (;138;) (borrow 7)) + (type (;139;) (option 27)) + (type (;140;) (func (param "err" 138) (result 139))) + (export (;50;) "http-error-code" (func (type 140))) + ) + ) + (export (;4;) "wasi:http/types@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (type 9))) + ) + ) + (export (;1;) "types" (type 0)) + (type (;2;) + (component + (type (;0;) + (instance + (export (;0;) "pollable" (type (sub resource))) + ) + ) + (import "wasi:io/poll@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;0;) (type 0))) + (alias export 0 "pollable" (type (;1;))) + (type (;2;) + (instance + (alias outer 1 1 (type (;0;))) + (export (;1;) "pollable" (type (eq 0))) + (type (;2;) u64) + (export (;3;) "instant" (type (eq 2))) + (type (;4;) u64) + (export (;5;) "duration" (type (eq 4))) + ) + ) + (import "wasi:clocks/monotonic-clock@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;1;) (type 2))) + (type (;3;) + (instance + (export (;0;) "error" (type (sub resource))) + ) + ) + (import "wasi:io/error@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;2;) (type 3))) + (alias export 2 "error" (type (;4;))) + (type (;5;) + (instance + (alias outer 1 4 (type (;0;))) + (export (;1;) "error" (type (eq 0))) + (alias outer 1 1 (type (;2;))) + (export (;3;) "pollable" (type (eq 2))) + (type (;4;) (own 1)) + (type (;5;) (variant (case "last-operation-failed" 4) (case "closed"))) + (export (;6;) "stream-error" (type (eq 5))) + (export (;7;) "input-stream" (type (sub resource))) + (export (;8;) "output-stream" (type (sub resource))) + ) + ) + (import "wasi:io/streams@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;3;) (type 5))) + (alias export 1 "duration" (type (;6;))) + (alias export 3 "input-stream" (type (;7;))) + (alias export 3 "output-stream" (type (;8;))) + (type (;9;) + (instance + (alias outer 1 6 (type (;0;))) + (export (;1;) "duration" (type (eq 0))) + (alias outer 1 7 (type (;2;))) + (export (;3;) "input-stream" (type (eq 2))) + (alias outer 1 8 (type (;4;))) + (export (;5;) "output-stream" (type (eq 4))) + (alias outer 1 4 (type (;6;))) + (export (;7;) "io-error" (type (eq 6))) + (alias outer 1 1 (type (;8;))) + (export (;9;) "pollable" (type (eq 8))) + (type (;10;) (variant (case "get") (case "head") (case "post") (case "put") (case "delete") (case "connect") (case "options") (case "trace") (case "patch") (case "other" string))) + (export (;11;) "method" (type (eq 10))) + (type (;12;) (variant (case "HTTP") (case "HTTPS") (case "other" string))) + (export (;13;) "scheme" (type (eq 12))) + (type (;14;) (option string)) + (type (;15;) (option u16)) + (type (;16;) (record (field "rcode" 14) (field "info-code" 15))) + (export (;17;) "DNS-error-payload" (type (eq 16))) + (type (;18;) (option u8)) + (type (;19;) (record (field "alert-id" 18) (field "alert-message" 14))) + (export (;20;) "TLS-alert-received-payload" (type (eq 19))) + (type (;21;) (option u32)) + (type (;22;) (record (field "field-name" 14) (field "field-size" 21))) + (export (;23;) "field-size-payload" (type (eq 22))) + (type (;24;) (option u64)) + (type (;25;) (option 23)) + (type (;26;) (variant (case "DNS-timeout") (case "DNS-error" 17) (case "destination-not-found") (case "destination-unavailable") (case "destination-IP-prohibited") (case "destination-IP-unroutable") (case "connection-refused") (case "connection-terminated") (case "connection-timeout") (case "connection-read-timeout") (case "connection-write-timeout") (case "connection-limit-reached") (case "TLS-protocol-error") (case "TLS-certificate-error") (case "TLS-alert-received" 20) (case "HTTP-request-denied") (case "HTTP-request-length-required") (case "HTTP-request-body-size" 24) (case "HTTP-request-method-invalid") (case "HTTP-request-URI-invalid") (case "HTTP-request-URI-too-long") (case "HTTP-request-header-section-size" 21) (case "HTTP-request-header-size" 25) (case "HTTP-request-trailer-section-size" 21) (case "HTTP-request-trailer-size" 23) (case "HTTP-response-incomplete") (case "HTTP-response-header-section-size" 21) (case "HTTP-response-header-size" 23) (case "HTTP-response-body-size" 24) (case "HTTP-response-trailer-section-size" 21) (case "HTTP-response-trailer-size" 23) (case "HTTP-response-transfer-coding" 14) (case "HTTP-response-content-coding" 14) (case "HTTP-response-timeout") (case "HTTP-upgrade-failed") (case "HTTP-protocol-error") (case "loop-detected") (case "configuration-error") (case "internal-error" 14))) + (export (;27;) "error-code" (type (eq 26))) + (type (;28;) (variant (case "invalid-syntax") (case "forbidden") (case "immutable"))) + (export (;29;) "header-error" (type (eq 28))) + (type (;30;) string) + (export (;31;) "field-key" (type (eq 30))) + (type (;32;) (list u8)) + (export (;33;) "field-value" (type (eq 32))) + (export (;34;) "fields" (type (sub resource))) + (export (;35;) "headers" (type (eq 34))) + (export (;36;) "trailers" (type (eq 34))) + (export (;37;) "incoming-request" (type (sub resource))) + (export (;38;) "outgoing-request" (type (sub resource))) + (export (;39;) "request-options" (type (sub resource))) + (export (;40;) "response-outparam" (type (sub resource))) + (type (;41;) u16) + (export (;42;) "status-code" (type (eq 41))) + (export (;43;) "incoming-response" (type (sub resource))) + (export (;44;) "incoming-body" (type (sub resource))) + (export (;45;) "future-trailers" (type (sub resource))) + (export (;46;) "outgoing-response" (type (sub resource))) + (export (;47;) "outgoing-body" (type (sub resource))) + (export (;48;) "future-incoming-response" (type (sub resource))) + ) + ) + (import "wasi:http/types@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (;4;) (type 9))) + (alias export 4 "incoming-request" (type (;10;))) + (alias export 4 "response-outparam" (type (;11;))) + (type (;12;) + (instance + (alias outer 1 10 (type (;0;))) + (export (;1;) "incoming-request" (type (eq 0))) + (alias outer 1 11 (type (;2;))) + (export (;3;) "response-outparam" (type (eq 2))) + (type (;4;) (own 1)) + (type (;5;) (own 3)) + (type (;6;) (func (param "request" 4) (param "response-out" 5))) + (export (;0;) "handle" (func (type 6))) + ) + ) + (export (;5;) "wasi:http/incoming-handler@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (type 12))) + ) + ) + (export (;3;) "incoming-handler" (type 2)) + (type (;4;) + (component + (type (;0;) + (instance + (export (;0;) "pollable" (type (sub resource))) + ) + ) + (import "wasi:io/poll@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;0;) (type 0))) + (alias export 0 "pollable" (type (;1;))) + (type (;2;) + (instance + (alias outer 1 1 (type (;0;))) + (export (;1;) "pollable" (type (eq 0))) + (type (;2;) u64) + (export (;3;) "instant" (type (eq 2))) + (type (;4;) u64) + (export (;5;) "duration" (type (eq 4))) + ) + ) + (import "wasi:clocks/monotonic-clock@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;1;) (type 2))) + (type (;3;) + (instance + (export (;0;) "error" (type (sub resource))) + ) + ) + (import "wasi:io/error@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;2;) (type 3))) + (alias export 2 "error" (type (;4;))) + (type (;5;) + (instance + (alias outer 1 4 (type (;0;))) + (export (;1;) "error" (type (eq 0))) + (alias outer 1 1 (type (;2;))) + (export (;3;) "pollable" (type (eq 2))) + (type (;4;) (own 1)) + (type (;5;) (variant (case "last-operation-failed" 4) (case "closed"))) + (export (;6;) "stream-error" (type (eq 5))) + (export (;7;) "input-stream" (type (sub resource))) + (export (;8;) "output-stream" (type (sub resource))) + ) + ) + (import "wasi:io/streams@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;3;) (type 5))) + (alias export 1 "duration" (type (;6;))) + (alias export 3 "input-stream" (type (;7;))) + (alias export 3 "output-stream" (type (;8;))) + (type (;9;) + (instance + (alias outer 1 6 (type (;0;))) + (export (;1;) "duration" (type (eq 0))) + (alias outer 1 7 (type (;2;))) + (export (;3;) "input-stream" (type (eq 2))) + (alias outer 1 8 (type (;4;))) + (export (;5;) "output-stream" (type (eq 4))) + (alias outer 1 4 (type (;6;))) + (export (;7;) "io-error" (type (eq 6))) + (alias outer 1 1 (type (;8;))) + (export (;9;) "pollable" (type (eq 8))) + (type (;10;) (variant (case "get") (case "head") (case "post") (case "put") (case "delete") (case "connect") (case "options") (case "trace") (case "patch") (case "other" string))) + (export (;11;) "method" (type (eq 10))) + (type (;12;) (variant (case "HTTP") (case "HTTPS") (case "other" string))) + (export (;13;) "scheme" (type (eq 12))) + (type (;14;) (option string)) + (type (;15;) (option u16)) + (type (;16;) (record (field "rcode" 14) (field "info-code" 15))) + (export (;17;) "DNS-error-payload" (type (eq 16))) + (type (;18;) (option u8)) + (type (;19;) (record (field "alert-id" 18) (field "alert-message" 14))) + (export (;20;) "TLS-alert-received-payload" (type (eq 19))) + (type (;21;) (option u32)) + (type (;22;) (record (field "field-name" 14) (field "field-size" 21))) + (export (;23;) "field-size-payload" (type (eq 22))) + (type (;24;) (option u64)) + (type (;25;) (option 23)) + (type (;26;) (variant (case "DNS-timeout") (case "DNS-error" 17) (case "destination-not-found") (case "destination-unavailable") (case "destination-IP-prohibited") (case "destination-IP-unroutable") (case "connection-refused") (case "connection-terminated") (case "connection-timeout") (case "connection-read-timeout") (case "connection-write-timeout") (case "connection-limit-reached") (case "TLS-protocol-error") (case "TLS-certificate-error") (case "TLS-alert-received" 20) (case "HTTP-request-denied") (case "HTTP-request-length-required") (case "HTTP-request-body-size" 24) (case "HTTP-request-method-invalid") (case "HTTP-request-URI-invalid") (case "HTTP-request-URI-too-long") (case "HTTP-request-header-section-size" 21) (case "HTTP-request-header-size" 25) (case "HTTP-request-trailer-section-size" 21) (case "HTTP-request-trailer-size" 23) (case "HTTP-response-incomplete") (case "HTTP-response-header-section-size" 21) (case "HTTP-response-header-size" 23) (case "HTTP-response-body-size" 24) (case "HTTP-response-trailer-section-size" 21) (case "HTTP-response-trailer-size" 23) (case "HTTP-response-transfer-coding" 14) (case "HTTP-response-content-coding" 14) (case "HTTP-response-timeout") (case "HTTP-upgrade-failed") (case "HTTP-protocol-error") (case "loop-detected") (case "configuration-error") (case "internal-error" 14))) + (export (;27;) "error-code" (type (eq 26))) + (type (;28;) (variant (case "invalid-syntax") (case "forbidden") (case "immutable"))) + (export (;29;) "header-error" (type (eq 28))) + (type (;30;) string) + (export (;31;) "field-key" (type (eq 30))) + (type (;32;) (list u8)) + (export (;33;) "field-value" (type (eq 32))) + (export (;34;) "fields" (type (sub resource))) + (export (;35;) "headers" (type (eq 34))) + (export (;36;) "trailers" (type (eq 34))) + (export (;37;) "incoming-request" (type (sub resource))) + (export (;38;) "outgoing-request" (type (sub resource))) + (export (;39;) "request-options" (type (sub resource))) + (export (;40;) "response-outparam" (type (sub resource))) + (type (;41;) u16) + (export (;42;) "status-code" (type (eq 41))) + (export (;43;) "incoming-response" (type (sub resource))) + (export (;44;) "incoming-body" (type (sub resource))) + (export (;45;) "future-trailers" (type (sub resource))) + (export (;46;) "outgoing-response" (type (sub resource))) + (export (;47;) "outgoing-body" (type (sub resource))) + (export (;48;) "future-incoming-response" (type (sub resource))) + ) + ) + (import "wasi:http/types@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (;4;) (type 9))) + (alias export 4 "outgoing-request" (type (;10;))) + (alias export 4 "request-options" (type (;11;))) + (alias export 4 "future-incoming-response" (type (;12;))) + (alias export 4 "error-code" (type (;13;))) + (type (;14;) + (instance + (alias outer 1 10 (type (;0;))) + (export (;1;) "outgoing-request" (type (eq 0))) + (alias outer 1 11 (type (;2;))) + (export (;3;) "request-options" (type (eq 2))) + (alias outer 1 12 (type (;4;))) + (export (;5;) "future-incoming-response" (type (eq 4))) + (alias outer 1 13 (type (;6;))) + (export (;7;) "error-code" (type (eq 6))) + (type (;8;) (own 1)) + (type (;9;) (own 3)) + (type (;10;) (option 9)) + (type (;11;) (own 5)) + (type (;12;) (result 11 (error 7))) + (type (;13;) (func (param "request" 8) (param "options" 10) (result 12))) + (export (;0;) "handle" (func (type 13))) + ) + ) + (export (;5;) "wasi:http/outgoing-handler@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (type 14))) + ) + ) + (export (;5;) "outgoing-handler" (type 4)) + (type (;6;) + (component + (type (;0;) + (component + (type (;0;) + (instance + (type (;0;) (list u8)) + (type (;1;) (func (param "len" u64) (result 0))) + (export (;0;) "get-random-bytes" (func (type 1))) + (type (;2;) (func (result u64))) + (export (;1;) "get-random-u64" (func (type 2))) + ) + ) + (import "wasi:random/random@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;0;) (type 0))) + (type (;1;) + (instance + (export (;0;) "error" (type (sub resource))) + (type (;1;) (borrow 0)) + (type (;2;) (func (param "self" 1) (result string))) + (export (;0;) "[method]error.to-debug-string" (func (type 2))) + ) + ) + (import "wasi:io/error@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;1;) (type 1))) + (type (;2;) + (instance + (export (;0;) "pollable" (type (sub resource))) + (type (;1;) (borrow 0)) + (type (;2;) (func (param "self" 1) (result bool))) + (export (;0;) "[method]pollable.ready" (func (type 2))) + (type (;3;) (func (param "self" 1))) + (export (;1;) "[method]pollable.block" (func (type 3))) + (type (;4;) (list 1)) + (type (;5;) (list u32)) + (type (;6;) (func (param "in" 4) (result 5))) + (export (;2;) "poll" (func (type 6))) + ) + ) + (import "wasi:io/poll@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;2;) (type 2))) + (alias export 1 "error" (type (;3;))) + (alias export 2 "pollable" (type (;4;))) + (type (;5;) + (instance + (alias outer 1 3 (type (;0;))) + (export (;1;) "error" (type (eq 0))) + (alias outer 1 4 (type (;2;))) + (export (;3;) "pollable" (type (eq 2))) + (type (;4;) (own 1)) + (type (;5;) (variant (case "last-operation-failed" 4) (case "closed"))) + (export (;6;) "stream-error" (type (eq 5))) + (export (;7;) "input-stream" (type (sub resource))) + (export (;8;) "output-stream" (type (sub resource))) + (type (;9;) (borrow 7)) + (type (;10;) (list u8)) + (type (;11;) (result 10 (error 6))) + (type (;12;) (func (param "self" 9) (param "len" u64) (result 11))) + (export (;0;) "[method]input-stream.read" (func (type 12))) + (export (;1;) "[method]input-stream.blocking-read" (func (type 12))) + (type (;13;) (result u64 (error 6))) + (type (;14;) (func (param "self" 9) (param "len" u64) (result 13))) + (export (;2;) "[method]input-stream.skip" (func (type 14))) + (export (;3;) "[method]input-stream.blocking-skip" (func (type 14))) + (type (;15;) (own 3)) + (type (;16;) (func (param "self" 9) (result 15))) + (export (;4;) "[method]input-stream.subscribe" (func (type 16))) + (type (;17;) (borrow 8)) + (type (;18;) (func (param "self" 17) (result 13))) + (export (;5;) "[method]output-stream.check-write" (func (type 18))) + (type (;19;) (result (error 6))) + (type (;20;) (func (param "self" 17) (param "contents" 10) (result 19))) + (export (;6;) "[method]output-stream.write" (func (type 20))) + (export (;7;) "[method]output-stream.blocking-write-and-flush" (func (type 20))) + (type (;21;) (func (param "self" 17) (result 19))) + (export (;8;) "[method]output-stream.flush" (func (type 21))) + (export (;9;) "[method]output-stream.blocking-flush" (func (type 21))) + (type (;22;) (func (param "self" 17) (result 15))) + (export (;10;) "[method]output-stream.subscribe" (func (type 22))) + (type (;23;) (func (param "self" 17) (param "len" u64) (result 19))) + (export (;11;) "[method]output-stream.write-zeroes" (func (type 23))) + (export (;12;) "[method]output-stream.blocking-write-zeroes-and-flush" (func (type 23))) + (type (;24;) (func (param "self" 17) (param "src" 9) (param "len" u64) (result 13))) + (export (;13;) "[method]output-stream.splice" (func (type 24))) + (export (;14;) "[method]output-stream.blocking-splice" (func (type 24))) + ) + ) + (import "wasi:io/streams@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;3;) (type 5))) + (alias export 3 "output-stream" (type (;6;))) + (type (;7;) + (instance + (alias outer 1 6 (type (;0;))) + (export (;1;) "output-stream" (type (eq 0))) + (type (;2;) (own 1)) + (type (;3;) (func (result 2))) + (export (;0;) "get-stdout" (func (type 3))) + ) + ) + (import "wasi:cli/stdout@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (;4;) (type 7))) + (type (;8;) + (instance + (alias outer 1 6 (type (;0;))) + (export (;1;) "output-stream" (type (eq 0))) + (type (;2;) (own 1)) + (type (;3;) (func (result 2))) + (export (;0;) "get-stderr" (func (type 3))) + ) + ) + (import "wasi:cli/stderr@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (;5;) (type 8))) + (alias export 3 "input-stream" (type (;9;))) + (type (;10;) + (instance + (alias outer 1 9 (type (;0;))) + (export (;1;) "input-stream" (type (eq 0))) + (type (;2;) (own 1)) + (type (;3;) (func (result 2))) + (export (;0;) "get-stdin" (func (type 3))) + ) + ) + (import "wasi:cli/stdin@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (;6;) (type 10))) + (type (;11;) + (instance + (alias outer 1 4 (type (;0;))) + (export (;1;) "pollable" (type (eq 0))) + (type (;2;) u64) + (export (;3;) "instant" (type (eq 2))) + (type (;4;) u64) + (export (;5;) "duration" (type (eq 4))) + (type (;6;) (func (result 3))) + (export (;0;) "now" (func (type 6))) + (type (;7;) (func (result 5))) + (export (;1;) "resolution" (func (type 7))) + (type (;8;) (own 1)) + (type (;9;) (func (param "when" 3) (result 8))) + (export (;2;) "subscribe-instant" (func (type 9))) + (type (;10;) (func (param "when" 5) (result 8))) + (export (;3;) "subscribe-duration" (func (type 10))) + ) + ) + (import "wasi:clocks/monotonic-clock@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;7;) (type 11))) + (alias export 7 "duration" (type (;12;))) + (type (;13;) + (instance + (alias outer 1 12 (type (;0;))) + (export (;1;) "duration" (type (eq 0))) + (alias outer 1 9 (type (;2;))) + (export (;3;) "input-stream" (type (eq 2))) + (alias outer 1 6 (type (;4;))) + (export (;5;) "output-stream" (type (eq 4))) + (alias outer 1 3 (type (;6;))) + (export (;7;) "io-error" (type (eq 6))) + (alias outer 1 4 (type (;8;))) + (export (;9;) "pollable" (type (eq 8))) + (type (;10;) (variant (case "get") (case "head") (case "post") (case "put") (case "delete") (case "connect") (case "options") (case "trace") (case "patch") (case "other" string))) + (export (;11;) "method" (type (eq 10))) + (type (;12;) (variant (case "HTTP") (case "HTTPS") (case "other" string))) + (export (;13;) "scheme" (type (eq 12))) + (type (;14;) (option string)) + (type (;15;) (option u16)) + (type (;16;) (record (field "rcode" 14) (field "info-code" 15))) + (export (;17;) "DNS-error-payload" (type (eq 16))) + (type (;18;) (option u8)) + (type (;19;) (record (field "alert-id" 18) (field "alert-message" 14))) + (export (;20;) "TLS-alert-received-payload" (type (eq 19))) + (type (;21;) (option u32)) + (type (;22;) (record (field "field-name" 14) (field "field-size" 21))) + (export (;23;) "field-size-payload" (type (eq 22))) + (type (;24;) (option u64)) + (type (;25;) (option 23)) + (type (;26;) (variant (case "DNS-timeout") (case "DNS-error" 17) (case "destination-not-found") (case "destination-unavailable") (case "destination-IP-prohibited") (case "destination-IP-unroutable") (case "connection-refused") (case "connection-terminated") (case "connection-timeout") (case "connection-read-timeout") (case "connection-write-timeout") (case "connection-limit-reached") (case "TLS-protocol-error") (case "TLS-certificate-error") (case "TLS-alert-received" 20) (case "HTTP-request-denied") (case "HTTP-request-length-required") (case "HTTP-request-body-size" 24) (case "HTTP-request-method-invalid") (case "HTTP-request-URI-invalid") (case "HTTP-request-URI-too-long") (case "HTTP-request-header-section-size" 21) (case "HTTP-request-header-size" 25) (case "HTTP-request-trailer-section-size" 21) (case "HTTP-request-trailer-size" 23) (case "HTTP-response-incomplete") (case "HTTP-response-header-section-size" 21) (case "HTTP-response-header-size" 23) (case "HTTP-response-body-size" 24) (case "HTTP-response-trailer-section-size" 21) (case "HTTP-response-trailer-size" 23) (case "HTTP-response-transfer-coding" 14) (case "HTTP-response-content-coding" 14) (case "HTTP-response-timeout") (case "HTTP-upgrade-failed") (case "HTTP-protocol-error") (case "loop-detected") (case "configuration-error") (case "internal-error" 14))) + (export (;27;) "error-code" (type (eq 26))) + (type (;28;) (variant (case "invalid-syntax") (case "forbidden") (case "immutable"))) + (export (;29;) "header-error" (type (eq 28))) + (type (;30;) string) + (export (;31;) "field-key" (type (eq 30))) + (type (;32;) (list u8)) + (export (;33;) "field-value" (type (eq 32))) + (export (;34;) "fields" (type (sub resource))) + (export (;35;) "headers" (type (eq 34))) + (export (;36;) "trailers" (type (eq 34))) + (export (;37;) "incoming-request" (type (sub resource))) + (export (;38;) "outgoing-request" (type (sub resource))) + (export (;39;) "request-options" (type (sub resource))) + (export (;40;) "response-outparam" (type (sub resource))) + (type (;41;) u16) + (export (;42;) "status-code" (type (eq 41))) + (export (;43;) "incoming-response" (type (sub resource))) + (export (;44;) "incoming-body" (type (sub resource))) + (export (;45;) "future-trailers" (type (sub resource))) + (export (;46;) "outgoing-response" (type (sub resource))) + (export (;47;) "outgoing-body" (type (sub resource))) + (export (;48;) "future-incoming-response" (type (sub resource))) + (type (;49;) (own 34)) + (type (;50;) (func (result 49))) + (export (;0;) "[constructor]fields" (func (type 50))) + (type (;51;) (tuple 31 33)) + (type (;52;) (list 51)) + (type (;53;) (result 49 (error 29))) + (type (;54;) (func (param "entries" 52) (result 53))) + (export (;1;) "[static]fields.from-list" (func (type 54))) + (type (;55;) (borrow 34)) + (type (;56;) (list 33)) + (type (;57;) (func (param "self" 55) (param "name" 31) (result 56))) + (export (;2;) "[method]fields.get" (func (type 57))) + (type (;58;) (func (param "self" 55) (param "name" 31) (result bool))) + (export (;3;) "[method]fields.has" (func (type 58))) + (type (;59;) (result (error 29))) + (type (;60;) (func (param "self" 55) (param "name" 31) (param "value" 56) (result 59))) + (export (;4;) "[method]fields.set" (func (type 60))) + (type (;61;) (func (param "self" 55) (param "name" 31) (result 59))) + (export (;5;) "[method]fields.delete" (func (type 61))) + (type (;62;) (func (param "self" 55) (param "name" 31) (param "value" 33) (result 59))) + (export (;6;) "[method]fields.append" (func (type 62))) + (type (;63;) (func (param "self" 55) (result 52))) + (export (;7;) "[method]fields.entries" (func (type 63))) + (type (;64;) (func (param "self" 55) (result 49))) + (export (;8;) "[method]fields.clone" (func (type 64))) + (type (;65;) (borrow 37)) + (type (;66;) (func (param "self" 65) (result 11))) + (export (;9;) "[method]incoming-request.method" (func (type 66))) + (type (;67;) (func (param "self" 65) (result 14))) + (export (;10;) "[method]incoming-request.path-with-query" (func (type 67))) + (type (;68;) (option 13)) + (type (;69;) (func (param "self" 65) (result 68))) + (export (;11;) "[method]incoming-request.scheme" (func (type 69))) + (export (;12;) "[method]incoming-request.authority" (func (type 67))) + (type (;70;) (own 35)) + (type (;71;) (func (param "self" 65) (result 70))) + (export (;13;) "[method]incoming-request.headers" (func (type 71))) + (type (;72;) (own 44)) + (type (;73;) (result 72)) + (type (;74;) (func (param "self" 65) (result 73))) + (export (;14;) "[method]incoming-request.consume" (func (type 74))) + (type (;75;) (own 38)) + (type (;76;) (func (param "headers" 70) (result 75))) + (export (;15;) "[constructor]outgoing-request" (func (type 76))) + (type (;77;) (borrow 38)) + (type (;78;) (own 47)) + (type (;79;) (result 78)) + (type (;80;) (func (param "self" 77) (result 79))) + (export (;16;) "[method]outgoing-request.body" (func (type 80))) + (type (;81;) (func (param "self" 77) (result 11))) + (export (;17;) "[method]outgoing-request.method" (func (type 81))) + (type (;82;) (result)) + (type (;83;) (func (param "self" 77) (param "method" 11) (result 82))) + (export (;18;) "[method]outgoing-request.set-method" (func (type 83))) + (type (;84;) (func (param "self" 77) (result 14))) + (export (;19;) "[method]outgoing-request.path-with-query" (func (type 84))) + (type (;85;) (func (param "self" 77) (param "path-with-query" 14) (result 82))) + (export (;20;) "[method]outgoing-request.set-path-with-query" (func (type 85))) + (type (;86;) (func (param "self" 77) (result 68))) + (export (;21;) "[method]outgoing-request.scheme" (func (type 86))) + (type (;87;) (func (param "self" 77) (param "scheme" 68) (result 82))) + (export (;22;) "[method]outgoing-request.set-scheme" (func (type 87))) + (export (;23;) "[method]outgoing-request.authority" (func (type 84))) + (type (;88;) (func (param "self" 77) (param "authority" 14) (result 82))) + (export (;24;) "[method]outgoing-request.set-authority" (func (type 88))) + (type (;89;) (func (param "self" 77) (result 70))) + (export (;25;) "[method]outgoing-request.headers" (func (type 89))) + (type (;90;) (own 39)) + (type (;91;) (func (result 90))) + (export (;26;) "[constructor]request-options" (func (type 91))) + (type (;92;) (borrow 39)) + (type (;93;) (option 1)) + (type (;94;) (func (param "self" 92) (result 93))) + (export (;27;) "[method]request-options.connect-timeout" (func (type 94))) + (type (;95;) (func (param "self" 92) (param "duration" 93) (result 82))) + (export (;28;) "[method]request-options.set-connect-timeout" (func (type 95))) + (export (;29;) "[method]request-options.first-byte-timeout" (func (type 94))) + (export (;30;) "[method]request-options.set-first-byte-timeout" (func (type 95))) + (export (;31;) "[method]request-options.between-bytes-timeout" (func (type 94))) + (export (;32;) "[method]request-options.set-between-bytes-timeout" (func (type 95))) + (type (;96;) (own 40)) + (type (;97;) (own 46)) + (type (;98;) (result 97 (error 27))) + (type (;99;) (func (param "param" 96) (param "response" 98))) + (export (;33;) "[static]response-outparam.set" (func (type 99))) + (type (;100;) (borrow 43)) + (type (;101;) (func (param "self" 100) (result 42))) + (export (;34;) "[method]incoming-response.status" (func (type 101))) + (type (;102;) (func (param "self" 100) (result 70))) + (export (;35;) "[method]incoming-response.headers" (func (type 102))) + (type (;103;) (func (param "self" 100) (result 73))) + (export (;36;) "[method]incoming-response.consume" (func (type 103))) + (type (;104;) (borrow 44)) + (type (;105;) (own 3)) + (type (;106;) (result 105)) + (type (;107;) (func (param "self" 104) (result 106))) + (export (;37;) "[method]incoming-body.stream" (func (type 107))) + (type (;108;) (own 45)) + (type (;109;) (func (param "this" 72) (result 108))) + (export (;38;) "[static]incoming-body.finish" (func (type 109))) + (type (;110;) (borrow 45)) + (type (;111;) (own 9)) + (type (;112;) (func (param "self" 110) (result 111))) + (export (;39;) "[method]future-trailers.subscribe" (func (type 112))) + (type (;113;) (own 36)) + (type (;114;) (option 113)) + (type (;115;) (result 114 (error 27))) + (type (;116;) (result 115)) + (type (;117;) (option 116)) + (type (;118;) (func (param "self" 110) (result 117))) + (export (;40;) "[method]future-trailers.get" (func (type 118))) + (type (;119;) (func (param "headers" 70) (result 97))) + (export (;41;) "[constructor]outgoing-response" (func (type 119))) + (type (;120;) (borrow 46)) + (type (;121;) (func (param "self" 120) (result 42))) + (export (;42;) "[method]outgoing-response.status-code" (func (type 121))) + (type (;122;) (func (param "self" 120) (param "status-code" 42) (result 82))) + (export (;43;) "[method]outgoing-response.set-status-code" (func (type 122))) + (type (;123;) (func (param "self" 120) (result 70))) + (export (;44;) "[method]outgoing-response.headers" (func (type 123))) + (type (;124;) (func (param "self" 120) (result 79))) + (export (;45;) "[method]outgoing-response.body" (func (type 124))) + (type (;125;) (borrow 47)) + (type (;126;) (own 5)) + (type (;127;) (result 126)) + (type (;128;) (func (param "self" 125) (result 127))) + (export (;46;) "[method]outgoing-body.write" (func (type 128))) + (type (;129;) (result (error 27))) + (type (;130;) (func (param "this" 78) (param "trailers" 114) (result 129))) + (export (;47;) "[static]outgoing-body.finish" (func (type 130))) + (type (;131;) (borrow 48)) + (type (;132;) (func (param "self" 131) (result 111))) + (export (;48;) "[method]future-incoming-response.subscribe" (func (type 132))) + (type (;133;) (own 43)) + (type (;134;) (result 133 (error 27))) + (type (;135;) (result 134)) + (type (;136;) (option 135)) + (type (;137;) (func (param "self" 131) (result 136))) + (export (;49;) "[method]future-incoming-response.get" (func (type 137))) + (type (;138;) (borrow 7)) + (type (;139;) (option 27)) + (type (;140;) (func (param "err" 138) (result 139))) + (export (;50;) "http-error-code" (func (type 140))) + ) + ) + (import "wasi:http/types@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (;8;) (type 13))) + (alias export 8 "outgoing-request" (type (;14;))) + (alias export 8 "request-options" (type (;15;))) + (alias export 8 "future-incoming-response" (type (;16;))) + (alias export 8 "error-code" (type (;17;))) + (type (;18;) + (instance + (alias outer 1 14 (type (;0;))) + (export (;1;) "outgoing-request" (type (eq 0))) + (alias outer 1 15 (type (;2;))) + (export (;3;) "request-options" (type (eq 2))) + (alias outer 1 16 (type (;4;))) + (export (;5;) "future-incoming-response" (type (eq 4))) + (alias outer 1 17 (type (;6;))) + (export (;7;) "error-code" (type (eq 6))) + (type (;8;) (own 1)) + (type (;9;) (own 3)) + (type (;10;) (option 9)) + (type (;11;) (own 5)) + (type (;12;) (result 11 (error 7))) + (type (;13;) (func (param "request" 8) (param "options" 10) (result 12))) + (export (;0;) "handle" (func (type 13))) + ) + ) + (import "wasi:http/outgoing-handler@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (;9;) (type 18))) + (type (;19;) + (instance + (type (;0;) (record (field "seconds" u64) (field "nanoseconds" u32))) + (export (;1;) "datetime" (type (eq 0))) + (type (;2;) (func (result 1))) + (export (;0;) "now" (func (type 2))) + (export (;1;) "resolution" (func (type 2))) + ) + ) + (import "wasi:clocks/wall-clock@0.2" (versionsuffix ".0-rc-2023-11-10") (instance (;10;) (type 19))) + (alias export 8 "incoming-request" (type (;20;))) + (alias export 8 "response-outparam" (type (;21;))) + (type (;22;) + (instance + (alias outer 1 20 (type (;0;))) + (export (;1;) "incoming-request" (type (eq 0))) + (alias outer 1 21 (type (;2;))) + (export (;3;) "response-outparam" (type (eq 2))) + (type (;4;) (own 1)) + (type (;5;) (own 3)) + (type (;6;) (func (param "request" 4) (param "response-out" 5))) + (export (;0;) "handle" (func (type 6))) + ) + ) + (export (;11;) "wasi:http/incoming-handler@0.2" (versionsuffix ".0-rc-2023-12-05") (instance (type 22))) + ) + ) + (export (;0;) "wasi:http/proxy@0.2.0-rc-2023-12-05" (component (type 0))) + ) + ) + (export (;7;) "proxy" (type 6)) + (@custom "package-docs" "\01{\22worlds\22:{\22proxy\22:{\22docs\22:\22The `wasi:http/proxy` world captures a widely-implementable intersection of\5cnhosts that includes HTTP forward and reverse proxies. Components targeting\5cnthis world may concurrently stream in and out any number of incoming and\5cnoutgoing HTTP requests.\22,\22interface_import_docs\22:{\22wasi:cli/stdout@0.2.0-rc-2023-12-05\22:\22Proxies have standard output and error streams which are expected to\5cnterminate in a developer-facing console provided by the host.\22,\22wasi:cli/stdin@0.2.0-rc-2023-12-05\22:\22TODO: this is a temporary workaround until component tooling is able to\5cngracefully handle the absence of stdin. Hosts must return an eof stream\5cnfor this import, which is what wasi-libc + tooling will do automatically\5cnwhen this import is properly removed.\22,\22wasi:http/outgoing-handler@0.2.0-rc-2023-12-05\22:\22This is the default handler to use when user code simply wants to make an\5cnHTTP request (e.g., via `fetch()`).\22},\22interface_export_docs\22:{\22wasi:http/incoming-handler@0.2.0-rc-2023-12-05\22:\22The host delivers incoming HTTP requests to a component by calling the\5cn`handle` function of this exported interface. A host may arbitrarily reuse\5cnor not reuse component instance when delivering incoming HTTP requests and\5cnthus a component must be able to handle 0..N calls to `handle`.\22}}},\22interfaces\22:{\22types\22:{\22docs\22:\22This interface defines all of the types and methods for implementing\5cnHTTP Requests and Responses, both incoming and outgoing, as well as\5cntheir headers, trailers, and bodies.\22,\22funcs\22:{\22http-error-code\22:{\22docs\22:\22Attempts to extract a http-related `error` from the wasi:io `error`\5cnprovided.\5cn\5cnStream operations which return\5cn`wasi:io/stream/stream-error::last-operation-failed` have a payload of\5cntype `wasi:io/error/error` with more information about the operation\5cnthat failed. This payload can be passed through to this function to see\5cnif there's http-related information about the error to return.\5cn\5cnNote that this function is fallible because not all io-errors are\5cnhttp-related errors.\22},\22[constructor]fields\22:{\22docs\22:\22Construct an empty HTTP Fields.\5cn\5cnThe resulting `fields` is mutable.\22},\22[static]fields.from-list\22:{\22docs\22:\22Construct an HTTP Fields.\5cn\5cnThe resulting `fields` is mutable.\5cn\5cnThe list represents each key-value pair in the Fields. Keys\5cnwhich have multiple values are represented by multiple entries in this\5cnlist with the same key.\5cn\5cnThe tuple is a pair of the field key, represented as a string, and\5cnValue, represented as a list of bytes. In a valid Fields, all keys\5cnand values are valid UTF-8 strings. However, values are not always\5cnwell-formed, so they are represented as a raw list of bytes.\5cn\5cnAn error result will be returned if any header or value was\5cnsyntactically invalid, or if a header was forbidden.\22},\22[method]fields.get\22:{\22docs\22:\22Get all of the values corresponding to a key. If the key is not present\5cnin this `fields`, an empty list is returned. However, if the key is\5cnpresent but empty, this is represented by a list with one or more\5cnempty field-values present.\22},\22[method]fields.has\22:{\22docs\22:\22Returns `true` when the key is present in this `fields`. If the key is\5cnsyntactically invalid, `false` is returned.\22},\22[method]fields.set\22:{\22docs\22:\22Set all of the values for a key. Clears any existing values for that\5cnkey, if they have been set.\5cn\5cnFails with `header-error.immutable` if the `fields` are immutable.\22},\22[method]fields.delete\22:{\22docs\22:\22Delete all values for a key. Does nothing if no values for the key\5cnexist.\5cn\5cnFails with `header-error.immutable` if the `fields` are immutable.\22},\22[method]fields.append\22:{\22docs\22:\22Append a value for a key. Does not change or delete any existing\5cnvalues for that key.\5cn\5cnFails with `header-error.immutable` if the `fields` are immutable.\22},\22[method]fields.entries\22:{\22docs\22:\22Retrieve the full set of keys and values in the Fields. Like the\5cnconstructor, the list represents each key-value pair.\5cn\5cnThe outer list represents each key-value pair in the Fields. Keys\5cnwhich have multiple values are represented by multiple entries in this\5cnlist with the same key.\22},\22[method]fields.clone\22:{\22docs\22:\22Make a deep copy of the Fields. Equivalent in behavior to calling the\5cn`fields` constructor on the return value of `entries`. The resulting\5cn`fields` is mutable.\22},\22[method]incoming-request.method\22:{\22docs\22:\22Returns the method of the incoming request.\22},\22[method]incoming-request.path-with-query\22:{\22docs\22:\22Returns the path with query parameters from the request, as a string.\22},\22[method]incoming-request.scheme\22:{\22docs\22:\22Returns the protocol scheme from the request.\22},\22[method]incoming-request.authority\22:{\22docs\22:\22Returns the authority from the request, if it was present.\22},\22[method]incoming-request.headers\22:{\22docs\22:\22Get the `headers` associated with the request.\5cn\5cnThe returned `headers` resource is immutable: `set`, `append`, and\5cn`delete` operations will fail with `header-error.immutable`.\5cn\5cnThe `headers` returned are a child resource: it must be dropped before\5cnthe parent `incoming-request` is dropped. Dropping this\5cn`incoming-request` before all children are dropped will trap.\22},\22[method]incoming-request.consume\22:{\22docs\22:\22Gives the `incoming-body` associated with this request. Will only\5cnreturn success at most once, and subsequent calls will return error.\22},\22[constructor]outgoing-request\22:{\22docs\22:\22Construct a new `outgoing-request` with a default `method` of `GET`, and\5cn`none` values for `path-with-query`, `scheme`, and `authority`.\5cn\5cn* `headers` is the HTTP Headers for the Request.\5cn\5cnIt is possible to construct, or manipulate with the accessor functions\5cnbelow, an `outgoing-request` with an invalid combination of `scheme`\5cnand `authority`, or `headers` which are not permitted to be sent.\5cnIt is the obligation of the `outgoing-handler.handle` implementation\5cnto reject invalid constructions of `outgoing-request`.\22},\22[method]outgoing-request.body\22:{\22docs\22:\22Returns the resource corresponding to the outgoing Body for this\5cnRequest.\5cn\5cnReturns success on the first call: the `outgoing-body` resource for\5cnthis `outgoing-request` can be retrieved at most once. Subsequent\5cncalls will return error.\22},\22[method]outgoing-request.method\22:{\22docs\22:\22Get the Method for the Request.\22},\22[method]outgoing-request.set-method\22:{\22docs\22:\22Set the Method for the Request. Fails if the string present in a\5cn`method.other` argument is not a syntactically valid method.\22},\22[method]outgoing-request.path-with-query\22:{\22docs\22:\22Get the combination of the HTTP Path and Query for the Request.\5cnWhen `none`, this represents an empty Path and empty Query.\22},\22[method]outgoing-request.set-path-with-query\22:{\22docs\22:\22Set the combination of the HTTP Path and Query for the Request.\5cnWhen `none`, this represents an empty Path and empty Query. Fails is the\5cnstring given is not a syntactically valid path and query uri component.\22},\22[method]outgoing-request.scheme\22:{\22docs\22:\22Get the HTTP Related Scheme for the Request. When `none`, the\5cnimplementation may choose an appropriate default scheme.\22},\22[method]outgoing-request.set-scheme\22:{\22docs\22:\22Set the HTTP Related Scheme for the Request. When `none`, the\5cnimplementation may choose an appropriate default scheme. Fails if the\5cnstring given is not a syntactically valid uri scheme.\22},\22[method]outgoing-request.authority\22:{\22docs\22:\22Get the HTTP Authority for the Request. A value of `none` may be used\5cnwith Related Schemes which do not require an Authority. The HTTP and\5cnHTTPS schemes always require an authority.\22},\22[method]outgoing-request.set-authority\22:{\22docs\22:\22Set the HTTP Authority for the Request. A value of `none` may be used\5cnwith Related Schemes which do not require an Authority. The HTTP and\5cnHTTPS schemes always require an authority. Fails if the string given is\5cnnot a syntactically valid uri authority.\22},\22[method]outgoing-request.headers\22:{\22docs\22:\22Get the headers associated with the Request.\5cn\5cnThe returned `headers` resource is immutable: `set`, `append`, and\5cn`delete` operations will fail with `header-error.immutable`.\5cn\5cnThis headers resource is a child: it must be dropped before the parent\5cn`outgoing-request` is dropped, or its ownership is transferred to\5cnanother component by e.g. `outgoing-handler.handle`.\22},\22[constructor]request-options\22:{\22docs\22:\22Construct a default `request-options` value.\22},\22[method]request-options.connect-timeout\22:{\22docs\22:\22The timeout for the initial connect to the HTTP Server.\22},\22[method]request-options.set-connect-timeout\22:{\22docs\22:\22Set the timeout for the initial connect to the HTTP Server. An error\5cnreturn value indicates that this timeout is not supported.\22},\22[method]request-options.first-byte-timeout\22:{\22docs\22:\22The timeout for receiving the first byte of the Response body.\22},\22[method]request-options.set-first-byte-timeout\22:{\22docs\22:\22Set the timeout for receiving the first byte of the Response body. An\5cnerror return value indicates that this timeout is not supported.\22},\22[method]request-options.between-bytes-timeout\22:{\22docs\22:\22The timeout for receiving subsequent chunks of bytes in the Response\5cnbody stream.\22},\22[method]request-options.set-between-bytes-timeout\22:{\22docs\22:\22Set the timeout for receiving subsequent chunks of bytes in the Response\5cnbody stream. An error return value indicates that this timeout is not\5cnsupported.\22},\22[static]response-outparam.set\22:{\22docs\22:\22Set the value of the `response-outparam` to either send a response,\5cnor indicate an error.\5cn\5cnThis method consumes the `response-outparam` to ensure that it is\5cncalled at most once. If it is never called, the implementation\5cnwill respond with an error.\5cn\5cnThe user may provide an `error` to `response` to allow the\5cnimplementation determine how to respond with an HTTP error response.\22},\22[method]incoming-response.status\22:{\22docs\22:\22Returns the status code from the incoming response.\22},\22[method]incoming-response.headers\22:{\22docs\22:\22Returns the headers from the incoming response.\5cn\5cnThe returned `headers` resource is immutable: `set`, `append`, and\5cn`delete` operations will fail with `header-error.immutable`.\5cn\5cnThis headers resource is a child: it must be dropped before the parent\5cn`incoming-response` is dropped.\22},\22[method]incoming-response.consume\22:{\22docs\22:\22Returns the incoming body. May be called at most once. Returns error\5cnif called additional times.\22},\22[method]incoming-body.stream\22:{\22docs\22:\22Returns the contents of the body, as a stream of bytes.\5cn\5cnReturns success on first call: the stream representing the contents\5cncan be retrieved at most once. Subsequent calls will return error.\5cn\5cnThe returned `input-stream` resource is a child: it must be dropped\5cnbefore the parent `incoming-body` is dropped, or consumed by\5cn`incoming-body.finish`.\5cn\5cnThis invariant ensures that the implementation can determine whether\5cnthe user is consuming the contents of the body, waiting on the\5cn`future-trailers` to be ready, or neither. This allows for network\5cnbackpressure is to be applied when the user is consuming the body,\5cnand for that backpressure to not inhibit delivery of the trailers if\5cnthe user does not read the entire body.\22},\22[static]incoming-body.finish\22:{\22docs\22:\22Takes ownership of `incoming-body`, and returns a `future-trailers`.\5cnThis function will trap if the `input-stream` child is still alive.\22},\22[method]future-trailers.subscribe\22:{\22docs\22:\22Returns a pollable which becomes ready when either the trailers have\5cnbeen received, or an error has occurred. When this pollable is ready,\5cnthe `get` method will return `some`.\22},\22[method]future-trailers.get\22:{\22docs\22:\22Returns the contents of the trailers, or an error which occurred,\5cnonce the future is ready.\5cn\5cnThe outer `option` represents future readiness. Users can wait on this\5cn`option` to become `some` using the `subscribe` method.\5cn\5cnThe outer `result` is used to retrieve the trailers or error at most\5cnonce. It will be success on the first call in which the outer option\5cnis `some`, and error on subsequent calls.\5cn\5cnThe inner `result` represents that either the HTTP Request or Response\5cnbody, as well as any trailers, were received successfully, or that an\5cnerror occurred receiving them. The optional `trailers` indicates whether\5cnor not trailers were present in the body.\5cn\5cnWhen some `trailers` are returned by this method, the `trailers`\5cnresource is immutable, and a child. Use of the `set`, `append`, or\5cn`delete` methods will return an error, and the resource must be\5cndropped before the parent `future-trailers` is dropped.\22},\22[constructor]outgoing-response\22:{\22docs\22:\22Construct an `outgoing-response`, with a default `status-code` of `200`.\5cnIf a different `status-code` is needed, it must be set via the\5cn`set-status-code` method.\5cn\5cn* `headers` is the HTTP Headers for the Response.\22},\22[method]outgoing-response.status-code\22:{\22docs\22:\22Get the HTTP Status Code for the Response.\22},\22[method]outgoing-response.set-status-code\22:{\22docs\22:\22Set the HTTP Status Code for the Response. Fails if the status-code\5cngiven is not a valid http status code.\22},\22[method]outgoing-response.headers\22:{\22docs\22:\22Get the headers associated with the Request.\5cn\5cnThe returned `headers` resource is immutable: `set`, `append`, and\5cn`delete` operations will fail with `header-error.immutable`.\5cn\5cnThis headers resource is a child: it must be dropped before the parent\5cn`outgoing-request` is dropped, or its ownership is transferred to\5cnanother component by e.g. `outgoing-handler.handle`.\22},\22[method]outgoing-response.body\22:{\22docs\22:\22Returns the resource corresponding to the outgoing Body for this Response.\5cn\5cnReturns success on the first call: the `outgoing-body` resource for\5cnthis `outgoing-response` can be retrieved at most once. Subsequent\5cncalls will return error.\22},\22[method]outgoing-body.write\22:{\22docs\22:\22Returns a stream for writing the body contents.\5cn\5cnThe returned `output-stream` is a child resource: it must be dropped\5cnbefore the parent `outgoing-body` resource is dropped (or finished),\5cnotherwise the `outgoing-body` drop or `finish` will trap.\5cn\5cnReturns success on the first call: the `output-stream` resource for\5cnthis `outgoing-body` may be retrieved at most once. Subsequent calls\5cnwill return error.\22},\22[static]outgoing-body.finish\22:{\22docs\22:\22Finalize an outgoing body, optionally providing trailers. This must be\5cncalled to signal that the response is complete. If the `outgoing-body`\5cnis dropped without calling `outgoing-body.finalize`, the implementation\5cnshould treat the body as corrupted.\5cn\5cnFails if the body's `outgoing-request` or `outgoing-response` was\5cnconstructed with a Content-Length header, and the contents written\5cnto the body (via `write`) does not match the value given in the\5cnContent-Length.\22},\22[method]future-incoming-response.subscribe\22:{\22docs\22:\22Returns a pollable which becomes ready when either the Response has\5cnbeen received, or an error has occurred. When this pollable is ready,\5cnthe `get` method will return `some`.\22},\22[method]future-incoming-response.get\22:{\22docs\22:\22Returns the incoming HTTP Response, or an error, once one is ready.\5cn\5cnThe outer `option` represents future readiness. Users can wait on this\5cn`option` to become `some` using the `subscribe` method.\5cn\5cnThe outer `result` is used to retrieve the response or error at most\5cnonce. It will be success on the first call in which the outer option\5cnis `some`, and error on subsequent calls.\5cn\5cnThe inner `result` represents that either the incoming HTTP Response\5cnstatus and headers have received successfully, or that an error\5cnoccurred. Errors may also occur while consuming the response body,\5cnbut those will be reported by the `incoming-body` and its\5cn`output-stream` child.\22}},\22types\22:{\22method\22:{\22docs\22:\22This type corresponds to HTTP standard Methods.\22},\22scheme\22:{\22docs\22:\22This type corresponds to HTTP standard Related Schemes.\22},\22DNS-error-payload\22:{\22docs\22:\22Defines the case payload type for `DNS-error` above:\22},\22TLS-alert-received-payload\22:{\22docs\22:\22Defines the case payload type for `TLS-alert-received` above:\22},\22field-size-payload\22:{\22docs\22:\22Defines the case payload type for `HTTP-response-{header,trailer}-size` above:\22},\22error-code\22:{\22docs\22:\22These cases are inspired by the IANA HTTP Proxy Error Types:\5cn https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types\22,\22items\22:{\22internal-error\22:\22This is a catch-all error for anything that doesn't fit cleanly into a\5cnmore specific case. It also includes an optional string for an\5cnunstructured description of the error. Users should not depend on the\5cnstring for diagnosing errors, as it's not required to be consistent\5cnbetween implementations.\22}},\22header-error\22:{\22docs\22:\22This type enumerates the different kinds of errors that may occur when\5cnsetting or appending to a `fields` resource.\22,\22items\22:{\22invalid-syntax\22:\22This error indicates that a `field-key` or `field-value` was\5cnsyntactically invalid when used with an operation that sets headers in a\5cn`fields`.\22,\22forbidden\22:\22This error indicates that a forbidden `field-key` was used when trying\5cnto set a header in a `fields`.\22,\22immutable\22:\22This error indicates that the operation on the `fields` was not\5cnpermitted because the fields are immutable.\22}},\22field-key\22:{\22docs\22:\22Field keys are always strings.\22},\22field-value\22:{\22docs\22:\22Field values should always be ASCII strings. However, in\5cnreality, HTTP implementations often have to interpret malformed values,\5cnso they are provided as a list of bytes.\22},\22fields\22:{\22docs\22:\22This following block defines the `fields` resource which corresponds to\5cnHTTP standard Fields. Fields are a common representation used for both\5cnHeaders and Trailers.\5cn\5cnA `fields` may be mutable or immutable. A `fields` created using the\5cnconstructor, `from-list`, or `clone` will be mutable, but a `fields`\5cnresource given by other means (including, but not limited to,\5cn`incoming-request.headers`, `outgoing-request.headers`) might be be\5cnimmutable. In an immutable fields, the `set`, `append`, and `delete`\5cnoperations will fail with `header-error.immutable`.\22},\22headers\22:{\22docs\22:\22Headers is an alias for Fields.\22},\22trailers\22:{\22docs\22:\22Trailers is an alias for Fields.\22},\22incoming-request\22:{\22docs\22:\22Represents an incoming HTTP Request.\22},\22outgoing-request\22:{\22docs\22:\22Represents an outgoing HTTP Request.\22},\22request-options\22:{\22docs\22:\22Parameters for making an HTTP Request. Each of these parameters is\5cncurrently an optional timeout applicable to the transport layer of the\5cnHTTP protocol.\5cn\5cnThese timeouts are separate from any the user may use to bound a\5cnblocking call to `wasi:io/poll.poll`.\22},\22response-outparam\22:{\22docs\22:\22Represents the ability to send an HTTP Response.\5cn\5cnThis resource is used by the `wasi:http/incoming-handler` interface to\5cnallow a Response to be sent corresponding to the Request provided as the\5cnother argument to `incoming-handler.handle`.\22},\22status-code\22:{\22docs\22:\22This type corresponds to the HTTP standard Status Code.\22},\22incoming-response\22:{\22docs\22:\22Represents an incoming HTTP Response.\22},\22incoming-body\22:{\22docs\22:\22Represents an incoming HTTP Request or Response's Body.\5cn\5cnA body has both its contents - a stream of bytes - and a (possibly\5cnempty) set of trailers, indicating that the full contents of the\5cnbody have been received. This resource represents the contents as\5cnan `input-stream` and the delivery of trailers as a `future-trailers`,\5cnand ensures that the user of this interface may only be consuming either\5cnthe body contents or waiting on trailers at any given time.\22},\22future-trailers\22:{\22docs\22:\22Represents a future which may eventually return trailers, or an error.\5cn\5cnIn the case that the incoming HTTP Request or Response did not have any\5cntrailers, this future will resolve to the empty set of trailers once the\5cncomplete Request or Response body has been received.\22},\22outgoing-response\22:{\22docs\22:\22Represents an outgoing HTTP Response.\22},\22outgoing-body\22:{\22docs\22:\22Represents an outgoing HTTP Request or Response's Body.\5cn\5cnA body has both its contents - a stream of bytes - and a (possibly\5cnempty) set of trailers, inducating the full contents of the body\5cnhave been sent. This resource represents the contents as an\5cn`output-stream` child resource, and the completion of the body (with\5cnoptional trailers) with a static function that consumes the\5cn`outgoing-body` resource, and ensures that the user of this interface\5cnmay not write to the body contents after the body has been finished.\5cn\5cnIf the user code drops this resource, as opposed to calling the static\5cnmethod `finish`, the implementation should treat the body as incomplete,\5cnand that an error has occurred. The implementation should propagate this\5cnerror to the HTTP protocol by whatever means it has available,\5cnincluding: corrupting the body on the wire, aborting the associated\5cnRequest, or sending a late status code for the Response.\22},\22future-incoming-response\22:{\22docs\22:\22Represents a future which may eventually return an incoming HTTP\5cnResponse, or an error.\5cn\5cnThis resource is returned by the `wasi:http/outgoing-handler` interface to\5cnprovide the HTTP Response corresponding to the sent Request.\22}}},\22incoming-handler\22:{\22docs\22:\22This interface defines a handler of incoming HTTP Requests. It should\5cnbe exported by components which can respond to HTTP Requests.\22,\22funcs\22:{\22handle\22:{\22docs\22:\22This function is invoked with an incoming HTTP Request, and a resource\5cn`response-outparam` which provides the capability to reply with an HTTP\5cnResponse. The response is sent by calling the `response-outparam.set`\5cnmethod, which allows execution to continue after the response has been\5cnsent. This enables both streaming to the response body, and performing other\5cnwork.\5cn\5cnThe implementor of this function must write a response to the\5cn`response-outparam` before returning, or else the caller will respond\5cnwith an error on its behalf.\22}}},\22outgoing-handler\22:{\22docs\22:\22This interface defines a handler of outgoing HTTP Requests. It should be\5cnimported by components which wish to make HTTP Requests.\22,\22funcs\22:{\22handle\22:{\22docs\22:\22This function is invoked with an outgoing HTTP Request, and it returns\5cna resource `future-incoming-response` which represents an HTTP Response\5cnwhich may arrive in the future.\5cn\5cnThe `options` argument accepts optional parameters for the HTTP\5cnprotocol's transport layer.\5cn\5cnThis function may return an error if the `outgoing-request` is invalid\5cnor not allowed to be made. Otherwise, protocol errors are reported\5cnthrough the `future-incoming-response`.\22}}}}}") + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) +) diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit new file mode 100644 index 0000000000..cc82ae5dc5 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit @@ -0,0 +1,7 @@ +package wasi:cli@0.2.0-rc-2023-12-05; + +world command { + include imports; + + export run; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit new file mode 100644 index 0000000000..70065233e8 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit @@ -0,0 +1,18 @@ +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + initial-cwd: func() -> option; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit new file mode 100644 index 0000000000..d0c2b82ae2 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit @@ -0,0 +1,4 @@ +interface exit { + /// Exit the current instance and any linked instances. + exit: func(status: result); +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit new file mode 100644 index 0000000000..9965ea35ec --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit @@ -0,0 +1,20 @@ +package wasi:cli@0.2.0-rc-2023-12-05; + +world imports { + include wasi:clocks/imports@0.2.0-rc-2023-11-10; + include wasi:filesystem/imports@0.2.0-rc-2023-11-10; + include wasi:sockets/imports@0.2.0-rc-2023-11-10; + include wasi:random/imports@0.2.0-rc-2023-11-10; + include wasi:io/imports@0.2.0-rc-2023-11-10; + + import environment; + import exit; + import stdin; + import stdout; + import stderr; + import terminal-input; + import terminal-output; + import terminal-stdin; + import terminal-stdout; + import terminal-stderr; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit new file mode 100644 index 0000000000..a70ee8c038 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit @@ -0,0 +1,4 @@ +interface run { + /// Run the program. + run: func() -> result; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit new file mode 100644 index 0000000000..1b653b6e2d --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit @@ -0,0 +1,17 @@ +interface stdin { + use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream}; + + get-stdin: func() -> input-stream; +} + +interface stdout { + use wasi:io/streams@0.2.0-rc-2023-11-10.{output-stream}; + + get-stdout: func() -> output-stream; +} + +interface stderr { + use wasi:io/streams@0.2.0-rc-2023-11-10.{output-stream}; + + get-stderr: func() -> output-stream; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit new file mode 100644 index 0000000000..47495769b3 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit @@ -0,0 +1,47 @@ +interface terminal-input { + /// The input side of a terminal. + resource terminal-input; + + // In the future, this may include functions for disabling echoing, + // disabling input buffering so that keyboard events are sent through + // immediately, querying supported features, and so on. +} + +interface terminal-output { + /// The output side of a terminal. + resource terminal-output; + + // In the future, this may include functions for querying the terminal + // size, being notified of terminal size changes, querying supported + // features, and so on. +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +interface terminal-stdin { + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +interface terminal-stdout { + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +interface terminal-stderr { + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stderr: func() -> option; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit new file mode 100644 index 0000000000..fdd54f566c --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit @@ -0,0 +1,45 @@ +package wasi:clocks@0.2.0-rc-2023-11-10; +/// WASI Monotonic Clock is a clock API intended to let users measure elapsed +/// time. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A monotonic clock is a clock which has an unspecified initial value, and +/// successive reads of the clock will produce non-decreasing values. +/// +/// It is intended for measuring elapsed time. +interface monotonic-clock { + use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; + + /// A duration of time, in nanoseconds. + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// occurred. + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occurred. + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit new file mode 100644 index 0000000000..8abb9a0c0e --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit @@ -0,0 +1,42 @@ +package wasi:clocks@0.2.0-rc-2023-11-10; +/// WASI Wall Clock is a clock API intended to let users query the current +/// time. The name "wall" makes an analogy to a "clock on the wall", which +/// is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A wall clock is a clock which measures the date and time according to +/// some external reference. +/// +/// External references may be reset, so this clock is not necessarily +/// monotonic, making it unsuitable for measuring elapsed time. +/// +/// It is intended for reporting the current date and time for humans. +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit new file mode 100644 index 0000000000..8fa080f0e2 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit @@ -0,0 +1,6 @@ +package wasi:clocks@0.2.0-rc-2023-11-10; + +world imports { + import monotonic-clock; + import wall-clock; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit new file mode 100644 index 0000000000..95ec678434 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit @@ -0,0 +1,8 @@ +package wasi:filesystem@0.2.0-rc-2023-11-10; + +interface preopens { + use types.{descriptor}; + + /// Return the set of preopened directories, and their path. + get-directories: func() -> list>; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit new file mode 100644 index 0000000000..16067ad68c --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit @@ -0,0 +1,634 @@ +package wasi:filesystem@0.2.0-rc-2023-11-10; +/// WASI filesystem is a filesystem API primarily intended to let users run WASI +/// programs that access their files on their existing filesystems, without +/// significant overhead. +/// +/// It is intended to be roughly portable between Unix-family platforms and +/// Windows, though it does not hide many of the major differences. +/// +/// Paths are passed as interface-type `string`s, meaning they must consist of +/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +/// paths which are not accessible by this API. +/// +/// The directory separator in WASI is always the forward-slash (`/`). +/// +/// All paths in WASI are relative paths, and are interpreted relative to a +/// `descriptor` referring to a base directory. If a `path` argument to any WASI +/// function starts with `/`, or if any step of resolving a `path`, including +/// `..` and symbolic link steps, reaches a directory outside of the base +/// directory, or reaches a symlink to an absolute or rooted path in the +/// underlying filesystem, the function fails with `error-code::not-permitted`. +/// +/// For more information about WASI path resolution and sandboxing, see +/// [WASI filesystem path resolution]. +/// +/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +interface types { + use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream, output-stream, error}; + use wasi:clocks/wall-clock@0.2.0-rc-2023-11-10.{datetime}; + + /// File size or length of a region within a file. + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrity + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// Flags determining the method of how paths are resolved. + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device, + } + + /// File or memory access pattern advisory information. + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse, + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + resource descriptor { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + sync-data: func() -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-type: func() -> result; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + read-directory: func() -> result; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func( + /// The relative path of the symbolic link from which to read. + path: string, + ) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + is-same-object: func(other: borrow) -> bool; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encourated to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit new file mode 100644 index 0000000000..285e0bae9e --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit @@ -0,0 +1,6 @@ +package wasi:filesystem@0.2.0-rc-2023-11-10; + +world imports { + import types; + import preopens; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit new file mode 100644 index 0000000000..31918acbb4 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.0-rc-2023-11-10; + + +interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit new file mode 100644 index 0000000000..81b1cab999 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit @@ -0,0 +1,41 @@ +package wasi:io@0.2.0-rc-2023-11-10; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit new file mode 100644 index 0000000000..1a7efa186c --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit @@ -0,0 +1,251 @@ +package wasi:io@0.2.0-rc-2023-11-10; + +/// WASI I/O is an I/O abstraction API which is currently focused on providing +/// stream types. +/// +/// In the future, the component model is expected to add built-in stream types; +/// when it does, they are expected to subsume this API. +interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + /// Perform a non-blocking read from the stream. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + } + + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + check-write: func() -> result; + + /// Perform a write. This function never blocks. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func( + contents: list + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit new file mode 100644 index 0000000000..8243da2ee9 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit @@ -0,0 +1,6 @@ +package wasi:io@0.2.0-rc-2023-11-10; + +world imports { + import streams; + import poll; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit new file mode 100644 index 0000000000..f76e87dadc --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.0-rc-2023-11-10; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit new file mode 100644 index 0000000000..ec7b997376 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit @@ -0,0 +1,22 @@ +package wasi:random@0.2.0-rc-2023-11-10; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit new file mode 100644 index 0000000000..7a7dfa27a9 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit @@ -0,0 +1,26 @@ +package wasi:random@0.2.0-rc-2023-11-10; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit new file mode 100644 index 0000000000..49e5743b4b --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit @@ -0,0 +1,7 @@ +package wasi:random@0.2.0-rc-2023-11-10; + +world imports { + import random; + import insecure; + import insecure-seed; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit new file mode 100644 index 0000000000..e455d0ff7b --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit @@ -0,0 +1,9 @@ + +/// This interface provides a value-export of the default network handle.. +interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit new file mode 100644 index 0000000000..931ccf7e05 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,51 @@ + +interface ip-name-lookup { + use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; + use network.{network, error-code, ip-address}; + + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + + resource resolve-address-stream { + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit new file mode 100644 index 0000000000..6bb07cd6fa --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit @@ -0,0 +1,147 @@ + +interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + enum error-code { + // ### GENERAL ERRORS ### + + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + + /// The operation timed out before it could finish completely. + timeout, + + /// This operation is incompatible with another asynchronous operation that is already in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + + + + // ### TCP & UDP SOCKET ERRORS ### + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + + /// A bind operation failed because the provided address is not an address that the `network` can bind to. + address-not-bindable, + + /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. + address-in-use, + + /// The remote address is not reachable + remote-unreachable, + + + // ### TCP SOCKET ERRORS ### + + /// The connection was forcefully rejected + connection-refused, + + /// The connection was reset. + connection-reset, + + /// A connection was aborted. + connection-aborted, + + + // ### UDP SOCKET ERRORS ### + datagram-too-large, + + + // ### NAME LOOKUP ERRORS ### + + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + permanent-resolver-failure, + } + + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + type ipv4-address = tuple; + type ipv6-address = tuple; + + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + record ipv4-socket-address { + port: u16, // sin_port + address: ipv4-address, // sin_addr + } + + record ipv6-socket-address { + port: u16, // sin6_port + flow-info: u32, // sin6_flowinfo + address: ipv6-address, // sin6_addr + scope-id: u32, // sin6_scope_id + } + + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit new file mode 100644 index 0000000000..768a07c850 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,26 @@ + +interface tcp-create-socket { + use network.{network, error-code, ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`listen`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit new file mode 100644 index 0000000000..b01b65e6c4 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit @@ -0,0 +1,321 @@ + +interface tcp { + use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream, output-stream}; + use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0-rc-2023-11-10.{duration}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + + /// Similar to `SHUT_WR` in POSIX. + send, + + /// Similar to `SHUT_RDWR` in POSIX. + both, + } + + + /// A TCP socket handle. + resource tcp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// When a socket is not explicitly bound, the first invocation to a listen or connect operation will + /// implicitly bind the socket. + /// + /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts. + /// + /// # Typical `start` errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address, but the socket has `ipv6-only` enabled. (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// + /// # Typical `finish` errors + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the Connection state + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// POSIX mentions: + /// > If connect() fails, the state of the socket is unspecified. Conforming applications should + /// > close the file descriptor and create a new socket before attempting to reconnect. + /// + /// WASI prescribes the following behavior: + /// - If `connect` fails because an input/state validation error, the socket should remain usable. + /// - If a connection was actually attempted but failed, the socket should become unusable for further network communication. + /// Besides `drop`, any method after such a failure may return an error. + /// + /// # Typical `start` errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address, but the socket has `ipv6-only` enabled. (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the Connection state. (EISCONN) + /// - `invalid-state`: The socket is already in the Listener state. (EOPNOTSUPP, EINVAL on Windows) + /// + /// # Typical `finish` errors + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A `connect` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the Listener state. + /// + /// Unlike POSIX: + /// - this function is async. This enables interactive WASI hosts to inject permission prompts. + /// - the socket must already be explicitly bound. + /// + /// # Typical `start` errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the Connection state. (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the Listener state. + /// + /// # Typical `finish` errors + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A `listen` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; + finish-listen: func() -> result<_, error-code>; + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the Connection state. The following properties are inherited from the listener socket: + /// - `address-family` + /// - `ipv6-only` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the Listener state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + + /// Whether the socket is listening for new connections. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + + /// Whether IPv4 compatibility (dual-stack) mode is disabled or not. + /// + /// Equivalent to the IPV6_V6ONLY socket option. + /// + /// # Typical errors + /// - `invalid-state`: (set) The socket is already bound. + /// - `not-supported`: (get/set) `this` socket is an IPv4 socket. + /// - `not-supported`: (set) Host does not support dual-stack sockets. (Implementations are not required to.) + ipv6-only: func() -> result; + set-ipv6-only: func(value: bool) -> result<_, error-code>; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is already in the Connection state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + /// - `invalid-state`: (set) The socket is already in the Connection state. + /// - `invalid-state`: (set) The socket is already in the Listener state. + hop-limit: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is already in the Connection state. + /// - `invalid-state`: (set) The socket is already in the Listener state. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + + /// Initiate a graceful shutdown. + /// + /// - receive: the socket is not expecting to receive any more data from the peer. All subsequent read + /// operations on the `input-stream` associated with this socket will return an End Of Stream indication. + /// Any data still in the receive queue at time of calling `shutdown` will be discarded. + /// - send: the socket is not expecting to send any more data to the peer. All subsequent write + /// operations on the `output-stream` associated with this socket will return an error. + /// - both: same effect as receive & send combined. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the Connection state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit new file mode 100644 index 0000000000..cc58234d84 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit @@ -0,0 +1,26 @@ + +interface udp-create-socket { + use network.{network, error-code, ip-address-family}; + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit new file mode 100644 index 0000000000..c8dafadfcb --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit @@ -0,0 +1,277 @@ + +interface udp { + use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. + remote-address: option, + } + + + + /// A UDP socket handle. + resource udp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts. + /// + /// # Typical `start` errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// + /// # Typical `finish` errors + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, but + /// only the most recently returned pair of streams will be operational. Implementations may trap if + /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + %stream: func(remote-address: option) -> result, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + + /// Whether IPv4 compatibility (dual-stack) mode is disabled or not. + /// + /// Equivalent to the IPV6_V6ONLY socket option. + /// + /// # Typical errors + /// - `not-supported`: (get/set) `this` socket is an IPv4 socket. + /// - `invalid-state`: (set) The socket is already bound. + /// - `not-supported`: (set) Host does not support dual-stack sockets. (Implementations are not required to.) + ipv6-only: func() -> result; + set-ipv6-only: func(value: bool) -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource incoming-datagram-stream { + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource outgoing-datagram-stream { + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without blocking and + /// returns how many messages were actually sent (or queued for sending). This function never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list and sequentially + /// sending each individual datagram until either the end of the list has been reached or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit new file mode 100644 index 0000000000..49ad8d3d9f --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit @@ -0,0 +1,11 @@ +package wasi:sockets@0.2.0-rc-2023-11-10; + +world imports { + import instance-network; + import network; + import udp; + import udp-create-socket; + import tcp; + import tcp-create-socket; + import ip-name-lookup; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit new file mode 100644 index 0000000000..a34a0649d5 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit @@ -0,0 +1,43 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +interface incoming-handler { + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func( + request: incoming-request, + response-out: response-outparam + ); +} + +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +interface outgoing-handler { + use types.{ + outgoing-request, request-options, future-incoming-response, error-code + }; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/http.wit.print b/crates/wit-component/tests/interfaces/canon-names-wasi-http/http.wit.print new file mode 100644 index 0000000000..bdfbde3140 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/http.wit.print @@ -0,0 +1,583 @@ +package wasi:http@0.2.0-rc-2023-12-05; + +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +interface types { + use wasi:clocks/monotonic-clock@0.2.0-rc-2023-11-10.{duration}; + use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream, output-stream}; + use wasi:io/error@0.2.0-rc-2023-11-10.{error as io-error}; + use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string), + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { + HTTP, + HTTPS, + other(string), + } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option, + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option, + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option, + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option), + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all keys + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + from-list: static func(entries: list>) -> result; + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields`, an empty list is returned. However, if the key is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + get: func(name: field-key) -> list; + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + set: func(name: field-key, value: list) -> result<_, header-error>; + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + delete: func(name: field-key) -> result<_, header-error>; + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + /// Returns the method of the incoming request. + method: func() -> method; + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + /// Returns the protocol scheme from the request. + scheme: func() -> option; + /// Returns the authority from the request, if it was present. + authority: func() -> option; + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor(headers: headers); + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + /// Get the Method for the Request. + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func(param: response-outparam, response: result); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + /// Returns the status code from the incoming response. + status: func() -> status-code; + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func(this: outgoing-body, trailers: option) -> result<_, error-code>; + } + + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; +} + +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +interface incoming-handler { + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func(request: incoming-request, response-out: response-outparam); +} + +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +interface outgoing-handler { + use types.{outgoing-request, request-options, future-incoming-response, error-code}; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func(request: outgoing-request, options: option) -> result; +} + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +world proxy { + import wasi:random/random@0.2.0-rc-2023-11-10; + import wasi:io/error@0.2.0-rc-2023-11-10; + import wasi:io/poll@0.2.0-rc-2023-11-10; + import wasi:io/streams@0.2.0-rc-2023-11-10; + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + import wasi:cli/stdout@0.2.0-rc-2023-12-05; + import wasi:cli/stderr@0.2.0-rc-2023-12-05; + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + import wasi:cli/stdin@0.2.0-rc-2023-12-05; + import wasi:clocks/monotonic-clock@0.2.0-rc-2023-11-10; + import types; + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + import outgoing-handler; + import wasi:clocks/wall-clock@0.2.0-rc-2023-11-10; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + export incoming-handler; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit new file mode 100644 index 0000000000..0f466c93c1 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit @@ -0,0 +1,32 @@ +package wasi:http@0.2.0-rc-2023-12-05; + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +world proxy { + /// HTTP proxies have access to time and randomness. + include wasi:clocks/imports@0.2.0-rc-2023-11-10; + import wasi:random/random@0.2.0-rc-2023-11-10; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + import wasi:cli/stdout@0.2.0-rc-2023-12-05; + import wasi:cli/stderr@0.2.0-rc-2023-12-05; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + import wasi:cli/stdin@0.2.0-rc-2023-12-05; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + import outgoing-handler; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + export incoming-handler; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit new file mode 100644 index 0000000000..06c3761665 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit @@ -0,0 +1,570 @@ +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +interface types { + use wasi:clocks/monotonic-clock@0.2.0-rc-2023-11-10.{duration}; + use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream, output-stream}; + use wasi:io/error@0.2.0-rc-2023-11-10.{error as io-error}; + use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option) + } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all keys + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields`, an empty list is returned. However, if the key is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + get: func(name: field-key) -> list; + + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + set: func(name: field-key, value: list) -> result<_, header-error>; + + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + delete: func(name: field-key) -> result<_, header-error>; + + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + + /// Returns the method of the incoming request. + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + scheme: func() -> option; + + /// Returns the authority from the request, if it was present. + authority: func() -> option; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor( + headers: headers + ); + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the Method for the Request. + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + + /// Returns the status code from the incoming response. + status: func() -> status-code; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + + } +} diff --git a/crates/wit-parser/src/lib.rs b/crates/wit-parser/src/lib.rs index 61cb75ab01..86d641855d 100644 --- a/crates/wit-parser/src/lib.rs +++ b/crates/wit-parser/src/lib.rs @@ -244,23 +244,16 @@ pub struct PackageName { pub version: Option, } +#[cfg(feature = "canon-names")] impl PackageName { /// Returns the canonical version prefix for comparison purposes. /// /// When `canon-names` is enabled, this returns only the canonical prefix - /// from [`PackageName::canon_version_split`]. Otherwise returns the full - /// version string. + /// from [`PackageName::canon_version_split`]. fn version_key(&self) -> Option { let version = self.version.as_ref()?; - #[cfg(feature = "canon-names")] - { - let (prefix, _) = Self::canon_version_split(version); - Some(prefix) - } - #[cfg(not(feature = "canon-names"))] - { - Some(version.to_string()) - } + let (prefix, _) = Self::canon_version_split(version); + Some(prefix) } } @@ -268,7 +261,10 @@ impl core::hash::Hash for PackageName { fn hash(&self, state: &mut H) { self.namespace.hash(state); self.name.hash(state); + #[cfg(feature = "canon-names")] self.version_key().hash(state); + #[cfg(not(feature = "canon-names"))] + self.version.hash(state); } } @@ -276,7 +272,16 @@ impl PartialEq for PackageName { fn eq(&self, other: &Self) -> bool { self.namespace == other.namespace && self.name == other.name - && self.version_key() == other.version_key() + && { + #[cfg(feature = "canon-names")] + { + self.version_key() == other.version_key() + } + #[cfg(not(feature = "canon-names"))] + { + self.version == other.version + } + } } } @@ -293,7 +298,16 @@ impl Ord for PackageName { self.namespace .cmp(&other.namespace) .then_with(|| self.name.cmp(&other.name)) - .then_with(|| self.version_key().cmp(&other.version_key())) + .then_with(|| { + #[cfg(feature = "canon-names")] + { + self.version_key().cmp(&other.version_key()) + } + #[cfg(not(feature = "canon-names"))] + { + self.version.cmp(&other.version) + } + }) } } diff --git a/crates/wit-parser/src/resolve/mod.rs b/crates/wit-parser/src/resolve/mod.rs index 3f4714a1be..71b1ae549b 100644 --- a/crates/wit-parser/src/resolve/mod.rs +++ b/crates/wit-parser/src/resolve/mod.rs @@ -284,16 +284,51 @@ impl Resolve { if let Some((prev_pkg, prev_source_map_index)) = pkg_details_map.insert(name.clone(), (pkg, source_map_index)) { - let prev_offset = source_map_offsets[prev_source_map_index]; - let mut span1 = my_span; - span1.adjust(offset); - let mut span2 = prev_pkg.package_name_span; - span2.adjust(prev_offset); - return Err(ResolveError::from(ResolveErrorKind::DuplicatePackage { - name, - span1, - span2, - })); + #[cfg(feature = "canon-names")] + { + // When canon-names is enabled, packages with the same + // canonical version prefix are considered equivalent. + // Keep the one with the larger full version. + // If full versions are exactly equal, it's a true duplicate error. + let (current_pkg, _) = pkg_details_map.get(&name).unwrap(); + match prev_pkg.name.full_version_cmp(¤t_pkg.name) { + std::cmp::Ordering::Greater => { + // Previous package had larger version, put it back + pkg_details_map + .insert(name, (prev_pkg, prev_source_map_index)); + } + std::cmp::Ordering::Less => { + // Current (just inserted) is larger, keep it + } + std::cmp::Ordering::Equal => { + let prev_offset = source_map_offsets[prev_source_map_index]; + let mut span1 = my_span; + span1.adjust(offset); + let mut span2 = prev_pkg.package_name_span; + span2.adjust(prev_offset); + return Err(ResolveError::from( + ResolveErrorKind::DuplicatePackage { + name, + span1, + span2, + }, + )); + } + } + } + #[cfg(not(feature = "canon-names"))] + { + let prev_offset = source_map_offsets[prev_source_map_index]; + let mut span1 = my_span; + span1.adjust(offset); + let mut span2 = prev_pkg.package_name_span; + span2.adjust(prev_offset); + return Err(ResolveError::from(ResolveErrorKind::DuplicatePackage { + name, + span1, + span2, + })); + } } } diff --git a/crates/wit-parser/tests/all.rs b/crates/wit-parser/tests/all.rs index e24e0e6a50..8cdc85986c 100644 --- a/crates/wit-parser/tests/all.rs +++ b/crates/wit-parser/tests/all.rs @@ -24,6 +24,10 @@ fn main() { let mut trials = Vec::new(); for test in tests { + let name = test.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + if cfg!(feature = "canon-names") != name.starts_with("canon-names-") { + continue; + } let trial = Trial::test(format!("{test:?}"), move || { Runner {} .run(&test) diff --git a/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit b/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit new file mode 100644 index 0000000000..1f438b7141 --- /dev/null +++ b/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit @@ -0,0 +1,24 @@ +package foo:root; +package foo:name@1.0.0 { + interface i1 { + type a = u32; + } + + world w1 { + import imp1: interface { + use i1.{a}; + } + } +} + +package foo:name@1.0.1 { + interface i1 { + type a = u32; + } + + world w1 { + import imp1: interface { + use i1.{a}; + } + } +} diff --git a/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit.json b/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit.json new file mode 100644 index 0000000000..5cad06b08b --- /dev/null +++ b/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit.json @@ -0,0 +1,75 @@ +{ + "worlds": [ + { + "name": "w1", + "imports": { + "interface-0": { + "interface": { + "id": 0 + } + }, + "imp1": { + "interface": { + "id": 1 + } + } + }, + "exports": {}, + "package": 0 + } + ], + "interfaces": [ + { + "name": "i1", + "types": { + "a": 0 + }, + "functions": {}, + "package": 0 + }, + { + "name": null, + "types": { + "a": 1 + }, + "functions": {}, + "package": 0 + } + ], + "types": [ + { + "name": "a", + "kind": { + "type": "u32" + }, + "owner": { + "interface": 0 + } + }, + { + "name": "a", + "kind": { + "type": 0 + }, + "owner": { + "interface": 1 + } + } + ], + "packages": [ + { + "name": "foo:name@1.0.1", + "interfaces": { + "i1": 0 + }, + "worlds": { + "w1": 0 + } + }, + { + "name": "foo:root", + "interfaces": {}, + "worlds": {} + } + ] +} \ No newline at end of file diff --git a/crates/wit-parser/tests/ui/canon-names-version-syntax.wit b/crates/wit-parser/tests/ui/canon-names-version-syntax.wit new file mode 100644 index 0000000000..14d08afe82 --- /dev/null +++ b/crates/wit-parser/tests/ui/canon-names-version-syntax.wit @@ -0,0 +1,10 @@ +package foo:root; +package a:b@1.0.0 {} +package a:b@1.0.1 {} +package a:b@1.0.1-- {} +package a:b@1.0.1-a+a {} +package a:b@1.0.1-1+1 {} +package a:b@1.0.1-1a+1a {} +package a:b@1.0.0-11-a {} +package a:b@1.0.0-a1.1-a {} +package a:b@1.0.0-11ab {} diff --git a/crates/wit-parser/tests/ui/canon-names-version-syntax.wit.json b/crates/wit-parser/tests/ui/canon-names-version-syntax.wit.json new file mode 100644 index 0000000000..1965925e5f --- /dev/null +++ b/crates/wit-parser/tests/ui/canon-names-version-syntax.wit.json @@ -0,0 +1,17 @@ +{ + "worlds": [], + "interfaces": [], + "types": [], + "packages": [ + { + "name": "a:b@1.0.1", + "interfaces": {}, + "worlds": {} + }, + { + "name": "foo:root", + "interfaces": {}, + "worlds": {} + } + ] +} \ No newline at end of file From f513d36efcabd49df40ba2a6734429fec6e74a75 Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Thu, 13 Aug 2026 18:02:38 -0700 Subject: [PATCH 3/8] improve error message --- .../error.txt | 2 +- crates/wit-parser/src/ast/resolve.rs | 14 +++++++++++++- .../tests/ui/parse-fail/export-twice.wit.result | 2 +- .../tests/ui/parse-fail/import-twice.wit.result | 2 +- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt index bc870c544b..5d0561cea6 100644 --- a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt +++ b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt @@ -1 +1 @@ -failed to parse package: tests/components/canon-names-error-merge-import-versions: interface cannot be imported more than once \ No newline at end of file +failed to parse package: tests/components/canon-names-error-merge-import-versions: interface `a:b@0.1.1/c` cannot be imported more than once \ No newline at end of file diff --git a/crates/wit-parser/src/ast/resolve.rs b/crates/wit-parser/src/ast/resolve.rs index 3ac115a27d..df1cdc1b33 100644 --- a/crates/wit-parser/src/ast/resolve.rs +++ b/crates/wit-parser/src/ast/resolve.rs @@ -711,9 +711,21 @@ impl<'a> Resolver<'a> { }; if let WorldKey::Interface(id) = key { if !interfaces.insert(id) { + let full_name = match kind { + ast::ExternKind::Path(ast::UsePath::Package { id, name }) => { + let pkg = id.package_name(); + format!("{pkg}/{}", name.name) + } + _ => self.interfaces[id] + .name + .clone() + .unwrap_or_else(|| "unnamed".into()), + }; return Err(ParseError::new_syntax( kind.span(), - format!("interface cannot be {desc}ed more than once"), + format!( + "interface `{full_name}` cannot be {desc}ed more than once", + ), )); } } diff --git a/crates/wit-parser/tests/ui/parse-fail/export-twice.wit.result b/crates/wit-parser/tests/ui/parse-fail/export-twice.wit.result index ea6d0ecd7c..cc5f58aea4 100644 --- a/crates/wit-parser/tests/ui/parse-fail/export-twice.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/export-twice.wit.result @@ -1,4 +1,4 @@ -interface cannot be exported more than once +interface `foo` cannot be exported more than once --> tests/ui/parse-fail/export-twice.wit:7:10 | 7 | export foo; diff --git a/crates/wit-parser/tests/ui/parse-fail/import-twice.wit.result b/crates/wit-parser/tests/ui/parse-fail/import-twice.wit.result index d369190755..049391b608 100644 --- a/crates/wit-parser/tests/ui/parse-fail/import-twice.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/import-twice.wit.result @@ -1,4 +1,4 @@ -interface cannot be imported more than once +interface `foo` cannot be imported more than once --> tests/ui/parse-fail/import-twice.wit:7:10 | 7 | import foo; From f28270da58088bd673a2435ee04f0203f47a70f5 Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Thu, 13 Aug 2026 19:12:26 -0700 Subject: [PATCH 4/8] refactor tests --- crates/wit-component/tests/components.rs | 24 +- .../components/canon-names-cm32/module.wat | 32 - .../components/canon-names-cm32/module.wit | 30 - .../error.txt | 1 - .../module.wat | 15 - .../module.wit | 30 - .../adapt-old.wat | 10 - .../adapt-old.wit | 19 - .../component.wit.print | 5 - .../module.wat | 9 - .../module.wit | 14 - .../component.canon-names.wat} | 0 .../component.canon-names.wit.print} | 0 .../component.canon-names.wat} | 0 .../component.canon-names.wit.print} | 0 .../component.canon-names.wat} | 86 ++- .../component.canon-names.wit.print | 6 + .../merge-import-versions/component.wat | 94 ++- .../merge-import-versions/component.wit.print | 3 +- .../merge-import-versions/module.wat | 12 +- .../merge-import-versions/module.wit | 4 +- crates/wit-component/tests/interfaces.rs | 29 +- .../tests/interfaces/canon-names-merge.wat | 27 - .../interfaces/canon-names-merge/app.wit | 5 - .../canon-names-merge/app.wit.print | 5 - .../canon-names-merge/deps/lib-v1/lib.wit | 6 - .../canon-names-merge/deps/lib-v2/lib.wit | 7 - .../deps/cli/command.wit | 7 - .../deps/cli/environment.wit | 18 - .../canon-names-wasi-http/deps/cli/exit.wit | 4 - .../deps/cli/imports.wit | 20 - .../canon-names-wasi-http/deps/cli/run.wit | 4 - .../canon-names-wasi-http/deps/cli/stdio.wit | 17 - .../deps/cli/terminal.wit | 47 -- .../deps/clocks/monotonic-clock.wit | 45 -- .../deps/clocks/wall-clock.wit | 42 -- .../deps/clocks/world.wit | 6 - .../deps/filesystem/preopens.wit | 8 - .../deps/filesystem/types.wit | 634 ------------------ .../deps/filesystem/world.wit | 6 - .../canon-names-wasi-http/deps/io/error.wit | 34 - .../canon-names-wasi-http/deps/io/poll.wit | 41 -- .../canon-names-wasi-http/deps/io/streams.wit | 251 ------- .../canon-names-wasi-http/deps/io/world.wit | 6 - .../deps/random/insecure-seed.wit | 25 - .../deps/random/insecure.wit | 22 - .../deps/random/random.wit | 26 - .../deps/random/world.wit | 7 - .../deps/sockets/instance-network.wit | 9 - .../deps/sockets/ip-name-lookup.wit | 51 -- .../deps/sockets/network.wit | 147 ---- .../deps/sockets/tcp-create-socket.wit | 26 - .../deps/sockets/tcp.wit | 321 --------- .../deps/sockets/udp-create-socket.wit | 26 - .../deps/sockets/udp.wit | 277 -------- .../deps/sockets/world.wit | 11 - .../canon-names-wasi-http/handler.wit | 43 -- .../canon-names-wasi-http/proxy.wit | 32 - .../canon-names-wasi-http/types.wit | 570 ---------------- ...asi-http.wat => wasi-http.canon-names.wat} | 0 .../http.canon-names.wit.print} | 0 crates/wit-parser/tests/all.rs | 12 +- .../ui/canon-names-nested-with-semver.wit | 24 - .../tests/ui/canon-names-version-syntax.wit | 10 - ...s-nested-with-semver.wit.canon-names.json} | 0 ...on => version-syntax.wit.canon-names.json} | 0 66 files changed, 198 insertions(+), 3104 deletions(-) delete mode 100644 crates/wit-component/tests/components/canon-names-cm32/module.wat delete mode 100644 crates/wit-component/tests/components/canon-names-cm32/module.wit delete mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt delete mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat delete mode 100644 crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit delete mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat delete mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit delete mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print delete mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat delete mode 100644 crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit rename crates/wit-component/tests/components/{canon-names-cm32/component.wat => cm32-names/component.canon-names.wat} (100%) rename crates/wit-component/tests/components/{canon-names-cm32/component.wit.print => cm32-names/component.canon-names.wit.print} (100%) rename crates/wit-component/tests/components/{canon-names-merge-import-versions-with-adapter/component.wat => merge-import-versions-with-adapter/component.canon-names.wat} (100%) rename crates/wit-component/tests/components/{canon-names-error-merge-import-versions/component.wit.print => merge-import-versions-with-adapter/component.canon-names.wit.print} (100%) rename crates/wit-component/tests/components/{canon-names-error-merge-import-versions/component.wat => merge-import-versions/component.canon-names.wat} (54%) create mode 100644 crates/wit-component/tests/components/merge-import-versions/component.canon-names.wit.print delete mode 100644 crates/wit-component/tests/interfaces/canon-names-merge.wat delete mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/app.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print delete mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit delete mode 100644 crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit rename crates/wit-component/tests/interfaces/{canon-names-wasi-http.wat => wasi-http.canon-names.wat} (100%) rename crates/wit-component/tests/interfaces/{canon-names-wasi-http/http.wit.print => wasi-http/http.canon-names.wit.print} (100%) delete mode 100644 crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit delete mode 100644 crates/wit-parser/tests/ui/canon-names-version-syntax.wit rename crates/wit-parser/tests/ui/{canon-names-nested-with-semver.wit.json => packages-nested-with-semver.wit.canon-names.json} (100%) rename crates/wit-parser/tests/ui/{canon-names-version-syntax.wit.json => version-syntax.wit.canon-names.json} (100%) diff --git a/crates/wit-component/tests/components.rs b/crates/wit-component/tests/components.rs index b2acb4bdee..5cbdd27fa2 100644 --- a/crates/wit-component/tests/components.rs +++ b/crates/wit-component/tests/components.rs @@ -63,7 +63,7 @@ fn main() -> Result<()> { continue; } let name = path.file_name().unwrap().to_str().unwrap(); - if cfg!(feature = "canon-names") != name.starts_with("canon-names-") { + if name.starts_with("canon-names-") { continue; } @@ -80,7 +80,23 @@ fn main() -> Result<()> { } fn is_error_test(test_case: &str) -> bool { - test_case.starts_with("error-") || test_case.starts_with("canon-names-error-") + test_case.starts_with("error-") +} + +fn canon_names_output(path: &Path, name: &str) -> std::path::PathBuf { + if cfg!(feature = "canon-names") { + let parts: Vec<&str> = name.splitn(2, '.').collect(); + let canon_name = if parts.len() == 2 { + format!("{}.canon-names.{}", parts[0], parts[1]) + } else { + format!("{name}.canon-names") + }; + let canon_path = path.join(&canon_name); + if std::env::var_os("BLESS").is_some() || canon_path.exists() { + return canon_path; + } + } + path.join(name) } fn run_test(path: &Path) -> Result<()> { @@ -154,8 +170,8 @@ fn run_test(path: &Path) -> Result<()> { })? .encode() }; - let component_path = path.join("component.wat"); - let component_wit_path = path.join("component.wit.print"); + let component_path = canon_names_output(&path, "component.wat"); + let component_wit_path = canon_names_output(&path, "component.wit.print"); let error_path = path.join("error.txt"); let bytes = match result { diff --git a/crates/wit-component/tests/components/canon-names-cm32/module.wat b/crates/wit-component/tests/components/canon-names-cm32/module.wat deleted file mode 100644 index 6b1b47b5d4..0000000000 --- a/crates/wit-component/tests/components/canon-names-cm32/module.wat +++ /dev/null @@ -1,32 +0,0 @@ -(module - (import "cm32p2" "f" (func (param i32))) - (import "cm32p2|ns:pkg/i@0.2" "[constructor]r" (func (param i32 i32) (result i32))) - (import "cm32p2|ns:pkg/i@0.2" "[method]r.m" (func (param i32 i32))) - (import "cm32p2|ns:pkg/i@0.2" "frob" (func (param i32) (result i32))) - (import "cm32p2|ns:pkg/i@0.2" "r_drop" (func (param i32))) - (import "cm32p2|j" "[constructor]r" (func (param i32 i32) (result i32))) - (import "cm32p2|j" "[method]r.m" (func (param i32 i32))) - (import "cm32p2|j" "frob" (func (param i32) (result i32))) - (import "cm32p2|j" "r_drop" (func (param i32))) - (import "cm32p2|_ex_ns:pkg/i@0.2" "r_drop" (func (param i32))) - (import "cm32p2|_ex_ns:pkg/i@0.2" "r_new" (func (param i32) (result i32))) - (import "cm32p2|_ex_ns:pkg/i@0.2" "r_rep" (func (param i32) (result i32))) - (import "cm32p2|_ex_j" "r_drop" (func (param i32))) - (import "cm32p2|_ex_j" "r_new" (func (param i32) (result i32))) - (import "cm32p2|_ex_j" "r_rep" (func (param i32) (result i32))) - - (memory (export "cm32p2_memory") 0) - - (func (export "cm32p2||g") (result i32) unreachable) - (func (export "cm32p2||g_post") (param i32) unreachable) - (func (export "cm32p2|ns:pkg/i@0.2|[constructor]r") (param i32 i32) (result i32) unreachable) - (func (export "cm32p2|ns:pkg/i@0.2|[method]r.m") (param i32) (result i32) unreachable) - (func (export "cm32p2|ns:pkg/i@0.2|frob") (param i32) (result i32) unreachable) - (func (export "cm32p2|ns:pkg/i@0.2|r_dtor") (param i32) unreachable) - (func (export "cm32p2|j|[constructor]r") (param i32 i32) (result i32) unreachable) - (func (export "cm32p2|j|[method]r.m") (param i32) (result i32) unreachable) - (func (export "cm32p2|j|frob") (param i32) (result i32) unreachable) - (func (export "cm32p2|j|r_dtor") (param i32) unreachable) - (func (export "cm32p2_realloc") (param i32 i32 i32 i32) (result i32) unreachable) - (func (export "cm32p2_initialize")) -) diff --git a/crates/wit-component/tests/components/canon-names-cm32/module.wit b/crates/wit-component/tests/components/canon-names-cm32/module.wit deleted file mode 100644 index 32d8820e8f..0000000000 --- a/crates/wit-component/tests/components/canon-names-cm32/module.wit +++ /dev/null @@ -1,30 +0,0 @@ -package ns:pkg@0.2.1; - -interface i { - resource r { - constructor(s: string); - m: func() -> string; - } - frob: func(in: r) -> r; -} - -world module { - import f: func() -> string; - import i; - import j: interface { - resource r { - constructor(s: string); - m: func() -> string; - } - frob: func(in: r) -> r; - } - export g: func() -> string; - export i; - export j: interface { - resource r { - constructor(s: string); - m: func() -> string; - } - frob: func(in: r) -> r; - } -} diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt deleted file mode 100644 index 5d0561cea6..0000000000 --- a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/error.txt +++ /dev/null @@ -1 +0,0 @@ -failed to parse package: tests/components/canon-names-error-merge-import-versions: interface `a:b@0.1.1/c` cannot be imported more than once \ No newline at end of file diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat deleted file mode 100644 index b23e81cc96..0000000000 --- a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wat +++ /dev/null @@ -1,15 +0,0 @@ -(module - (import "a:b/c@0.1.0" "[constructor]r" (func (result i32))) - (import "a:b/c@0.1.0" "[resource-drop]r" (func (param i32))) - (import "a:b/c@0.1.0" "x" (func (param i32 i32))) - (import "a:b/c@0.1.0" "x2" (func (param i32 i32))) - - (import "a:b/c@0.1.1" "[constructor]r" (func (result i32))) - (import "a:b/c@0.1.1" "[resource-drop]r" (func (param i32))) - (import "a:b/c@0.1.1" "[method]r.x" (func (param i32))) - (import "a:b/c@0.1.1" "x" (func (param i32 i32))) - (import "a:b/c@0.1.1" "x2" (func (param i32 i32))) - (import "a:b/c@0.1.1" "y" (func)) - - (memory (export "memory") 1) -) diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit b/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit deleted file mode 100644 index 63dacf4115..0000000000 --- a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/module.wit +++ /dev/null @@ -1,30 +0,0 @@ -package foo:foo; - -world module { - import a:b/c@0.1.0; - import a:b/c@0.1.1; -} - -package a:b@0.1.0 { - interface c { - resource r { - constructor(); - } - x: func(x: string); - x2: func(x: string); - } -} - -package a:b@0.1.1 { - interface c { - x: func(x: string); - x2: func(x: string); - y: func(); - - resource r { - constructor(); - - x: func(); - } - } -} diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat deleted file mode 100644 index 6a32ffa471..0000000000 --- a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wat +++ /dev/null @@ -1,10 +0,0 @@ -(module - (import "a:b/c@0.1.1" "[constructor]r" (func (result i32))) - (import "a:b/c@0.1.1" "[resource-drop]r" (func (param i32))) - (import "a:b/c@0.1.1" "[method]r.x" (func (param i32))) - (import "a:b/c@0.1.1" "x" (func (param i32 i32))) - (import "a:b/c@0.1.1" "y" (func)) - - (func (export "f")) -) - diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit deleted file mode 100644 index 842ec11b64..0000000000 --- a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/adapt-old.wit +++ /dev/null @@ -1,19 +0,0 @@ -package foo:foo; - -world adapt-old { - import a:b/c@0.1.1; -} - -package a:b@0.1.1 { - interface c { - x: func(x: string); - y: func(); - - resource r { - constructor(); - - x: func(); - } - } -} - diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print deleted file mode 100644 index 1a2ed3c569..0000000000 --- a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wit.print +++ /dev/null @@ -1,5 +0,0 @@ -package root:component; - -world root { - import a:b/c@0.1.1; -} diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat deleted file mode 100644 index dafd15681a..0000000000 --- a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wat +++ /dev/null @@ -1,9 +0,0 @@ -(module - (import "old" "f" (func)) - - (import "a:b/c@0.1.0" "[constructor]r" (func (result i32))) - (import "a:b/c@0.1.0" "[resource-drop]r" (func (param i32))) - (import "a:b/c@0.1.0" "x" (func (param i32 i32))) - - (memory (export "memory") 1) -) diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit b/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit deleted file mode 100644 index 6e60c34822..0000000000 --- a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/module.wit +++ /dev/null @@ -1,14 +0,0 @@ -package foo:foo; - -world module { - import a:b/c@0.1.0; -} - -package a:b@0.1.0 { - interface c { - resource r { - constructor(); - } - x: func(x: string); - } -} diff --git a/crates/wit-component/tests/components/canon-names-cm32/component.wat b/crates/wit-component/tests/components/cm32-names/component.canon-names.wat similarity index 100% rename from crates/wit-component/tests/components/canon-names-cm32/component.wat rename to crates/wit-component/tests/components/cm32-names/component.canon-names.wat diff --git a/crates/wit-component/tests/components/canon-names-cm32/component.wit.print b/crates/wit-component/tests/components/cm32-names/component.canon-names.wit.print similarity index 100% rename from crates/wit-component/tests/components/canon-names-cm32/component.wit.print rename to crates/wit-component/tests/components/cm32-names/component.canon-names.wit.print diff --git a/crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wat b/crates/wit-component/tests/components/merge-import-versions-with-adapter/component.canon-names.wat similarity index 100% rename from crates/wit-component/tests/components/canon-names-merge-import-versions-with-adapter/component.wat rename to crates/wit-component/tests/components/merge-import-versions-with-adapter/component.canon-names.wat diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wit.print b/crates/wit-component/tests/components/merge-import-versions-with-adapter/component.canon-names.wit.print similarity index 100% rename from crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wit.print rename to crates/wit-component/tests/components/merge-import-versions-with-adapter/component.canon-names.wit.print diff --git a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wat b/crates/wit-component/tests/components/merge-import-versions/component.canon-names.wat similarity index 54% rename from crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wat rename to crates/wit-component/tests/components/merge-import-versions/component.canon-names.wat index 9ed9267bc7..376ab17ca8 100644 --- a/crates/wit-component/tests/components/canon-names-error-merge-import-versions/component.wat +++ b/crates/wit-component/tests/components/merge-import-versions/component.canon-names.wat @@ -1,5 +1,17 @@ (component (type $ty-a:b/c@0.1 (;0;) + (instance + (export (;0;) "r" (type (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (result 1))) + (export (;0;) "[constructor]r" (func (type 2))) + (type (;3;) (func (param "x" string))) + (export (;1;) "x" (func (type 3))) + (export (;2;) "x2" (func (type 3))) + ) + ) + (import "a:b/c@0.1" (versionsuffix ".0") (instance $a:b/c@0.1 (;0;) (type $ty-a:b/c@0.1))) + (type $ty-a:b/c@0.2 (;1;) (instance (export (;0;) "r" (type (sub resource))) (type (;1;) (own 0)) @@ -15,7 +27,7 @@ (export (;4;) "y" (func (type 6))) ) ) - (import "a:b/c@0.1" (versionsuffix ".1") (instance $a:b/c@0.1 (;0;) (type $ty-a:b/c@0.1))) + (import "a:b/c@0.2" (versionsuffix ".1") (instance $a:b/c@0.2 (;1;) (type $ty-a:b/c@0.2))) (core module $main (;0;) (type (;0;) (func (result i32))) (type (;1;) (func (param i32))) @@ -25,12 +37,12 @@ (import "a:b/c@0.1.0" "[resource-drop]r" (func (;1;) (type 1))) (import "a:b/c@0.1.0" "x" (func (;2;) (type 2))) (import "a:b/c@0.1.0" "x2" (func (;3;) (type 2))) - (import "a:b/c@0.1.1" "[constructor]r" (func (;4;) (type 0))) - (import "a:b/c@0.1.1" "[resource-drop]r" (func (;5;) (type 1))) - (import "a:b/c@0.1.1" "[method]r.x" (func (;6;) (type 1))) - (import "a:b/c@0.1.1" "x" (func (;7;) (type 2))) - (import "a:b/c@0.1.1" "x2" (func (;8;) (type 2))) - (import "a:b/c@0.1.1" "y" (func (;9;) (type 3))) + (import "a:b/c@0.2.1" "[constructor]r" (func (;4;) (type 0))) + (import "a:b/c@0.2.1" "[resource-drop]r" (func (;5;) (type 1))) + (import "a:b/c@0.2.1" "[method]r.x" (func (;6;) (type 1))) + (import "a:b/c@0.2.1" "x" (func (;7;) (type 2))) + (import "a:b/c@0.2.1" "x2" (func (;8;) (type 2))) + (import "a:b/c@0.2.1" "y" (func (;9;) (type 3))) (memory (;0;) 1) (export "memory" (memory 0)) (@producers @@ -40,9 +52,11 @@ ) (core module $wit-component-shim-module (;1;) (type (;0;) (func (param i32 i32))) - (table (;0;) 2 2 funcref) + (table (;0;) 4 4 funcref) (export "0" (func $indirect-a:b/c@0.1.0-x)) (export "1" (func $indirect-a:b/c@0.1.0-x2)) + (export "2" (func $indirect-a:b/c@0.2.1-x)) + (export "3" (func $indirect-a:b/c@0.2.1-x2)) (export "$imports" (table 0)) (func $indirect-a:b/c@0.1.0-x (;0;) (type 0) (param i32 i32) local.get 0 @@ -56,6 +70,18 @@ i32.const 1 call_indirect (type 0) ) + (func $indirect-a:b/c@0.2.1-x (;2;) (type 0) (param i32 i32) + local.get 0 + local.get 1 + i32.const 2 + call_indirect (type 0) + ) + (func $indirect-a:b/c@0.2.1-x2 (;3;) (type 0) (param i32 i32) + local.get 0 + local.get 1 + i32.const 3 + call_indirect (type 0) + ) (@producers (processed-by "wit-component" "$CARGO_PKG_VERSION") ) @@ -64,8 +90,10 @@ (type (;0;) (func (param i32 i32))) (import "" "0" (func (;0;) (type 0))) (import "" "1" (func (;1;) (type 0))) - (import "" "$imports" (table (;0;) 2 2 funcref)) - (elem (;0;) (i32.const 0) func 0 1) + (import "" "2" (func (;2;) (type 0))) + (import "" "3" (func (;3;) (type 0))) + (import "" "$imports" (table (;0;) 4 4 funcref)) + (elem (;0;) (i32.const 0) func 0 1 2 3) (@producers (processed-by "wit-component" "$CARGO_PKG_VERSION") ) @@ -73,7 +101,7 @@ (core instance $wit-component-shim-instance (;0;) (instantiate $wit-component-shim-module)) (alias export $a:b/c@0.1 "[constructor]r" (func $"[constructor]r" (;0;))) (core func $"[constructor]r" (;0;) (canon lower (func $"[constructor]r"))) - (alias export $a:b/c@0.1 "r" (type $r (;1;))) + (alias export $a:b/c@0.1 "r" (type $r (;2;))) (core func $resource.drop (;1;) (canon resource.drop $r)) (alias core export $wit-component-shim-instance "0" (core func $indirect-a:b/c@0.1.0-x (;2;))) (alias core export $wit-component-shim-instance "1" (core func $indirect-a:b/c@0.1.0-x2 (;3;))) @@ -83,37 +111,45 @@ (export "x" (func $indirect-a:b/c@0.1.0-x)) (export "x2" (func $indirect-a:b/c@0.1.0-x2)) ) - (alias export $a:b/c@0.1 "[constructor]r" (func $"#func1 [constructor]r" (@name "[constructor]r") (;1;))) + (alias export $a:b/c@0.2 "[constructor]r" (func $"#func1 [constructor]r" (@name "[constructor]r") (;1;))) (core func $"#core-func4 [constructor]r" (@name "[constructor]r") (;4;) (canon lower (func $"#func1 [constructor]r"))) - (alias export $a:b/c@0.1 "r" (type $"#type2 r" (@name "r") (;2;))) - (core func $"#core-func5 resource.drop" (@name "resource.drop") (;5;) (canon resource.drop $"#type2 r")) - (alias export $a:b/c@0.1 "[method]r.x" (func $"[method]r.x" (;2;))) + (alias export $a:b/c@0.2 "r" (type $"#type3 r" (@name "r") (;3;))) + (core func $"#core-func5 resource.drop" (@name "resource.drop") (;5;) (canon resource.drop $"#type3 r")) + (alias export $a:b/c@0.2 "[method]r.x" (func $"[method]r.x" (;2;))) (core func $"[method]r.x" (;6;) (canon lower (func $"[method]r.x"))) - (alias export $a:b/c@0.1 "y" (func $y (;3;))) - (core func $y (;7;) (canon lower (func $y))) - (core instance $a:b/c@0.1.1 (;2;) + (alias core export $wit-component-shim-instance "2" (core func $indirect-a:b/c@0.2.1-x (;7;))) + (alias core export $wit-component-shim-instance "3" (core func $indirect-a:b/c@0.2.1-x2 (;8;))) + (alias export $a:b/c@0.2 "y" (func $y (;3;))) + (core func $y (;9;) (canon lower (func $y))) + (core instance $a:b/c@0.2.1 (;2;) (export "[constructor]r" (func $"#core-func4 [constructor]r")) (export "[resource-drop]r" (func $"#core-func5 resource.drop")) (export "[method]r.x" (func $"[method]r.x")) - (export "x" (func $indirect-a:b/c@0.1.0-x)) - (export "x2" (func $indirect-a:b/c@0.1.0-x2)) + (export "x" (func $indirect-a:b/c@0.2.1-x)) + (export "x2" (func $indirect-a:b/c@0.2.1-x2)) (export "y" (func $y)) ) (core instance $main (;3;) (instantiate $main (with "a:b/c@0.1.0" (instance $a:b/c@0.1.0)) - (with "a:b/c@0.1.1" (instance $a:b/c@0.1.1)) + (with "a:b/c@0.2.1" (instance $a:b/c@0.2.1)) ) ) (alias core export $main "memory" (core memory $memory (;0;))) (alias core export $wit-component-shim-instance "$imports" (core table $"shim table" (;0;))) (alias export $a:b/c@0.1 "x" (func $x (;4;))) - (core func $"#core-func8 indirect-a:b/c@0.1.0-x" (@name "indirect-a:b/c@0.1.0-x") (;8;) (canon lower (func $x) (memory $memory) string-encoding=utf8)) + (core func $"#core-func10 indirect-a:b/c@0.1.0-x" (@name "indirect-a:b/c@0.1.0-x") (;10;) (canon lower (func $x) (memory $memory) string-encoding=utf8)) (alias export $a:b/c@0.1 "x2" (func $x2 (;5;))) - (core func $"#core-func9 indirect-a:b/c@0.1.0-x2" (@name "indirect-a:b/c@0.1.0-x2") (;9;) (canon lower (func $x2) (memory $memory) string-encoding=utf8)) + (core func $"#core-func11 indirect-a:b/c@0.1.0-x2" (@name "indirect-a:b/c@0.1.0-x2") (;11;) (canon lower (func $x2) (memory $memory) string-encoding=utf8)) + (alias export $a:b/c@0.2 "x" (func $"#func6 x" (@name "x") (;6;))) + (core func $"#core-func12 indirect-a:b/c@0.2.1-x" (@name "indirect-a:b/c@0.2.1-x") (;12;) (canon lower (func $"#func6 x") (memory $memory) string-encoding=utf8)) + (alias export $a:b/c@0.2 "x2" (func $"#func7 x2" (@name "x2") (;7;))) + (core func $"#core-func13 indirect-a:b/c@0.2.1-x2" (@name "indirect-a:b/c@0.2.1-x2") (;13;) (canon lower (func $"#func7 x2") (memory $memory) string-encoding=utf8)) (core instance $fixup-args (;4;) (export "$imports" (table $"shim table")) - (export "0" (func $"#core-func8 indirect-a:b/c@0.1.0-x")) - (export "1" (func $"#core-func9 indirect-a:b/c@0.1.0-x2")) + (export "0" (func $"#core-func10 indirect-a:b/c@0.1.0-x")) + (export "1" (func $"#core-func11 indirect-a:b/c@0.1.0-x2")) + (export "2" (func $"#core-func12 indirect-a:b/c@0.2.1-x")) + (export "3" (func $"#core-func13 indirect-a:b/c@0.2.1-x2")) ) (core instance $fixup (;5;) (instantiate $wit-component-fixup (with "" (instance $fixup-args)) diff --git a/crates/wit-component/tests/components/merge-import-versions/component.canon-names.wit.print b/crates/wit-component/tests/components/merge-import-versions/component.canon-names.wit.print new file mode 100644 index 0000000000..1da1fb1e42 --- /dev/null +++ b/crates/wit-component/tests/components/merge-import-versions/component.canon-names.wit.print @@ -0,0 +1,6 @@ +package root:component; + +world root { + import a:b/c@0.1.0; + import a:b/c@0.2.1; +} diff --git a/crates/wit-component/tests/components/merge-import-versions/component.wat b/crates/wit-component/tests/components/merge-import-versions/component.wat index 49aaa1b655..3f73faf4a1 100644 --- a/crates/wit-component/tests/components/merge-import-versions/component.wat +++ b/crates/wit-component/tests/components/merge-import-versions/component.wat @@ -1,5 +1,17 @@ (component - (type $ty-a:b/c@0.1.1 (;0;) + (type $ty-a:b/c@0.1.0 (;0;) + (instance + (export (;0;) "r" (type (sub resource))) + (type (;1;) (own 0)) + (type (;2;) (func (result 1))) + (export (;0;) "[constructor]r" (func (type 2))) + (type (;3;) (func (param "x" string))) + (export (;1;) "x" (func (type 3))) + (export (;2;) "x2" (func (type 3))) + ) + ) + (import "a:b/c@0.1.0" (instance $a:b/c@0.1.0 (;0;) (type $ty-a:b/c@0.1.0))) + (type $ty-a:b/c@0.2.1 (;1;) (instance (export (;0;) "r" (type (sub resource))) (type (;1;) (own 0)) @@ -15,7 +27,7 @@ (export (;4;) "y" (func (type 6))) ) ) - (import "a:b/c@0.1.1" (instance $a:b/c@0.1.1 (;0;) (type $ty-a:b/c@0.1.1))) + (import "a:b/c@0.2.1" (instance $a:b/c@0.2.1 (;1;) (type $ty-a:b/c@0.2.1))) (core module $main (;0;) (type (;0;) (func (result i32))) (type (;1;) (func (param i32))) @@ -25,12 +37,12 @@ (import "a:b/c@0.1.0" "[resource-drop]r" (func (;1;) (type 1))) (import "a:b/c@0.1.0" "x" (func (;2;) (type 2))) (import "a:b/c@0.1.0" "x2" (func (;3;) (type 2))) - (import "a:b/c@0.1.1" "[constructor]r" (func (;4;) (type 0))) - (import "a:b/c@0.1.1" "[resource-drop]r" (func (;5;) (type 1))) - (import "a:b/c@0.1.1" "[method]r.x" (func (;6;) (type 1))) - (import "a:b/c@0.1.1" "x" (func (;7;) (type 2))) - (import "a:b/c@0.1.1" "x2" (func (;8;) (type 2))) - (import "a:b/c@0.1.1" "y" (func (;9;) (type 3))) + (import "a:b/c@0.2.1" "[constructor]r" (func (;4;) (type 0))) + (import "a:b/c@0.2.1" "[resource-drop]r" (func (;5;) (type 1))) + (import "a:b/c@0.2.1" "[method]r.x" (func (;6;) (type 1))) + (import "a:b/c@0.2.1" "x" (func (;7;) (type 2))) + (import "a:b/c@0.2.1" "x2" (func (;8;) (type 2))) + (import "a:b/c@0.2.1" "y" (func (;9;) (type 3))) (memory (;0;) 1) (export "memory" (memory 0)) (@producers @@ -40,9 +52,11 @@ ) (core module $wit-component-shim-module (;1;) (type (;0;) (func (param i32 i32))) - (table (;0;) 2 2 funcref) + (table (;0;) 4 4 funcref) (export "0" (func $indirect-a:b/c@0.1.0-x)) (export "1" (func $indirect-a:b/c@0.1.0-x2)) + (export "2" (func $indirect-a:b/c@0.2.1-x)) + (export "3" (func $indirect-a:b/c@0.2.1-x2)) (export "$imports" (table 0)) (func $indirect-a:b/c@0.1.0-x (;0;) (type 0) (param i32 i32) local.get 0 @@ -56,6 +70,18 @@ i32.const 1 call_indirect (type 0) ) + (func $indirect-a:b/c@0.2.1-x (;2;) (type 0) (param i32 i32) + local.get 0 + local.get 1 + i32.const 2 + call_indirect (type 0) + ) + (func $indirect-a:b/c@0.2.1-x2 (;3;) (type 0) (param i32 i32) + local.get 0 + local.get 1 + i32.const 3 + call_indirect (type 0) + ) (@producers (processed-by "wit-component" "$CARGO_PKG_VERSION") ) @@ -64,16 +90,18 @@ (type (;0;) (func (param i32 i32))) (import "" "0" (func (;0;) (type 0))) (import "" "1" (func (;1;) (type 0))) - (import "" "$imports" (table (;0;) 2 2 funcref)) - (elem (;0;) (i32.const 0) func 0 1) + (import "" "2" (func (;2;) (type 0))) + (import "" "3" (func (;3;) (type 0))) + (import "" "$imports" (table (;0;) 4 4 funcref)) + (elem (;0;) (i32.const 0) func 0 1 2 3) (@producers (processed-by "wit-component" "$CARGO_PKG_VERSION") ) ) (core instance $wit-component-shim-instance (;0;) (instantiate $wit-component-shim-module)) - (alias export $a:b/c@0.1.1 "[constructor]r" (func $"[constructor]r" (;0;))) + (alias export $a:b/c@0.1.0 "[constructor]r" (func $"[constructor]r" (;0;))) (core func $"[constructor]r" (;0;) (canon lower (func $"[constructor]r"))) - (alias export $a:b/c@0.1.1 "r" (type $r (;1;))) + (alias export $a:b/c@0.1.0 "r" (type $r (;2;))) (core func $resource.drop (;1;) (canon resource.drop $r)) (alias core export $wit-component-shim-instance "0" (core func $indirect-a:b/c@0.1.0-x (;2;))) (alias core export $wit-component-shim-instance "1" (core func $indirect-a:b/c@0.1.0-x2 (;3;))) @@ -83,37 +111,45 @@ (export "x" (func $indirect-a:b/c@0.1.0-x)) (export "x2" (func $indirect-a:b/c@0.1.0-x2)) ) - (alias export $a:b/c@0.1.1 "[constructor]r" (func $"#func1 [constructor]r" (@name "[constructor]r") (;1;))) + (alias export $a:b/c@0.2.1 "[constructor]r" (func $"#func1 [constructor]r" (@name "[constructor]r") (;1;))) (core func $"#core-func4 [constructor]r" (@name "[constructor]r") (;4;) (canon lower (func $"#func1 [constructor]r"))) - (alias export $a:b/c@0.1.1 "r" (type $"#type2 r" (@name "r") (;2;))) - (core func $"#core-func5 resource.drop" (@name "resource.drop") (;5;) (canon resource.drop $"#type2 r")) - (alias export $a:b/c@0.1.1 "[method]r.x" (func $"[method]r.x" (;2;))) + (alias export $a:b/c@0.2.1 "r" (type $"#type3 r" (@name "r") (;3;))) + (core func $"#core-func5 resource.drop" (@name "resource.drop") (;5;) (canon resource.drop $"#type3 r")) + (alias export $a:b/c@0.2.1 "[method]r.x" (func $"[method]r.x" (;2;))) (core func $"[method]r.x" (;6;) (canon lower (func $"[method]r.x"))) - (alias export $a:b/c@0.1.1 "y" (func $y (;3;))) - (core func $y (;7;) (canon lower (func $y))) - (core instance $a:b/c@0.1.1 (;2;) + (alias core export $wit-component-shim-instance "2" (core func $indirect-a:b/c@0.2.1-x (;7;))) + (alias core export $wit-component-shim-instance "3" (core func $indirect-a:b/c@0.2.1-x2 (;8;))) + (alias export $a:b/c@0.2.1 "y" (func $y (;3;))) + (core func $y (;9;) (canon lower (func $y))) + (core instance $a:b/c@0.2.1 (;2;) (export "[constructor]r" (func $"#core-func4 [constructor]r")) (export "[resource-drop]r" (func $"#core-func5 resource.drop")) (export "[method]r.x" (func $"[method]r.x")) - (export "x" (func $indirect-a:b/c@0.1.0-x)) - (export "x2" (func $indirect-a:b/c@0.1.0-x2)) + (export "x" (func $indirect-a:b/c@0.2.1-x)) + (export "x2" (func $indirect-a:b/c@0.2.1-x2)) (export "y" (func $y)) ) (core instance $main (;3;) (instantiate $main (with "a:b/c@0.1.0" (instance $a:b/c@0.1.0)) - (with "a:b/c@0.1.1" (instance $a:b/c@0.1.1)) + (with "a:b/c@0.2.1" (instance $a:b/c@0.2.1)) ) ) (alias core export $main "memory" (core memory $memory (;0;))) (alias core export $wit-component-shim-instance "$imports" (core table $"shim table" (;0;))) - (alias export $a:b/c@0.1.1 "x" (func $x (;4;))) - (core func $"#core-func8 indirect-a:b/c@0.1.0-x" (@name "indirect-a:b/c@0.1.0-x") (;8;) (canon lower (func $x) (memory $memory) string-encoding=utf8)) - (alias export $a:b/c@0.1.1 "x2" (func $x2 (;5;))) - (core func $"#core-func9 indirect-a:b/c@0.1.0-x2" (@name "indirect-a:b/c@0.1.0-x2") (;9;) (canon lower (func $x2) (memory $memory) string-encoding=utf8)) + (alias export $a:b/c@0.1.0 "x" (func $x (;4;))) + (core func $"#core-func10 indirect-a:b/c@0.1.0-x" (@name "indirect-a:b/c@0.1.0-x") (;10;) (canon lower (func $x) (memory $memory) string-encoding=utf8)) + (alias export $a:b/c@0.1.0 "x2" (func $x2 (;5;))) + (core func $"#core-func11 indirect-a:b/c@0.1.0-x2" (@name "indirect-a:b/c@0.1.0-x2") (;11;) (canon lower (func $x2) (memory $memory) string-encoding=utf8)) + (alias export $a:b/c@0.2.1 "x" (func $"#func6 x" (@name "x") (;6;))) + (core func $"#core-func12 indirect-a:b/c@0.2.1-x" (@name "indirect-a:b/c@0.2.1-x") (;12;) (canon lower (func $"#func6 x") (memory $memory) string-encoding=utf8)) + (alias export $a:b/c@0.2.1 "x2" (func $"#func7 x2" (@name "x2") (;7;))) + (core func $"#core-func13 indirect-a:b/c@0.2.1-x2" (@name "indirect-a:b/c@0.2.1-x2") (;13;) (canon lower (func $"#func7 x2") (memory $memory) string-encoding=utf8)) (core instance $fixup-args (;4;) (export "$imports" (table $"shim table")) - (export "0" (func $"#core-func8 indirect-a:b/c@0.1.0-x")) - (export "1" (func $"#core-func9 indirect-a:b/c@0.1.0-x2")) + (export "0" (func $"#core-func10 indirect-a:b/c@0.1.0-x")) + (export "1" (func $"#core-func11 indirect-a:b/c@0.1.0-x2")) + (export "2" (func $"#core-func12 indirect-a:b/c@0.2.1-x")) + (export "3" (func $"#core-func13 indirect-a:b/c@0.2.1-x2")) ) (core instance $fixup (;5;) (instantiate $wit-component-fixup (with "" (instance $fixup-args)) diff --git a/crates/wit-component/tests/components/merge-import-versions/component.wit.print b/crates/wit-component/tests/components/merge-import-versions/component.wit.print index 1a2ed3c569..1da1fb1e42 100644 --- a/crates/wit-component/tests/components/merge-import-versions/component.wit.print +++ b/crates/wit-component/tests/components/merge-import-versions/component.wit.print @@ -1,5 +1,6 @@ package root:component; world root { - import a:b/c@0.1.1; + import a:b/c@0.1.0; + import a:b/c@0.2.1; } diff --git a/crates/wit-component/tests/components/merge-import-versions/module.wat b/crates/wit-component/tests/components/merge-import-versions/module.wat index b23e81cc96..690c8a370a 100644 --- a/crates/wit-component/tests/components/merge-import-versions/module.wat +++ b/crates/wit-component/tests/components/merge-import-versions/module.wat @@ -4,12 +4,12 @@ (import "a:b/c@0.1.0" "x" (func (param i32 i32))) (import "a:b/c@0.1.0" "x2" (func (param i32 i32))) - (import "a:b/c@0.1.1" "[constructor]r" (func (result i32))) - (import "a:b/c@0.1.1" "[resource-drop]r" (func (param i32))) - (import "a:b/c@0.1.1" "[method]r.x" (func (param i32))) - (import "a:b/c@0.1.1" "x" (func (param i32 i32))) - (import "a:b/c@0.1.1" "x2" (func (param i32 i32))) - (import "a:b/c@0.1.1" "y" (func)) + (import "a:b/c@0.2.1" "[constructor]r" (func (result i32))) + (import "a:b/c@0.2.1" "[resource-drop]r" (func (param i32))) + (import "a:b/c@0.2.1" "[method]r.x" (func (param i32))) + (import "a:b/c@0.2.1" "x" (func (param i32 i32))) + (import "a:b/c@0.2.1" "x2" (func (param i32 i32))) + (import "a:b/c@0.2.1" "y" (func)) (memory (export "memory") 1) ) diff --git a/crates/wit-component/tests/components/merge-import-versions/module.wit b/crates/wit-component/tests/components/merge-import-versions/module.wit index 63dacf4115..dc97b1a4a3 100644 --- a/crates/wit-component/tests/components/merge-import-versions/module.wit +++ b/crates/wit-component/tests/components/merge-import-versions/module.wit @@ -2,7 +2,7 @@ package foo:foo; world module { import a:b/c@0.1.0; - import a:b/c@0.1.1; + import a:b/c@0.2.1; } package a:b@0.1.0 { @@ -15,7 +15,7 @@ package a:b@0.1.0 { } } -package a:b@0.1.1 { +package a:b@0.2.1 { interface c { x: func(x: string); x2: func(x: string); diff --git a/crates/wit-component/tests/interfaces.rs b/crates/wit-component/tests/interfaces.rs index 6881228062..aecbde8f0b 100644 --- a/crates/wit-component/tests/interfaces.rs +++ b/crates/wit-component/tests/interfaces.rs @@ -30,7 +30,7 @@ fn main() -> Result<()> { }; let is_dir = path.is_dir(); let is_test = is_dir || name.ends_with(".wit"); - if cfg!(feature = "canon-names") != name.starts_with("canon-names-") { + if name.starts_with("canon-names-") { continue; } if is_test { @@ -49,6 +49,17 @@ fn main() -> Result<()> { libtest_mimic::run(&args, trials).exit(); } +fn canon_names_path(path: &Path, ext: &str) -> std::path::PathBuf { + if cfg!(feature = "canon-names") { + let canon_ext = format!("canon-names.{ext}"); + let canon_path = path.with_extension(&canon_ext); + if std::env::var_os("BLESS").is_some() || canon_path.exists() { + return canon_path; + } + } + path.with_extension(ext) +} + fn run_test(path: &Path, is_dir: bool) -> Result<()> { let mut resolve = Resolve::new(); let package = if is_dir { @@ -64,7 +75,7 @@ fn run_test(path: &Path, is_dir: bool) -> Result<()> { // expectation. let wasm = wit_component::encode(&resolve, package)?; let wat = wasmprinter::print_bytes(&wasm)?; - assert_output(&path.with_extension("wat"), &wat)?; + assert_output(&canon_names_path(path, "wat"), &wat)?; wasmparser::Validator::new_with_features(WasmFeatures::all()) .validate_all(&wasm) .context("failed to validate wasm output")?; @@ -95,9 +106,19 @@ fn assert_print(resolve: &Resolve, pkg_id: PackageId, path: &Path, is_dir: bool) let output = printer.output.to_string(); let pkg = &resolve.packages[pkg_id]; let expected = if is_dir { - path.join(format!("{}.wit.print", &pkg.name.name)) + let base = path.join(format!("{}.wit.print", &pkg.name.name)); + if cfg!(feature = "canon-names") { + let canon = path.join(format!("{}.canon-names.wit.print", &pkg.name.name)); + if std::env::var_os("BLESS").is_some() || canon.exists() { + canon + } else { + base + } + } else { + base + } } else { - path.with_extension("wit.print") + canon_names_path(path, "wit.print") }; assert_output(&expected, &output)?; diff --git a/crates/wit-component/tests/interfaces/canon-names-merge.wat b/crates/wit-component/tests/interfaces/canon-names-merge.wat deleted file mode 100644 index 53265b6c7d..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-merge.wat +++ /dev/null @@ -1,27 +0,0 @@ -(component - (type (;0;) - (component - (type (;0;) - (component - (type (;0;) - (instance - (type (;0;) u32) - (export (;1;) "my-type" (type (eq 0))) - (type (;2;) (func (result 1))) - (export (;0;) "my-func" (func (type 2))) - (type (;3;) (func (param "x" 1) (result string))) - (export (;1;) "added-func" (func (type 3))) - ) - ) - (import "test:lib/types@1" (versionsuffix ".2.0") (instance (;0;) (type 0))) - ) - ) - (export (;0;) "test:app/my-world@1.0.0" (component (type 0))) - ) - ) - (export (;1;) "my-world" (type 0)) - (@custom "package-docs" "\01{}") - (@producers - (processed-by "wit-component" "$CARGO_PKG_VERSION") - ) -) diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/app.wit b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit deleted file mode 100644 index 11c930f5eb..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-merge/app.wit +++ /dev/null @@ -1,5 +0,0 @@ -package test:app@1.0.0; - -world my-world { - import test:lib/types@1.2.0; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print deleted file mode 100644 index 3d8b6b204e..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-merge/app.wit.print +++ /dev/null @@ -1,5 +0,0 @@ -package test:app@1.0.0; - -world my-world { - import test:lib/types@1.2.0; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit deleted file mode 100644 index e7d5c0e8d3..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit +++ /dev/null @@ -1,6 +0,0 @@ -package test:lib@1.0.0; - -interface types { - type my-type = u32; - my-func: func() -> my-type; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit deleted file mode 100644 index d0945528cf..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit +++ /dev/null @@ -1,7 +0,0 @@ -package test:lib@1.2.0; - -interface types { - type my-type = u32; - my-func: func() -> my-type; - added-func: func(x: my-type) -> string; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit deleted file mode 100644 index cc82ae5dc5..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/command.wit +++ /dev/null @@ -1,7 +0,0 @@ -package wasi:cli@0.2.0-rc-2023-12-05; - -world command { - include imports; - - export run; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit deleted file mode 100644 index 70065233e8..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/environment.wit +++ /dev/null @@ -1,18 +0,0 @@ -interface environment { - /// Get the POSIX-style environment variables. - /// - /// Each environment variable is provided as a pair of string variable names - /// and string value. - /// - /// Morally, these are a value import, but until value imports are available - /// in the component model, this import function should return the same - /// values each time it is called. - get-environment: func() -> list>; - - /// Get the POSIX-style arguments to the program. - get-arguments: func() -> list; - - /// Return a path that programs should use as their initial current working - /// directory, interpreting `.` as shorthand for this. - initial-cwd: func() -> option; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit deleted file mode 100644 index d0c2b82ae2..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/exit.wit +++ /dev/null @@ -1,4 +0,0 @@ -interface exit { - /// Exit the current instance and any linked instances. - exit: func(status: result); -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit deleted file mode 100644 index 9965ea35ec..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/imports.wit +++ /dev/null @@ -1,20 +0,0 @@ -package wasi:cli@0.2.0-rc-2023-12-05; - -world imports { - include wasi:clocks/imports@0.2.0-rc-2023-11-10; - include wasi:filesystem/imports@0.2.0-rc-2023-11-10; - include wasi:sockets/imports@0.2.0-rc-2023-11-10; - include wasi:random/imports@0.2.0-rc-2023-11-10; - include wasi:io/imports@0.2.0-rc-2023-11-10; - - import environment; - import exit; - import stdin; - import stdout; - import stderr; - import terminal-input; - import terminal-output; - import terminal-stdin; - import terminal-stdout; - import terminal-stderr; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit deleted file mode 100644 index a70ee8c038..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/run.wit +++ /dev/null @@ -1,4 +0,0 @@ -interface run { - /// Run the program. - run: func() -> result; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit deleted file mode 100644 index 1b653b6e2d..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/stdio.wit +++ /dev/null @@ -1,17 +0,0 @@ -interface stdin { - use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream}; - - get-stdin: func() -> input-stream; -} - -interface stdout { - use wasi:io/streams@0.2.0-rc-2023-11-10.{output-stream}; - - get-stdout: func() -> output-stream; -} - -interface stderr { - use wasi:io/streams@0.2.0-rc-2023-11-10.{output-stream}; - - get-stderr: func() -> output-stream; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit deleted file mode 100644 index 47495769b3..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/cli/terminal.wit +++ /dev/null @@ -1,47 +0,0 @@ -interface terminal-input { - /// The input side of a terminal. - resource terminal-input; - - // In the future, this may include functions for disabling echoing, - // disabling input buffering so that keyboard events are sent through - // immediately, querying supported features, and so on. -} - -interface terminal-output { - /// The output side of a terminal. - resource terminal-output; - - // In the future, this may include functions for querying the terminal - // size, being notified of terminal size changes, querying supported - // features, and so on. -} - -/// An interface providing an optional `terminal-input` for stdin as a -/// link-time authority. -interface terminal-stdin { - use terminal-input.{terminal-input}; - - /// If stdin is connected to a terminal, return a `terminal-input` handle - /// allowing further interaction with it. - get-terminal-stdin: func() -> option; -} - -/// An interface providing an optional `terminal-output` for stdout as a -/// link-time authority. -interface terminal-stdout { - use terminal-output.{terminal-output}; - - /// If stdout is connected to a terminal, return a `terminal-output` handle - /// allowing further interaction with it. - get-terminal-stdout: func() -> option; -} - -/// An interface providing an optional `terminal-output` for stderr as a -/// link-time authority. -interface terminal-stderr { - use terminal-output.{terminal-output}; - - /// If stderr is connected to a terminal, return a `terminal-output` handle - /// allowing further interaction with it. - get-terminal-stderr: func() -> option; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit deleted file mode 100644 index fdd54f566c..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/monotonic-clock.wit +++ /dev/null @@ -1,45 +0,0 @@ -package wasi:clocks@0.2.0-rc-2023-11-10; -/// WASI Monotonic Clock is a clock API intended to let users measure elapsed -/// time. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -/// -/// A monotonic clock is a clock which has an unspecified initial value, and -/// successive reads of the clock will produce non-decreasing values. -/// -/// It is intended for measuring elapsed time. -interface monotonic-clock { - use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; - - /// An instant in time, in nanoseconds. An instant is relative to an - /// unspecified initial value, and can only be compared to instances from - /// the same monotonic-clock. - type instant = u64; - - /// A duration of time, in nanoseconds. - type duration = u64; - - /// Read the current value of the clock. - /// - /// The clock is monotonic, therefore calling this function repeatedly will - /// produce a sequence of non-decreasing values. - now: func() -> instant; - - /// Query the resolution of the clock. Returns the duration of time - /// corresponding to a clock tick. - resolution: func() -> duration; - - /// Create a `pollable` which will resolve once the specified instant - /// occurred. - subscribe-instant: func( - when: instant, - ) -> pollable; - - /// Create a `pollable` which will resolve once the given duration has - /// elapsed, starting at the time at which this function was called. - /// occurred. - subscribe-duration: func( - when: duration, - ) -> pollable; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit deleted file mode 100644 index 8abb9a0c0e..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/wall-clock.wit +++ /dev/null @@ -1,42 +0,0 @@ -package wasi:clocks@0.2.0-rc-2023-11-10; -/// WASI Wall Clock is a clock API intended to let users query the current -/// time. The name "wall" makes an analogy to a "clock on the wall", which -/// is not necessarily monotonic as it may be reset. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -/// -/// A wall clock is a clock which measures the date and time according to -/// some external reference. -/// -/// External references may be reset, so this clock is not necessarily -/// monotonic, making it unsuitable for measuring elapsed time. -/// -/// It is intended for reporting the current date and time for humans. -interface wall-clock { - /// A time and date in seconds plus nanoseconds. - record datetime { - seconds: u64, - nanoseconds: u32, - } - - /// Read the current value of the clock. - /// - /// This clock is not monotonic, therefore calling this function repeatedly - /// will not necessarily produce a sequence of non-decreasing values. - /// - /// The returned timestamps represent the number of seconds since - /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], - /// also known as [Unix Time]. - /// - /// The nanoseconds field of the output is always less than 1000000000. - /// - /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 - /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time - now: func() -> datetime; - - /// Query the resolution of the clock. - /// - /// The nanoseconds field of the output is always less than 1000000000. - resolution: func() -> datetime; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit deleted file mode 100644 index 8fa080f0e2..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/clocks/world.wit +++ /dev/null @@ -1,6 +0,0 @@ -package wasi:clocks@0.2.0-rc-2023-11-10; - -world imports { - import monotonic-clock; - import wall-clock; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit deleted file mode 100644 index 95ec678434..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/preopens.wit +++ /dev/null @@ -1,8 +0,0 @@ -package wasi:filesystem@0.2.0-rc-2023-11-10; - -interface preopens { - use types.{descriptor}; - - /// Return the set of preopened directories, and their path. - get-directories: func() -> list>; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit deleted file mode 100644 index 16067ad68c..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/types.wit +++ /dev/null @@ -1,634 +0,0 @@ -package wasi:filesystem@0.2.0-rc-2023-11-10; -/// WASI filesystem is a filesystem API primarily intended to let users run WASI -/// programs that access their files on their existing filesystems, without -/// significant overhead. -/// -/// It is intended to be roughly portable between Unix-family platforms and -/// Windows, though it does not hide many of the major differences. -/// -/// Paths are passed as interface-type `string`s, meaning they must consist of -/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain -/// paths which are not accessible by this API. -/// -/// The directory separator in WASI is always the forward-slash (`/`). -/// -/// All paths in WASI are relative paths, and are interpreted relative to a -/// `descriptor` referring to a base directory. If a `path` argument to any WASI -/// function starts with `/`, or if any step of resolving a `path`, including -/// `..` and symbolic link steps, reaches a directory outside of the base -/// directory, or reaches a symlink to an absolute or rooted path in the -/// underlying filesystem, the function fails with `error-code::not-permitted`. -/// -/// For more information about WASI path resolution and sandboxing, see -/// [WASI filesystem path resolution]. -/// -/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md -interface types { - use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream, output-stream, error}; - use wasi:clocks/wall-clock@0.2.0-rc-2023-11-10.{datetime}; - - /// File size or length of a region within a file. - type filesize = u64; - - /// The type of a filesystem object referenced by a descriptor. - /// - /// Note: This was called `filetype` in earlier versions of WASI. - enum descriptor-type { - /// The type of the descriptor or file is unknown or is different from - /// any of the other types specified. - unknown, - /// The descriptor refers to a block device inode. - block-device, - /// The descriptor refers to a character device inode. - character-device, - /// The descriptor refers to a directory inode. - directory, - /// The descriptor refers to a named pipe. - fifo, - /// The file refers to a symbolic link inode. - symbolic-link, - /// The descriptor refers to a regular file inode. - regular-file, - /// The descriptor refers to a socket. - socket, - } - - /// Descriptor flags. - /// - /// Note: This was called `fdflags` in earlier versions of WASI. - flags descriptor-flags { - /// Read mode: Data can be read. - read, - /// Write mode: Data can be written to. - write, - /// Request that writes be performed according to synchronized I/O file - /// integrity completion. The data stored in the file and the file's - /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - file-integrity-sync, - /// Request that writes be performed according to synchronized I/O data - /// integrity completion. Only the data stored in the file is - /// synchronized. This is similar to `O_DSYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - data-integrity-sync, - /// Requests that reads be performed at the same level of integrity - /// requested for writes. This is similar to `O_RSYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - requested-write-sync, - /// Mutating directories mode: Directory contents may be mutated. - /// - /// When this flag is unset on a descriptor, operations using the - /// descriptor which would create, rename, delete, modify the data or - /// metadata of filesystem objects, or obtain another handle which - /// would permit any of those, shall fail with `error-code::read-only` if - /// they would otherwise succeed. - /// - /// This may only be set on directories. - mutate-directory, - } - - /// File attributes. - /// - /// Note: This was called `filestat` in earlier versions of WASI. - record descriptor-stat { - /// File type. - %type: descriptor-type, - /// Number of hard links to the file. - link-count: link-count, - /// For regular files, the file size in bytes. For symbolic links, the - /// length in bytes of the pathname contained in the symbolic link. - size: filesize, - /// Last data access timestamp. - /// - /// If the `option` is none, the platform doesn't maintain an access - /// timestamp for this file. - data-access-timestamp: option, - /// Last data modification timestamp. - /// - /// If the `option` is none, the platform doesn't maintain a - /// modification timestamp for this file. - data-modification-timestamp: option, - /// Last file status-change timestamp. - /// - /// If the `option` is none, the platform doesn't maintain a - /// status-change timestamp for this file. - status-change-timestamp: option, - } - - /// Flags determining the method of how paths are resolved. - flags path-flags { - /// As long as the resolved path corresponds to a symbolic link, it is - /// expanded. - symlink-follow, - } - - /// Open flags used by `open-at`. - flags open-flags { - /// Create file if it does not exist, similar to `O_CREAT` in POSIX. - create, - /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. - directory, - /// Fail if file already exists, similar to `O_EXCL` in POSIX. - exclusive, - /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. - truncate, - } - - /// Number of hard links to an inode. - type link-count = u64; - - /// When setting a timestamp, this gives the value to set it to. - variant new-timestamp { - /// Leave the timestamp set to its previous value. - no-change, - /// Set the timestamp to the current time of the system clock associated - /// with the filesystem. - now, - /// Set the timestamp to the given value. - timestamp(datetime), - } - - /// A directory entry. - record directory-entry { - /// The type of the file referred to by this directory entry. - %type: descriptor-type, - - /// The name of the object. - name: string, - } - - /// Error codes returned by functions, similar to `errno` in POSIX. - /// Not all of these error codes are returned by the functions provided by this - /// API; some are used in higher-level library layers, and others are provided - /// merely for alignment with POSIX. - enum error-code { - /// Permission denied, similar to `EACCES` in POSIX. - access, - /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. - would-block, - /// Connection already in progress, similar to `EALREADY` in POSIX. - already, - /// Bad descriptor, similar to `EBADF` in POSIX. - bad-descriptor, - /// Device or resource busy, similar to `EBUSY` in POSIX. - busy, - /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. - deadlock, - /// Storage quota exceeded, similar to `EDQUOT` in POSIX. - quota, - /// File exists, similar to `EEXIST` in POSIX. - exist, - /// File too large, similar to `EFBIG` in POSIX. - file-too-large, - /// Illegal byte sequence, similar to `EILSEQ` in POSIX. - illegal-byte-sequence, - /// Operation in progress, similar to `EINPROGRESS` in POSIX. - in-progress, - /// Interrupted function, similar to `EINTR` in POSIX. - interrupted, - /// Invalid argument, similar to `EINVAL` in POSIX. - invalid, - /// I/O error, similar to `EIO` in POSIX. - io, - /// Is a directory, similar to `EISDIR` in POSIX. - is-directory, - /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. - loop, - /// Too many links, similar to `EMLINK` in POSIX. - too-many-links, - /// Message too large, similar to `EMSGSIZE` in POSIX. - message-size, - /// Filename too long, similar to `ENAMETOOLONG` in POSIX. - name-too-long, - /// No such device, similar to `ENODEV` in POSIX. - no-device, - /// No such file or directory, similar to `ENOENT` in POSIX. - no-entry, - /// No locks available, similar to `ENOLCK` in POSIX. - no-lock, - /// Not enough space, similar to `ENOMEM` in POSIX. - insufficient-memory, - /// No space left on device, similar to `ENOSPC` in POSIX. - insufficient-space, - /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. - not-directory, - /// Directory not empty, similar to `ENOTEMPTY` in POSIX. - not-empty, - /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. - not-recoverable, - /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. - unsupported, - /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. - no-tty, - /// No such device or address, similar to `ENXIO` in POSIX. - no-such-device, - /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. - overflow, - /// Operation not permitted, similar to `EPERM` in POSIX. - not-permitted, - /// Broken pipe, similar to `EPIPE` in POSIX. - pipe, - /// Read-only file system, similar to `EROFS` in POSIX. - read-only, - /// Invalid seek, similar to `ESPIPE` in POSIX. - invalid-seek, - /// Text file busy, similar to `ETXTBSY` in POSIX. - text-file-busy, - /// Cross-device link, similar to `EXDEV` in POSIX. - cross-device, - } - - /// File or memory access pattern advisory information. - enum advice { - /// The application has no advice to give on its behavior with respect - /// to the specified data. - normal, - /// The application expects to access the specified data sequentially - /// from lower offsets to higher offsets. - sequential, - /// The application expects to access the specified data in a random - /// order. - random, - /// The application expects to access the specified data in the near - /// future. - will-need, - /// The application expects that it will not access the specified data - /// in the near future. - dont-need, - /// The application expects to access the specified data once and then - /// not reuse it thereafter. - no-reuse, - } - - /// A 128-bit hash value, split into parts because wasm doesn't have a - /// 128-bit integer type. - record metadata-hash-value { - /// 64 bits of a 128-bit hash value. - lower: u64, - /// Another 64 bits of a 128-bit hash value. - upper: u64, - } - - /// A descriptor is a reference to a filesystem object, which may be a file, - /// directory, named pipe, special file, or other object on which filesystem - /// calls may be made. - resource descriptor { - /// Return a stream for reading from a file, if available. - /// - /// May fail with an error-code describing why the file cannot be read. - /// - /// Multiple read, write, and append streams may be active on the same open - /// file and they do not interfere with each other. - /// - /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. - read-via-stream: func( - /// The offset within the file at which to start reading. - offset: filesize, - ) -> result; - - /// Return a stream for writing to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be written. - /// - /// Note: This allows using `write-stream`, which is similar to `write` in - /// POSIX. - write-via-stream: func( - /// The offset within the file at which to start writing. - offset: filesize, - ) -> result; - - /// Return a stream for appending to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be appended. - /// - /// Note: This allows using `write-stream`, which is similar to `write` with - /// `O_APPEND` in in POSIX. - append-via-stream: func() -> result; - - /// Provide file advisory information on a descriptor. - /// - /// This is similar to `posix_fadvise` in POSIX. - advise: func( - /// The offset within the file to which the advisory applies. - offset: filesize, - /// The length of the region to which the advisory applies. - length: filesize, - /// The advice. - advice: advice - ) -> result<_, error-code>; - - /// Synchronize the data of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fdatasync` in POSIX. - sync-data: func() -> result<_, error-code>; - - /// Get flags associated with a descriptor. - /// - /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. - /// - /// Note: This returns the value that was the `fs_flags` value returned - /// from `fdstat_get` in earlier versions of WASI. - get-flags: func() -> result; - - /// Get the dynamic type of a descriptor. - /// - /// Note: This returns the same value as the `type` field of the `fd-stat` - /// returned by `stat`, `stat-at` and similar. - /// - /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided - /// by `fstat` in POSIX. - /// - /// Note: This returns the value that was the `fs_filetype` value returned - /// from `fdstat_get` in earlier versions of WASI. - get-type: func() -> result; - - /// Adjust the size of an open file. If this increases the file's size, the - /// extra bytes are filled with zeros. - /// - /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. - set-size: func(size: filesize) -> result<_, error-code>; - - /// Adjust the timestamps of an open file or directory. - /// - /// Note: This is similar to `futimens` in POSIX. - /// - /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. - set-times: func( - /// The desired values of the data access timestamp. - data-access-timestamp: new-timestamp, - /// The desired values of the data modification timestamp. - data-modification-timestamp: new-timestamp, - ) -> result<_, error-code>; - - /// Read from a descriptor, without using and updating the descriptor's offset. - /// - /// This function returns a list of bytes containing the data that was - /// read, along with a bool which, when true, indicates that the end of the - /// file was reached. The returned list will contain up to `length` bytes; it - /// may return fewer than requested, if the end of the file is reached or - /// if the I/O operation is interrupted. - /// - /// In the future, this may change to return a `stream`. - /// - /// Note: This is similar to `pread` in POSIX. - read: func( - /// The maximum number of bytes to read. - length: filesize, - /// The offset within the file at which to read. - offset: filesize, - ) -> result, bool>, error-code>; - - /// Write to a descriptor, without using and updating the descriptor's offset. - /// - /// It is valid to write past the end of a file; the file is extended to the - /// extent of the write, with bytes between the previous end and the start of - /// the write set to zero. - /// - /// In the future, this may change to take a `stream`. - /// - /// Note: This is similar to `pwrite` in POSIX. - write: func( - /// Data to write - buffer: list, - /// The offset within the file at which to write. - offset: filesize, - ) -> result; - - /// Read directory entries from a directory. - /// - /// On filesystems where directories contain entries referring to themselves - /// and their parents, often named `.` and `..` respectively, these entries - /// are omitted. - /// - /// This always returns a new stream which starts at the beginning of the - /// directory. Multiple streams may be active on the same directory, and they - /// do not interfere with each other. - read-directory: func() -> result; - - /// Synchronize the data and metadata of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fsync` in POSIX. - sync: func() -> result<_, error-code>; - - /// Create a directory. - /// - /// Note: This is similar to `mkdirat` in POSIX. - create-directory-at: func( - /// The relative path at which to create the directory. - path: string, - ) -> result<_, error-code>; - - /// Return the attributes of an open file or directory. - /// - /// Note: This is similar to `fstat` in POSIX, except that it does not return - /// device and inode information. For testing whether two descriptors refer to - /// the same underlying filesystem object, use `is-same-object`. To obtain - /// additional data that can be used do determine whether a file has been - /// modified, use `metadata-hash`. - /// - /// Note: This was called `fd_filestat_get` in earlier versions of WASI. - stat: func() -> result; - - /// Return the attributes of a file or directory. - /// - /// Note: This is similar to `fstatat` in POSIX, except that it does not - /// return device and inode information. See the `stat` description for a - /// discussion of alternatives. - /// - /// Note: This was called `path_filestat_get` in earlier versions of WASI. - stat-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the file or directory to inspect. - path: string, - ) -> result; - - /// Adjust the timestamps of a file or directory. - /// - /// Note: This is similar to `utimensat` in POSIX. - /// - /// Note: This was called `path_filestat_set_times` in earlier versions of - /// WASI. - set-times-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the file or directory to operate on. - path: string, - /// The desired values of the data access timestamp. - data-access-timestamp: new-timestamp, - /// The desired values of the data modification timestamp. - data-modification-timestamp: new-timestamp, - ) -> result<_, error-code>; - - /// Create a hard link. - /// - /// Note: This is similar to `linkat` in POSIX. - link-at: func( - /// Flags determining the method of how the path is resolved. - old-path-flags: path-flags, - /// The relative source path from which to link. - old-path: string, - /// The base directory for `new-path`. - new-descriptor: borrow, - /// The relative destination path at which to create the hard link. - new-path: string, - ) -> result<_, error-code>; - - /// Open a file or directory. - /// - /// The returned descriptor is not guaranteed to be the lowest-numbered - /// descriptor not currently open/ it is randomized to prevent applications - /// from depending on making assumptions about indexes, since this is - /// error-prone in multi-threaded contexts. The returned descriptor is - /// guaranteed to be less than 2**31. - /// - /// If `flags` contains `descriptor-flags::mutate-directory`, and the base - /// descriptor doesn't have `descriptor-flags::mutate-directory` set, - /// `open-at` fails with `error-code::read-only`. - /// - /// If `flags` contains `write` or `mutate-directory`, or `open-flags` - /// contains `truncate` or `create`, and the base descriptor doesn't have - /// `descriptor-flags::mutate-directory` set, `open-at` fails with - /// `error-code::read-only`. - /// - /// Note: This is similar to `openat` in POSIX. - open-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the object to open. - path: string, - /// The method by which to open the file. - open-flags: open-flags, - /// Flags to use for the resulting descriptor. - %flags: descriptor-flags, - ) -> result; - - /// Read the contents of a symbolic link. - /// - /// If the contents contain an absolute or rooted path in the underlying - /// filesystem, this function fails with `error-code::not-permitted`. - /// - /// Note: This is similar to `readlinkat` in POSIX. - readlink-at: func( - /// The relative path of the symbolic link from which to read. - path: string, - ) -> result; - - /// Remove a directory. - /// - /// Return `error-code::not-empty` if the directory is not empty. - /// - /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - remove-directory-at: func( - /// The relative path to a directory to remove. - path: string, - ) -> result<_, error-code>; - - /// Rename a filesystem object. - /// - /// Note: This is similar to `renameat` in POSIX. - rename-at: func( - /// The relative source path of the file or directory to rename. - old-path: string, - /// The base directory for `new-path`. - new-descriptor: borrow, - /// The relative destination path to which to rename the file or directory. - new-path: string, - ) -> result<_, error-code>; - - /// Create a symbolic link (also known as a "symlink"). - /// - /// If `old-path` starts with `/`, the function fails with - /// `error-code::not-permitted`. - /// - /// Note: This is similar to `symlinkat` in POSIX. - symlink-at: func( - /// The contents of the symbolic link. - old-path: string, - /// The relative destination path at which to create the symbolic link. - new-path: string, - ) -> result<_, error-code>; - - /// Unlink a filesystem object that is not a directory. - /// - /// Return `error-code::is-directory` if the path refers to a directory. - /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. - unlink-file-at: func( - /// The relative path to a file to unlink. - path: string, - ) -> result<_, error-code>; - - /// Test whether two descriptors refer to the same filesystem object. - /// - /// In POSIX, this corresponds to testing whether the two descriptors have the - /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. - /// wasi-filesystem does not expose device and inode numbers, so this function - /// may be used instead. - is-same-object: func(other: borrow) -> bool; - - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a descriptor. - /// - /// This returns a hash of the last-modification timestamp and file size, and - /// may also include the inode number, device number, birth timestamp, and - /// other metadata fields that may change when the file is modified or - /// replaced. It may also include a secret value chosen by the - /// implementation and not otherwise exposed. - /// - /// Implementations are encourated to provide the following properties: - /// - /// - If the file is not modified or replaced, the computed hash value should - /// usually not change. - /// - If the object is modified or replaced, the computed hash value should - /// usually change. - /// - The inputs to the hash should not be easily computable from the - /// computed hash. - /// - /// However, none of these is required. - metadata-hash: func() -> result; - - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a directory descriptor and a relative path. - /// - /// This performs the same hash computation as `metadata-hash`. - metadata-hash-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the file or directory to inspect. - path: string, - ) -> result; - } - - /// A stream of directory entries. - resource directory-entry-stream { - /// Read a single directory entry from a `directory-entry-stream`. - read-directory-entry: func() -> result, error-code>; - } - - /// Attempts to extract a filesystem-related `error-code` from the stream - /// `error` provided. - /// - /// Stream operations which return `stream-error::last-operation-failed` - /// have a payload with more information about the operation that failed. - /// This payload can be passed through to this function to see if there's - /// filesystem-related information about the error to return. - /// - /// Note that this function is fallible because not all stream-related - /// errors are filesystem-related errors. - filesystem-error-code: func(err: borrow) -> option; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit deleted file mode 100644 index 285e0bae9e..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/filesystem/world.wit +++ /dev/null @@ -1,6 +0,0 @@ -package wasi:filesystem@0.2.0-rc-2023-11-10; - -world imports { - import types; - import preopens; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit deleted file mode 100644 index 31918acbb4..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/error.wit +++ /dev/null @@ -1,34 +0,0 @@ -package wasi:io@0.2.0-rc-2023-11-10; - - -interface error { - /// A resource which represents some error information. - /// - /// The only method provided by this resource is `to-debug-string`, - /// which provides some human-readable information about the error. - /// - /// In the `wasi:io` package, this resource is returned through the - /// `wasi:io/streams/stream-error` type. - /// - /// To provide more specific error information, other interfaces may - /// provide functions to further "downcast" this error into more specific - /// error information. For example, `error`s returned in streams derived - /// from filesystem types to be described using the filesystem's own - /// error-code type, using the function - /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter - /// `borrow` and returns - /// `option`. - /// - /// The set of functions which can "downcast" an `error` into a more - /// concrete type is open. - resource error { - /// Returns a string that is suitable to assist humans in debugging - /// this error. - /// - /// WARNING: The returned string should not be consumed mechanically! - /// It may change across platforms, hosts, or other implementation - /// details. Parsing this string is a major platform-compatibility - /// hazard. - to-debug-string: func() -> string; - } -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit deleted file mode 100644 index 81b1cab999..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/poll.wit +++ /dev/null @@ -1,41 +0,0 @@ -package wasi:io@0.2.0-rc-2023-11-10; - -/// A poll API intended to let users wait for I/O events on multiple handles -/// at once. -interface poll { - /// `pollable` represents a single I/O event which may be ready, or not. - resource pollable { - - /// Return the readiness of a pollable. This function never blocks. - /// - /// Returns `true` when the pollable is ready, and `false` otherwise. - ready: func() -> bool; - - /// `block` returns immediately if the pollable is ready, and otherwise - /// blocks until ready. - /// - /// This function is equivalent to calling `poll.poll` on a list - /// containing only this pollable. - block: func(); - } - - /// Poll for completion on a set of pollables. - /// - /// This function takes a list of pollables, which identify I/O sources of - /// interest, and waits until one or more of the events is ready for I/O. - /// - /// The result `list` contains one or more indices of handles in the - /// argument list that is ready for I/O. - /// - /// If the list contains more elements than can be indexed with a `u32` - /// value, this function traps. - /// - /// A timeout can be implemented by adding a pollable from the - /// wasi-clocks API to the list. - /// - /// This function does not return a `result`; polling in itself does not - /// do any I/O so it doesn't fail. If any of the I/O sources identified by - /// the pollables has an error, it is indicated by marking the source as - /// being reaedy for I/O. - poll: func(in: list>) -> list; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit deleted file mode 100644 index 1a7efa186c..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/streams.wit +++ /dev/null @@ -1,251 +0,0 @@ -package wasi:io@0.2.0-rc-2023-11-10; - -/// WASI I/O is an I/O abstraction API which is currently focused on providing -/// stream types. -/// -/// In the future, the component model is expected to add built-in stream types; -/// when it does, they are expected to subsume this API. -interface streams { - use error.{error}; - use poll.{pollable}; - - /// An error for input-stream and output-stream operations. - variant stream-error { - /// The last operation (a write or flush) failed before completion. - /// - /// More information is available in the `error` payload. - last-operation-failed(error), - /// The stream is closed: no more input will be accepted by the - /// stream. A closed output-stream will return this error on all - /// future operations. - closed - } - - /// An input bytestream. - /// - /// `input-stream`s are *non-blocking* to the extent practical on underlying - /// platforms. I/O operations always return promptly; if fewer bytes are - /// promptly available than requested, they return the number of bytes promptly - /// available, which could even be zero. To wait for data to be available, - /// use the `subscribe` function to obtain a `pollable` which can be polled - /// for using `wasi:io/poll`. - resource input-stream { - /// Perform a non-blocking read from the stream. - /// - /// This function returns a list of bytes containing the read data, - /// when successful. The returned list will contain up to `len` bytes; - /// it may return fewer than requested, but not more. The list is - /// empty when no bytes are available for reading at this time. The - /// pollable given by `subscribe` will be ready when more bytes are - /// available. - /// - /// This function fails with a `stream-error` when the operation - /// encounters an error, giving `last-operation-failed`, or when the - /// stream is closed, giving `closed`. - /// - /// When the caller gives a `len` of 0, it represents a request to - /// read 0 bytes. If the stream is still open, this call should - /// succeed and return an empty list, or otherwise fail with `closed`. - /// - /// The `len` parameter is a `u64`, which could represent a list of u8 which - /// is not possible to allocate in wasm32, or not desirable to allocate as - /// as a return value by the callee. The callee may return a list of bytes - /// less than `len` in size while more bytes are available for reading. - read: func( - /// The maximum number of bytes to read - len: u64 - ) -> result, stream-error>; - - /// Read bytes from a stream, after blocking until at least one byte can - /// be read. Except for blocking, behavior is identical to `read`. - blocking-read: func( - /// The maximum number of bytes to read - len: u64 - ) -> result, stream-error>; - - /// Skip bytes from a stream. Returns number of bytes skipped. - /// - /// Behaves identical to `read`, except instead of returning a list - /// of bytes, returns the number of bytes consumed from the stream. - skip: func( - /// The maximum number of bytes to skip. - len: u64, - ) -> result; - - /// Skip bytes from a stream, after blocking until at least one byte - /// can be skipped. Except for blocking behavior, identical to `skip`. - blocking-skip: func( - /// The maximum number of bytes to skip. - len: u64, - ) -> result; - - /// Create a `pollable` which will resolve once either the specified stream - /// has bytes available to read or the other end of the stream has been - /// closed. - /// The created `pollable` is a child resource of the `input-stream`. - /// Implementations may trap if the `input-stream` is dropped before - /// all derived `pollable`s created with this function are dropped. - subscribe: func() -> pollable; - } - - - /// An output bytestream. - /// - /// `output-stream`s are *non-blocking* to the extent practical on - /// underlying platforms. Except where specified otherwise, I/O operations also - /// always return promptly, after the number of bytes that can be written - /// promptly, which could even be zero. To wait for the stream to be ready to - /// accept data, the `subscribe` function to obtain a `pollable` which can be - /// polled for using `wasi:io/poll`. - resource output-stream { - /// Check readiness for writing. This function never blocks. - /// - /// Returns the number of bytes permitted for the next call to `write`, - /// or an error. Calling `write` with more bytes than this function has - /// permitted will trap. - /// - /// When this function returns 0 bytes, the `subscribe` pollable will - /// become ready when this function will report at least 1 byte, or an - /// error. - check-write: func() -> result; - - /// Perform a write. This function never blocks. - /// - /// Precondition: check-write gave permit of Ok(n) and contents has a - /// length of less than or equal to n. Otherwise, this function will trap. - /// - /// returns Err(closed) without writing if the stream has closed since - /// the last call to check-write provided a permit. - write: func( - contents: list - ) -> result<_, stream-error>; - - /// Perform a write of up to 4096 bytes, and then flush the stream. Block - /// until all of these operations are complete, or an error occurs. - /// - /// This is a convenience wrapper around the use of `check-write`, - /// `subscribe`, `write`, and `flush`, and is implemented with the - /// following pseudo-code: - /// - /// ```text - /// let pollable = this.subscribe(); - /// while !contents.is_empty() { - /// // Wait for the stream to become writable - /// pollable.block(); - /// let Ok(n) = this.check-write(); // eliding error handling - /// let len = min(n, contents.len()); - /// let (chunk, rest) = contents.split_at(len); - /// this.write(chunk ); // eliding error handling - /// contents = rest; - /// } - /// this.flush(); - /// // Wait for completion of `flush` - /// pollable.block(); - /// // Check for any errors that arose during `flush` - /// let _ = this.check-write(); // eliding error handling - /// ``` - blocking-write-and-flush: func( - contents: list - ) -> result<_, stream-error>; - - /// Request to flush buffered output. This function never blocks. - /// - /// This tells the output-stream that the caller intends any buffered - /// output to be flushed. the output which is expected to be flushed - /// is all that has been passed to `write` prior to this call. - /// - /// Upon calling this function, the `output-stream` will not accept any - /// writes (`check-write` will return `ok(0)`) until the flush has - /// completed. The `subscribe` pollable will become ready when the - /// flush has completed and the stream can accept more writes. - flush: func() -> result<_, stream-error>; - - /// Request to flush buffered output, and block until flush completes - /// and stream is ready for writing again. - blocking-flush: func() -> result<_, stream-error>; - - /// Create a `pollable` which will resolve once the output-stream - /// is ready for more writing, or an error has occurred. When this - /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an - /// error. - /// - /// If the stream is closed, this pollable is always ready immediately. - /// - /// The created `pollable` is a child resource of the `output-stream`. - /// Implementations may trap if the `output-stream` is dropped before - /// all derived `pollable`s created with this function are dropped. - subscribe: func() -> pollable; - - /// Write zeroes to a stream. - /// - /// This should be used precisely like `write` with the exact same - /// preconditions (must use check-write first), but instead of - /// passing a list of bytes, you simply pass the number of zero-bytes - /// that should be written. - write-zeroes: func( - /// The number of zero-bytes to write - len: u64 - ) -> result<_, stream-error>; - - /// Perform a write of up to 4096 zeroes, and then flush the stream. - /// Block until all of these operations are complete, or an error - /// occurs. - /// - /// This is a convenience wrapper around the use of `check-write`, - /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with - /// the following pseudo-code: - /// - /// ```text - /// let pollable = this.subscribe(); - /// while num_zeroes != 0 { - /// // Wait for the stream to become writable - /// pollable.block(); - /// let Ok(n) = this.check-write(); // eliding error handling - /// let len = min(n, num_zeroes); - /// this.write-zeroes(len); // eliding error handling - /// num_zeroes -= len; - /// } - /// this.flush(); - /// // Wait for completion of `flush` - /// pollable.block(); - /// // Check for any errors that arose during `flush` - /// let _ = this.check-write(); // eliding error handling - /// ``` - blocking-write-zeroes-and-flush: func( - /// The number of zero-bytes to write - len: u64 - ) -> result<_, stream-error>; - - /// Read from one stream and write to another. - /// - /// The behavior of splice is equivalent to: - /// 1. calling `check-write` on the `output-stream` - /// 2. calling `read` on the `input-stream` with the smaller of the - /// `check-write` permitted length and the `len` provided to `splice` - /// 3. calling `write` on the `output-stream` with that read data. - /// - /// Any error reported by the call to `check-write`, `read`, or - /// `write` ends the splice and reports that error. - /// - /// This function returns the number of bytes transferred; it may be less - /// than `len`. - splice: func( - /// The stream to read from - src: borrow, - /// The number of bytes to splice - len: u64, - ) -> result; - - /// Read from one stream and write to another, with blocking. - /// - /// This is similar to `splice`, except that it blocks until the - /// `output-stream` is ready for writing, and the `input-stream` - /// is ready for reading, before performing the `splice`. - blocking-splice: func( - /// The stream to read from - src: borrow, - /// The number of bytes to splice - len: u64, - ) -> result; - } -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit deleted file mode 100644 index 8243da2ee9..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/io/world.wit +++ /dev/null @@ -1,6 +0,0 @@ -package wasi:io@0.2.0-rc-2023-11-10; - -world imports { - import streams; - import poll; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit deleted file mode 100644 index f76e87dadc..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure-seed.wit +++ /dev/null @@ -1,25 +0,0 @@ -package wasi:random@0.2.0-rc-2023-11-10; -/// The insecure-seed interface for seeding hash-map DoS resistance. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -interface insecure-seed { - /// Return a 128-bit value that may contain a pseudo-random value. - /// - /// The returned value is not required to be computed from a CSPRNG, and may - /// even be entirely deterministic. Host implementations are encouraged to - /// provide pseudo-random values to any program exposed to - /// attacker-controlled content, to enable DoS protection built into many - /// languages' hash-map implementations. - /// - /// This function is intended to only be called once, by a source language - /// to initialize Denial Of Service (DoS) protection in its hash-map - /// implementation. - /// - /// # Expected future evolution - /// - /// This will likely be changed to a value import, to prevent it from being - /// called multiple times and potentially used for purposes other than DoS - /// protection. - insecure-seed: func() -> tuple; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit deleted file mode 100644 index ec7b997376..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/insecure.wit +++ /dev/null @@ -1,22 +0,0 @@ -package wasi:random@0.2.0-rc-2023-11-10; -/// The insecure interface for insecure pseudo-random numbers. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -interface insecure { - /// Return `len` insecure pseudo-random bytes. - /// - /// This function is not cryptographically secure. Do not use it for - /// anything related to security. - /// - /// There are no requirements on the values of the returned bytes, however - /// implementations are encouraged to return evenly distributed values with - /// a long period. - get-insecure-random-bytes: func(len: u64) -> list; - - /// Return an insecure pseudo-random `u64` value. - /// - /// This function returns the same type of pseudo-random data as - /// `get-insecure-random-bytes`, represented as a `u64`. - get-insecure-random-u64: func() -> u64; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit deleted file mode 100644 index 7a7dfa27a9..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/random.wit +++ /dev/null @@ -1,26 +0,0 @@ -package wasi:random@0.2.0-rc-2023-11-10; -/// WASI Random is a random data API. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -interface random { - /// Return `len` cryptographically-secure random or pseudo-random bytes. - /// - /// This function must produce data at least as cryptographically secure and - /// fast as an adequately seeded cryptographically-secure pseudo-random - /// number generator (CSPRNG). It must not block, from the perspective of - /// the calling program, under any circumstances, including on the first - /// request and on requests for numbers of bytes. The returned data must - /// always be unpredictable. - /// - /// This function must always return fresh data. Deterministic environments - /// must omit this function, rather than implementing it with deterministic - /// data. - get-random-bytes: func(len: u64) -> list; - - /// Return a cryptographically-secure random or pseudo-random `u64` value. - /// - /// This function returns the same type of data as `get-random-bytes`, - /// represented as a `u64`. - get-random-u64: func() -> u64; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit deleted file mode 100644 index 49e5743b4b..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/random/world.wit +++ /dev/null @@ -1,7 +0,0 @@ -package wasi:random@0.2.0-rc-2023-11-10; - -world imports { - import random; - import insecure; - import insecure-seed; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit deleted file mode 100644 index e455d0ff7b..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/instance-network.wit +++ /dev/null @@ -1,9 +0,0 @@ - -/// This interface provides a value-export of the default network handle.. -interface instance-network { - use network.{network}; - - /// Get a handle to the default network. - instance-network: func() -> network; - -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit deleted file mode 100644 index 931ccf7e05..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/ip-name-lookup.wit +++ /dev/null @@ -1,51 +0,0 @@ - -interface ip-name-lookup { - use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; - use network.{network, error-code, ip-address}; - - - /// Resolve an internet host name to a list of IP addresses. - /// - /// Unicode domain names are automatically converted to ASCII using IDNA encoding. - /// If the input is an IP address string, the address is parsed and returned - /// as-is without making any external requests. - /// - /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. - /// - /// This function never blocks. It either immediately fails or immediately - /// returns successfully with a `resolve-address-stream` that can be used - /// to (asynchronously) fetch the results. - /// - /// # Typical errors - /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. - /// - /// # References: - /// - - /// - - /// - - /// - - resolve-addresses: func(network: borrow, name: string) -> result; - - resource resolve-address-stream { - /// Returns the next address from the resolver. - /// - /// This function should be called multiple times. On each call, it will - /// return the next address in connection order preference. If all - /// addresses have been exhausted, this function returns `none`. - /// - /// This function never returns IPv4-mapped IPv6 addresses. - /// - /// # Typical errors - /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) - /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) - /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) - /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) - resolve-next-address: func() -> result, error-code>; - - /// Create a `pollable` which will resolve once the stream is ready for I/O. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit deleted file mode 100644 index 6bb07cd6fa..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/network.wit +++ /dev/null @@ -1,147 +0,0 @@ - -interface network { - /// An opaque resource that represents access to (a subset of) the network. - /// This enables context-based security for networking. - /// There is no need for this to map 1:1 to a physical network interface. - resource network; - - /// Error codes. - /// - /// In theory, every API can return any error code. - /// In practice, API's typically only return the errors documented per API - /// combined with a couple of errors that are always possible: - /// - `unknown` - /// - `access-denied` - /// - `not-supported` - /// - `out-of-memory` - /// - `concurrency-conflict` - /// - /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. - enum error-code { - // ### GENERAL ERRORS ### - - /// Unknown error - unknown, - - /// Access denied. - /// - /// POSIX equivalent: EACCES, EPERM - access-denied, - - /// The operation is not supported. - /// - /// POSIX equivalent: EOPNOTSUPP - not-supported, - - /// One of the arguments is invalid. - /// - /// POSIX equivalent: EINVAL - invalid-argument, - - /// Not enough memory to complete the operation. - /// - /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY - out-of-memory, - - /// The operation timed out before it could finish completely. - timeout, - - /// This operation is incompatible with another asynchronous operation that is already in progress. - /// - /// POSIX equivalent: EALREADY - concurrency-conflict, - - /// Trying to finish an asynchronous operation that: - /// - has not been started yet, or: - /// - was already finished by a previous `finish-*` call. - /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - not-in-progress, - - /// The operation has been aborted because it could not be completed immediately. - /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - would-block, - - - - // ### TCP & UDP SOCKET ERRORS ### - - /// The operation is not valid in the socket's current state. - invalid-state, - - /// A new socket resource could not be created because of a system limit. - new-socket-limit, - - /// A bind operation failed because the provided address is not an address that the `network` can bind to. - address-not-bindable, - - /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. - address-in-use, - - /// The remote address is not reachable - remote-unreachable, - - - // ### TCP SOCKET ERRORS ### - - /// The connection was forcefully rejected - connection-refused, - - /// The connection was reset. - connection-reset, - - /// A connection was aborted. - connection-aborted, - - - // ### UDP SOCKET ERRORS ### - datagram-too-large, - - - // ### NAME LOOKUP ERRORS ### - - /// Name does not exist or has no suitable associated IP addresses. - name-unresolvable, - - /// A temporary failure in name resolution occurred. - temporary-resolver-failure, - - /// A permanent failure in name resolution occurred. - permanent-resolver-failure, - } - - enum ip-address-family { - /// Similar to `AF_INET` in POSIX. - ipv4, - - /// Similar to `AF_INET6` in POSIX. - ipv6, - } - - type ipv4-address = tuple; - type ipv6-address = tuple; - - variant ip-address { - ipv4(ipv4-address), - ipv6(ipv6-address), - } - - record ipv4-socket-address { - port: u16, // sin_port - address: ipv4-address, // sin_addr - } - - record ipv6-socket-address { - port: u16, // sin6_port - flow-info: u32, // sin6_flowinfo - address: ipv6-address, // sin6_addr - scope-id: u32, // sin6_scope_id - } - - variant ip-socket-address { - ipv4(ipv4-socket-address), - ipv6(ipv6-socket-address), - } - -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit deleted file mode 100644 index 768a07c850..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp-create-socket.wit +++ /dev/null @@ -1,26 +0,0 @@ - -interface tcp-create-socket { - use network.{network, error-code, ip-address-family}; - use tcp.{tcp-socket}; - - /// Create a new TCP socket. - /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. - /// - /// This function does not require a network capability handle. This is considered to be safe because - /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`listen`/`connect` - /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. - /// - /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. - /// - /// # Typical errors - /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) - /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) - /// - /// # References - /// - - /// - - /// - - /// - - create-tcp-socket: func(address-family: ip-address-family) -> result; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit deleted file mode 100644 index b01b65e6c4..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/tcp.wit +++ /dev/null @@ -1,321 +0,0 @@ - -interface tcp { - use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream, output-stream}; - use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; - use wasi:clocks/monotonic-clock@0.2.0-rc-2023-11-10.{duration}; - use network.{network, error-code, ip-socket-address, ip-address-family}; - - enum shutdown-type { - /// Similar to `SHUT_RD` in POSIX. - receive, - - /// Similar to `SHUT_WR` in POSIX. - send, - - /// Similar to `SHUT_RDWR` in POSIX. - both, - } - - - /// A TCP socket handle. - resource tcp-socket { - /// Bind the socket to a specific network on the provided IP address and port. - /// - /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which - /// network interface(s) to bind to. - /// If the TCP/UDP port is zero, the socket will be bound to a random free port. - /// - /// When a socket is not explicitly bound, the first invocation to a listen or connect operation will - /// implicitly bind the socket. - /// - /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts. - /// - /// # Typical `start` errors - /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) - /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address, but the socket has `ipv6-only` enabled. (EINVAL) - /// - `invalid-state`: The socket is already bound. (EINVAL) - /// - /// # Typical `finish` errors - /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) - /// - `address-in-use`: Address is already in use. (EADDRINUSE) - /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) - /// - `not-in-progress`: A `bind` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # References - /// - - /// - - /// - - /// - - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - finish-bind: func() -> result<_, error-code>; - - /// Connect to a remote endpoint. - /// - /// On success: - /// - the socket is transitioned into the Connection state - /// - a pair of streams is returned that can be used to read & write to the connection - /// - /// POSIX mentions: - /// > If connect() fails, the state of the socket is unspecified. Conforming applications should - /// > close the file descriptor and create a new socket before attempting to reconnect. - /// - /// WASI prescribes the following behavior: - /// - If `connect` fails because an input/state validation error, the socket should remain usable. - /// - If a connection was actually attempted but failed, the socket should become unusable for further network communication. - /// Besides `drop`, any method after such a failure may return an error. - /// - /// # Typical `start` errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) - /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) - /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address, but the socket has `ipv6-only` enabled. (EINVAL, EADDRNOTAVAIL on Illumos) - /// - `invalid-argument`: `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) - /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. - /// - `invalid-state`: The socket is already in the Connection state. (EISCONN) - /// - `invalid-state`: The socket is already in the Listener state. (EOPNOTSUPP, EINVAL on Windows) - /// - /// # Typical `finish` errors - /// - `timeout`: Connection timed out. (ETIMEDOUT) - /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) - /// - `connection-reset`: The connection was reset. (ECONNRESET) - /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) - /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `not-in-progress`: A `connect` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # References - /// - - /// - - /// - - /// - - start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; - finish-connect: func() -> result, error-code>; - - /// Start listening for new connections. - /// - /// Transitions the socket into the Listener state. - /// - /// Unlike POSIX: - /// - this function is async. This enables interactive WASI hosts to inject permission prompts. - /// - the socket must already be explicitly bound. - /// - /// # Typical `start` errors - /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) - /// - `invalid-state`: The socket is already in the Connection state. (EISCONN, EINVAL on BSD) - /// - `invalid-state`: The socket is already in the Listener state. - /// - /// # Typical `finish` errors - /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) - /// - `not-in-progress`: A `listen` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # References - /// - - /// - - /// - - /// - - start-listen: func() -> result<_, error-code>; - finish-listen: func() -> result<_, error-code>; - - /// Accept a new client socket. - /// - /// The returned socket is bound and in the Connection state. The following properties are inherited from the listener socket: - /// - `address-family` - /// - `ipv6-only` - /// - `keep-alive-enabled` - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// - `hop-limit` - /// - `receive-buffer-size` - /// - `send-buffer-size` - /// - /// On success, this function returns the newly accepted client socket along with - /// a pair of streams that can be used to read & write to the connection. - /// - /// # Typical errors - /// - `invalid-state`: Socket is not in the Listener state. (EINVAL) - /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) - /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) - /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) - /// - /// # References - /// - - /// - - /// - - /// - - accept: func() -> result, error-code>; - - /// Get the bound local address. - /// - /// POSIX mentions: - /// > If the socket has not been bound to a local name, the value - /// > stored in the object pointed to by `address` is unspecified. - /// - /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. - /// - /// # References - /// - - /// - - /// - - /// - - local-address: func() -> result; - - /// Get the remote address. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - - /// Whether the socket is listening for new connections. - /// - /// Equivalent to the SO_ACCEPTCONN socket option. - is-listening: func() -> bool; - - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - address-family: func() -> ip-address-family; - - /// Whether IPv4 compatibility (dual-stack) mode is disabled or not. - /// - /// Equivalent to the IPV6_V6ONLY socket option. - /// - /// # Typical errors - /// - `invalid-state`: (set) The socket is already bound. - /// - `not-supported`: (get/set) `this` socket is an IPv4 socket. - /// - `not-supported`: (set) Host does not support dual-stack sockets. (Implementations are not required to.) - ipv6-only: func() -> result; - set-ipv6-only: func(value: bool) -> result<_, error-code>; - - /// Hints the desired listen queue size. Implementations are free to ignore this. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// - /// # Typical errors - /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. - /// - `invalid-argument`: (set) The provided value was 0. - /// - `invalid-state`: (set) The socket is already in the Connection state. - set-listen-backlog-size: func(value: u64) -> result<_, error-code>; - - /// Enables or disables keepalive. - /// - /// The keepalive behavior can be adjusted using: - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. - /// - /// Equivalent to the SO_KEEPALIVE socket option. - keep-alive-enabled: func() -> result; - set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; - - /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-idle-time: func() -> result; - set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; - - /// The time between keepalive packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the TCP_KEEPINTVL socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-interval: func() -> result; - set-keep-alive-interval: func(value: duration) -> result<_, error-code>; - - /// The maximum amount of keepalive packets TCP should send before aborting the connection. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the TCP_KEEPCNT socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-count: func() -> result; - set-keep-alive-count: func(value: u32) -> result<_, error-code>; - - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - /// - `invalid-state`: (set) The socket is already in the Connection state. - /// - `invalid-state`: (set) The socket is already in the Listener state. - hop-limit: func() -> result; - set-hop-limit: func(value: u8) -> result<_, error-code>; - - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - /// - `invalid-state`: (set) The socket is already in the Connection state. - /// - `invalid-state`: (set) The socket is already in the Listener state. - receive-buffer-size: func() -> result; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - send-buffer-size: func() -> result; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; - - /// Create a `pollable` which will resolve once the socket is ready for I/O. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - - /// Initiate a graceful shutdown. - /// - /// - receive: the socket is not expecting to receive any more data from the peer. All subsequent read - /// operations on the `input-stream` associated with this socket will return an End Of Stream indication. - /// Any data still in the receive queue at time of calling `shutdown` will be discarded. - /// - send: the socket is not expecting to send any more data to the peer. All subsequent write - /// operations on the `output-stream` associated with this socket will return an error. - /// - both: same effect as receive & send combined. - /// - /// The shutdown function does not close (drop) the socket. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not in the Connection state. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; - } -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit deleted file mode 100644 index cc58234d84..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp-create-socket.wit +++ /dev/null @@ -1,26 +0,0 @@ - -interface udp-create-socket { - use network.{network, error-code, ip-address-family}; - use udp.{udp-socket}; - - /// Create a new UDP socket. - /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. - /// - /// This function does not require a network capability handle. This is considered to be safe because - /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, - /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. - /// - /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. - /// - /// # Typical errors - /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) - /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) - /// - /// # References: - /// - - /// - - /// - - /// - - create-udp-socket: func(address-family: ip-address-family) -> result; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit deleted file mode 100644 index c8dafadfcb..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/udp.wit +++ /dev/null @@ -1,277 +0,0 @@ - -interface udp { - use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; - use network.{network, error-code, ip-socket-address, ip-address-family}; - - /// A received datagram. - record incoming-datagram { - /// The payload. - /// - /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. - data: list, - - /// The source address. - /// - /// This field is guaranteed to match the remote address the stream was initialized with, if any. - /// - /// Equivalent to the `src_addr` out parameter of `recvfrom`. - remote-address: ip-socket-address, - } - - /// A datagram to be sent out. - record outgoing-datagram { - /// The payload. - data: list, - - /// The destination address. - /// - /// The requirements on this field depend on how the stream was initialized: - /// - with a remote address: this field must be None or match the stream's remote address exactly. - /// - without a remote address: this field is required. - /// - /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. - remote-address: option, - } - - - - /// A UDP socket handle. - resource udp-socket { - /// Bind the socket to a specific network on the provided IP address and port. - /// - /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which - /// network interface(s) to bind to. - /// If the port is zero, the socket will be bound to a random free port. - /// - /// Unlike in POSIX, this function is async. This enables interactive WASI hosts to inject permission prompts. - /// - /// # Typical `start` errors - /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-state`: The socket is already bound. (EINVAL) - /// - /// # Typical `finish` errors - /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) - /// - `address-in-use`: Address is already in use. (EADDRINUSE) - /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) - /// - `not-in-progress`: A `bind` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # References - /// - - /// - - /// - - /// - - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - finish-bind: func() -> result<_, error-code>; - - /// Set up inbound & outbound communication channels, optionally to a specific peer. - /// - /// This function only changes the local socket configuration and does not generate any network traffic. - /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, - /// based on the best network path to `remote-address`. - /// - /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: - /// - `send` can only be used to send to this destination. - /// - `receive` will only return datagrams sent from the provided `remote-address`. - /// - /// This method may be called multiple times on the same socket to change its association, but - /// only the most recently returned pair of streams will be operational. Implementations may trap if - /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. - /// - /// The POSIX equivalent in pseudo-code is: - /// ```text - /// if (was previously connected) { - /// connect(s, AF_UNSPEC) - /// } - /// if (remote_address is Some) { - /// connect(s, remote_address) - /// } - /// ``` - /// - /// Unlike in POSIX, the socket must already be explicitly bound. - /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) - /// - `invalid-argument`: `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-state`: The socket is not bound. - /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - /// # References - /// - - /// - - /// - - /// - - %stream: func(remote-address: option) -> result, error-code>; - - /// Get the current bound address. - /// - /// POSIX mentions: - /// > If the socket has not been bound to a local name, the value - /// > stored in the object pointed to by `address` is unspecified. - /// - /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. - /// - /// # References - /// - - /// - - /// - - /// - - local-address: func() -> result; - - /// Get the address the socket is currently streaming to. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - address-family: func() -> ip-address-family; - - /// Whether IPv4 compatibility (dual-stack) mode is disabled or not. - /// - /// Equivalent to the IPV6_V6ONLY socket option. - /// - /// # Typical errors - /// - `not-supported`: (get/set) `this` socket is an IPv4 socket. - /// - `invalid-state`: (set) The socket is already bound. - /// - `not-supported`: (set) Host does not support dual-stack sockets. (Implementations are not required to.) - ipv6-only: func() -> result; - set-ipv6-only: func(value: bool) -> result<_, error-code>; - - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - unicast-hop-limit: func() -> result; - set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; - - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - receive-buffer-size: func() -> result; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - send-buffer-size: func() -> result; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; - - /// Create a `pollable` which will resolve once the socket is ready for I/O. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } - - resource incoming-datagram-stream { - /// Receive messages on the socket. - /// - /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. - /// The returned list may contain fewer elements than requested, but never more. - /// - /// This function returns successfully with an empty list when either: - /// - `max-results` is 0, or: - /// - `max-results` is greater than 0, but no results are immediately available. - /// This function never returns `error(would-block)`. - /// - /// # Typical errors - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - receive: func(max-results: u64) -> result, error-code>; - - /// Create a `pollable` which will resolve once the stream is ready to receive again. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } - - resource outgoing-datagram-stream { - /// Check readiness for sending. This function never blocks. - /// - /// Returns the number of datagrams permitted for the next call to `send`, - /// or an error. Calling `send` with more datagrams than this function has - /// permitted will trap. - /// - /// When this function returns ok(0), the `subscribe` pollable will - /// become ready when this function will report at least ok(1), or an - /// error. - /// - /// Never returns `would-block`. - check-send: func() -> result; - - /// Send messages on the socket. - /// - /// This function attempts to send all provided `datagrams` on the socket without blocking and - /// returns how many messages were actually sent (or queued for sending). This function never - /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. - /// - /// This function semantically behaves the same as iterating the `datagrams` list and sequentially - /// sending each individual datagram until either the end of the list has been reached or the first error occurred. - /// If at least one datagram has been sent successfully, this function never returns an error. - /// - /// If the input list is empty, the function returns `ok(0)`. - /// - /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if - /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. - /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) - /// - `invalid-argument`: `remote-address` is a non-IPv4-mapped IPv6 address, but the socket was bound to a specific IPv4-mapped IPv6 address. (or vice versa) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) - /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) - /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - send: func(datagrams: list) -> result; - - /// Create a `pollable` which will resolve once the stream is ready to send again. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit deleted file mode 100644 index 49ad8d3d9f..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/deps/sockets/world.wit +++ /dev/null @@ -1,11 +0,0 @@ -package wasi:sockets@0.2.0-rc-2023-11-10; - -world imports { - import instance-network; - import network; - import udp; - import udp-create-socket; - import tcp; - import tcp-create-socket; - import ip-name-lookup; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit deleted file mode 100644 index a34a0649d5..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/handler.wit +++ /dev/null @@ -1,43 +0,0 @@ -/// This interface defines a handler of incoming HTTP Requests. It should -/// be exported by components which can respond to HTTP Requests. -interface incoming-handler { - use types.{incoming-request, response-outparam}; - - /// This function is invoked with an incoming HTTP Request, and a resource - /// `response-outparam` which provides the capability to reply with an HTTP - /// Response. The response is sent by calling the `response-outparam.set` - /// method, which allows execution to continue after the response has been - /// sent. This enables both streaming to the response body, and performing other - /// work. - /// - /// The implementor of this function must write a response to the - /// `response-outparam` before returning, or else the caller will respond - /// with an error on its behalf. - handle: func( - request: incoming-request, - response-out: response-outparam - ); -} - -/// This interface defines a handler of outgoing HTTP Requests. It should be -/// imported by components which wish to make HTTP Requests. -interface outgoing-handler { - use types.{ - outgoing-request, request-options, future-incoming-response, error-code - }; - - /// This function is invoked with an outgoing HTTP Request, and it returns - /// a resource `future-incoming-response` which represents an HTTP Response - /// which may arrive in the future. - /// - /// The `options` argument accepts optional parameters for the HTTP - /// protocol's transport layer. - /// - /// This function may return an error if the `outgoing-request` is invalid - /// or not allowed to be made. Otherwise, protocol errors are reported - /// through the `future-incoming-response`. - handle: func( - request: outgoing-request, - options: option - ) -> result; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit deleted file mode 100644 index 0f466c93c1..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/proxy.wit +++ /dev/null @@ -1,32 +0,0 @@ -package wasi:http@0.2.0-rc-2023-12-05; - -/// The `wasi:http/proxy` world captures a widely-implementable intersection of -/// hosts that includes HTTP forward and reverse proxies. Components targeting -/// this world may concurrently stream in and out any number of incoming and -/// outgoing HTTP requests. -world proxy { - /// HTTP proxies have access to time and randomness. - include wasi:clocks/imports@0.2.0-rc-2023-11-10; - import wasi:random/random@0.2.0-rc-2023-11-10; - - /// Proxies have standard output and error streams which are expected to - /// terminate in a developer-facing console provided by the host. - import wasi:cli/stdout@0.2.0-rc-2023-12-05; - import wasi:cli/stderr@0.2.0-rc-2023-12-05; - - /// TODO: this is a temporary workaround until component tooling is able to - /// gracefully handle the absence of stdin. Hosts must return an eof stream - /// for this import, which is what wasi-libc + tooling will do automatically - /// when this import is properly removed. - import wasi:cli/stdin@0.2.0-rc-2023-12-05; - - /// This is the default handler to use when user code simply wants to make an - /// HTTP request (e.g., via `fetch()`). - import outgoing-handler; - - /// The host delivers incoming HTTP requests to a component by calling the - /// `handle` function of this exported interface. A host may arbitrarily reuse - /// or not reuse component instance when delivering incoming HTTP requests and - /// thus a component must be able to handle 0..N calls to `handle`. - export incoming-handler; -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit b/crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit deleted file mode 100644 index 06c3761665..0000000000 --- a/crates/wit-component/tests/interfaces/canon-names-wasi-http/types.wit +++ /dev/null @@ -1,570 +0,0 @@ -/// This interface defines all of the types and methods for implementing -/// HTTP Requests and Responses, both incoming and outgoing, as well as -/// their headers, trailers, and bodies. -interface types { - use wasi:clocks/monotonic-clock@0.2.0-rc-2023-11-10.{duration}; - use wasi:io/streams@0.2.0-rc-2023-11-10.{input-stream, output-stream}; - use wasi:io/error@0.2.0-rc-2023-11-10.{error as io-error}; - use wasi:io/poll@0.2.0-rc-2023-11-10.{pollable}; - - /// This type corresponds to HTTP standard Methods. - variant method { - get, - head, - post, - put, - delete, - connect, - options, - trace, - patch, - other(string) - } - - /// This type corresponds to HTTP standard Related Schemes. - variant scheme { - HTTP, - HTTPS, - other(string) - } - - /// These cases are inspired by the IANA HTTP Proxy Error Types: - /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types - variant error-code { - DNS-timeout, - DNS-error(DNS-error-payload), - destination-not-found, - destination-unavailable, - destination-IP-prohibited, - destination-IP-unroutable, - connection-refused, - connection-terminated, - connection-timeout, - connection-read-timeout, - connection-write-timeout, - connection-limit-reached, - TLS-protocol-error, - TLS-certificate-error, - TLS-alert-received(TLS-alert-received-payload), - HTTP-request-denied, - HTTP-request-length-required, - HTTP-request-body-size(option), - HTTP-request-method-invalid, - HTTP-request-URI-invalid, - HTTP-request-URI-too-long, - HTTP-request-header-section-size(option), - HTTP-request-header-size(option), - HTTP-request-trailer-section-size(option), - HTTP-request-trailer-size(field-size-payload), - HTTP-response-incomplete, - HTTP-response-header-section-size(option), - HTTP-response-header-size(field-size-payload), - HTTP-response-body-size(option), - HTTP-response-trailer-section-size(option), - HTTP-response-trailer-size(field-size-payload), - HTTP-response-transfer-coding(option), - HTTP-response-content-coding(option), - HTTP-response-timeout, - HTTP-upgrade-failed, - HTTP-protocol-error, - loop-detected, - configuration-error, - /// This is a catch-all error for anything that doesn't fit cleanly into a - /// more specific case. It also includes an optional string for an - /// unstructured description of the error. Users should not depend on the - /// string for diagnosing errors, as it's not required to be consistent - /// between implementations. - internal-error(option) - } - - /// Defines the case payload type for `DNS-error` above: - record DNS-error-payload { - rcode: option, - info-code: option - } - - /// Defines the case payload type for `TLS-alert-received` above: - record TLS-alert-received-payload { - alert-id: option, - alert-message: option - } - - /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: - record field-size-payload { - field-name: option, - field-size: option - } - - /// Attempts to extract a http-related `error` from the wasi:io `error` - /// provided. - /// - /// Stream operations which return - /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of - /// type `wasi:io/error/error` with more information about the operation - /// that failed. This payload can be passed through to this function to see - /// if there's http-related information about the error to return. - /// - /// Note that this function is fallible because not all io-errors are - /// http-related errors. - http-error-code: func(err: borrow) -> option; - - /// This type enumerates the different kinds of errors that may occur when - /// setting or appending to a `fields` resource. - variant header-error { - /// This error indicates that a `field-key` or `field-value` was - /// syntactically invalid when used with an operation that sets headers in a - /// `fields`. - invalid-syntax, - - /// This error indicates that a forbidden `field-key` was used when trying - /// to set a header in a `fields`. - forbidden, - - /// This error indicates that the operation on the `fields` was not - /// permitted because the fields are immutable. - immutable, - } - - /// Field keys are always strings. - type field-key = string; - - /// Field values should always be ASCII strings. However, in - /// reality, HTTP implementations often have to interpret malformed values, - /// so they are provided as a list of bytes. - type field-value = list; - - /// This following block defines the `fields` resource which corresponds to - /// HTTP standard Fields. Fields are a common representation used for both - /// Headers and Trailers. - /// - /// A `fields` may be mutable or immutable. A `fields` created using the - /// constructor, `from-list`, or `clone` will be mutable, but a `fields` - /// resource given by other means (including, but not limited to, - /// `incoming-request.headers`, `outgoing-request.headers`) might be be - /// immutable. In an immutable fields, the `set`, `append`, and `delete` - /// operations will fail with `header-error.immutable`. - resource fields { - - /// Construct an empty HTTP Fields. - /// - /// The resulting `fields` is mutable. - constructor(); - - /// Construct an HTTP Fields. - /// - /// The resulting `fields` is mutable. - /// - /// The list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - /// - /// The tuple is a pair of the field key, represented as a string, and - /// Value, represented as a list of bytes. In a valid Fields, all keys - /// and values are valid UTF-8 strings. However, values are not always - /// well-formed, so they are represented as a raw list of bytes. - /// - /// An error result will be returned if any header or value was - /// syntactically invalid, or if a header was forbidden. - from-list: static func( - entries: list> - ) -> result; - - /// Get all of the values corresponding to a key. If the key is not present - /// in this `fields`, an empty list is returned. However, if the key is - /// present but empty, this is represented by a list with one or more - /// empty field-values present. - get: func(name: field-key) -> list; - - /// Returns `true` when the key is present in this `fields`. If the key is - /// syntactically invalid, `false` is returned. - has: func(name: field-key) -> bool; - - /// Set all of the values for a key. Clears any existing values for that - /// key, if they have been set. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - set: func(name: field-key, value: list) -> result<_, header-error>; - - /// Delete all values for a key. Does nothing if no values for the key - /// exist. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - delete: func(name: field-key) -> result<_, header-error>; - - /// Append a value for a key. Does not change or delete any existing - /// values for that key. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - append: func(name: field-key, value: field-value) -> result<_, header-error>; - - /// Retrieve the full set of keys and values in the Fields. Like the - /// constructor, the list represents each key-value pair. - /// - /// The outer list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - entries: func() -> list>; - - /// Make a deep copy of the Fields. Equivalent in behavior to calling the - /// `fields` constructor on the return value of `entries`. The resulting - /// `fields` is mutable. - clone: func() -> fields; - } - - /// Headers is an alias for Fields. - type headers = fields; - - /// Trailers is an alias for Fields. - type trailers = fields; - - /// Represents an incoming HTTP Request. - resource incoming-request { - - /// Returns the method of the incoming request. - method: func() -> method; - - /// Returns the path with query parameters from the request, as a string. - path-with-query: func() -> option; - - /// Returns the protocol scheme from the request. - scheme: func() -> option; - - /// Returns the authority from the request, if it was present. - authority: func() -> option; - - /// Get the `headers` associated with the request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// The `headers` returned are a child resource: it must be dropped before - /// the parent `incoming-request` is dropped. Dropping this - /// `incoming-request` before all children are dropped will trap. - headers: func() -> headers; - - /// Gives the `incoming-body` associated with this request. Will only - /// return success at most once, and subsequent calls will return error. - consume: func() -> result; - } - - /// Represents an outgoing HTTP Request. - resource outgoing-request { - - /// Construct a new `outgoing-request` with a default `method` of `GET`, and - /// `none` values for `path-with-query`, `scheme`, and `authority`. - /// - /// * `headers` is the HTTP Headers for the Request. - /// - /// It is possible to construct, or manipulate with the accessor functions - /// below, an `outgoing-request` with an invalid combination of `scheme` - /// and `authority`, or `headers` which are not permitted to be sent. - /// It is the obligation of the `outgoing-handler.handle` implementation - /// to reject invalid constructions of `outgoing-request`. - constructor( - headers: headers - ); - - /// Returns the resource corresponding to the outgoing Body for this - /// Request. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-request` can be retrieved at most once. Subsequent - /// calls will return error. - body: func() -> result; - - /// Get the Method for the Request. - method: func() -> method; - /// Set the Method for the Request. Fails if the string present in a - /// `method.other` argument is not a syntactically valid method. - set-method: func(method: method) -> result; - - /// Get the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. - path-with-query: func() -> option; - /// Set the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. Fails is the - /// string given is not a syntactically valid path and query uri component. - set-path-with-query: func(path-with-query: option) -> result; - - /// Get the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. - scheme: func() -> option; - /// Set the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. Fails if the - /// string given is not a syntactically valid uri scheme. - set-scheme: func(scheme: option) -> result; - - /// Get the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. - authority: func() -> option; - /// Set the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. Fails if the string given is - /// not a syntactically valid uri authority. - set-authority: func(authority: option) -> result; - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transferred to - /// another component by e.g. `outgoing-handler.handle`. - headers: func() -> headers; - } - - /// Parameters for making an HTTP Request. Each of these parameters is - /// currently an optional timeout applicable to the transport layer of the - /// HTTP protocol. - /// - /// These timeouts are separate from any the user may use to bound a - /// blocking call to `wasi:io/poll.poll`. - resource request-options { - /// Construct a default `request-options` value. - constructor(); - - /// The timeout for the initial connect to the HTTP Server. - connect-timeout: func() -> option; - - /// Set the timeout for the initial connect to the HTTP Server. An error - /// return value indicates that this timeout is not supported. - set-connect-timeout: func(duration: option) -> result; - - /// The timeout for receiving the first byte of the Response body. - first-byte-timeout: func() -> option; - - /// Set the timeout for receiving the first byte of the Response body. An - /// error return value indicates that this timeout is not supported. - set-first-byte-timeout: func(duration: option) -> result; - - /// The timeout for receiving subsequent chunks of bytes in the Response - /// body stream. - between-bytes-timeout: func() -> option; - - /// Set the timeout for receiving subsequent chunks of bytes in the Response - /// body stream. An error return value indicates that this timeout is not - /// supported. - set-between-bytes-timeout: func(duration: option) -> result; - } - - /// Represents the ability to send an HTTP Response. - /// - /// This resource is used by the `wasi:http/incoming-handler` interface to - /// allow a Response to be sent corresponding to the Request provided as the - /// other argument to `incoming-handler.handle`. - resource response-outparam { - - /// Set the value of the `response-outparam` to either send a response, - /// or indicate an error. - /// - /// This method consumes the `response-outparam` to ensure that it is - /// called at most once. If it is never called, the implementation - /// will respond with an error. - /// - /// The user may provide an `error` to `response` to allow the - /// implementation determine how to respond with an HTTP error response. - set: static func( - param: response-outparam, - response: result, - ); - } - - /// This type corresponds to the HTTP standard Status Code. - type status-code = u16; - - /// Represents an incoming HTTP Response. - resource incoming-response { - - /// Returns the status code from the incoming response. - status: func() -> status-code; - - /// Returns the headers from the incoming response. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `incoming-response` is dropped. - headers: func() -> headers; - - /// Returns the incoming body. May be called at most once. Returns error - /// if called additional times. - consume: func() -> result; - } - - /// Represents an incoming HTTP Request or Response's Body. - /// - /// A body has both its contents - a stream of bytes - and a (possibly - /// empty) set of trailers, indicating that the full contents of the - /// body have been received. This resource represents the contents as - /// an `input-stream` and the delivery of trailers as a `future-trailers`, - /// and ensures that the user of this interface may only be consuming either - /// the body contents or waiting on trailers at any given time. - resource incoming-body { - - /// Returns the contents of the body, as a stream of bytes. - /// - /// Returns success on first call: the stream representing the contents - /// can be retrieved at most once. Subsequent calls will return error. - /// - /// The returned `input-stream` resource is a child: it must be dropped - /// before the parent `incoming-body` is dropped, or consumed by - /// `incoming-body.finish`. - /// - /// This invariant ensures that the implementation can determine whether - /// the user is consuming the contents of the body, waiting on the - /// `future-trailers` to be ready, or neither. This allows for network - /// backpressure is to be applied when the user is consuming the body, - /// and for that backpressure to not inhibit delivery of the trailers if - /// the user does not read the entire body. - %stream: func() -> result; - - /// Takes ownership of `incoming-body`, and returns a `future-trailers`. - /// This function will trap if the `input-stream` child is still alive. - finish: static func(this: incoming-body) -> future-trailers; - } - - /// Represents a future which may eventually return trailers, or an error. - /// - /// In the case that the incoming HTTP Request or Response did not have any - /// trailers, this future will resolve to the empty set of trailers once the - /// complete Request or Response body has been received. - resource future-trailers { - - /// Returns a pollable which becomes ready when either the trailers have - /// been received, or an error has occurred. When this pollable is ready, - /// the `get` method will return `some`. - subscribe: func() -> pollable; - - /// Returns the contents of the trailers, or an error which occurred, - /// once the future is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the trailers or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the HTTP Request or Response - /// body, as well as any trailers, were received successfully, or that an - /// error occurred receiving them. The optional `trailers` indicates whether - /// or not trailers were present in the body. - /// - /// When some `trailers` are returned by this method, the `trailers` - /// resource is immutable, and a child. Use of the `set`, `append`, or - /// `delete` methods will return an error, and the resource must be - /// dropped before the parent `future-trailers` is dropped. - get: func() -> option, error-code>>>; - } - - /// Represents an outgoing HTTP Response. - resource outgoing-response { - - /// Construct an `outgoing-response`, with a default `status-code` of `200`. - /// If a different `status-code` is needed, it must be set via the - /// `set-status-code` method. - /// - /// * `headers` is the HTTP Headers for the Response. - constructor(headers: headers); - - /// Get the HTTP Status Code for the Response. - status-code: func() -> status-code; - - /// Set the HTTP Status Code for the Response. Fails if the status-code - /// given is not a valid http status code. - set-status-code: func(status-code: status-code) -> result; - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transferred to - /// another component by e.g. `outgoing-handler.handle`. - headers: func() -> headers; - - /// Returns the resource corresponding to the outgoing Body for this Response. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-response` can be retrieved at most once. Subsequent - /// calls will return error. - body: func() -> result; - } - - /// Represents an outgoing HTTP Request or Response's Body. - /// - /// A body has both its contents - a stream of bytes - and a (possibly - /// empty) set of trailers, inducating the full contents of the body - /// have been sent. This resource represents the contents as an - /// `output-stream` child resource, and the completion of the body (with - /// optional trailers) with a static function that consumes the - /// `outgoing-body` resource, and ensures that the user of this interface - /// may not write to the body contents after the body has been finished. - /// - /// If the user code drops this resource, as opposed to calling the static - /// method `finish`, the implementation should treat the body as incomplete, - /// and that an error has occurred. The implementation should propagate this - /// error to the HTTP protocol by whatever means it has available, - /// including: corrupting the body on the wire, aborting the associated - /// Request, or sending a late status code for the Response. - resource outgoing-body { - - /// Returns a stream for writing the body contents. - /// - /// The returned `output-stream` is a child resource: it must be dropped - /// before the parent `outgoing-body` resource is dropped (or finished), - /// otherwise the `outgoing-body` drop or `finish` will trap. - /// - /// Returns success on the first call: the `output-stream` resource for - /// this `outgoing-body` may be retrieved at most once. Subsequent calls - /// will return error. - write: func() -> result; - - /// Finalize an outgoing body, optionally providing trailers. This must be - /// called to signal that the response is complete. If the `outgoing-body` - /// is dropped without calling `outgoing-body.finalize`, the implementation - /// should treat the body as corrupted. - /// - /// Fails if the body's `outgoing-request` or `outgoing-response` was - /// constructed with a Content-Length header, and the contents written - /// to the body (via `write`) does not match the value given in the - /// Content-Length. - finish: static func( - this: outgoing-body, - trailers: option - ) -> result<_, error-code>; - } - - /// Represents a future which may eventually return an incoming HTTP - /// Response, or an error. - /// - /// This resource is returned by the `wasi:http/outgoing-handler` interface to - /// provide the HTTP Response corresponding to the sent Request. - resource future-incoming-response { - /// Returns a pollable which becomes ready when either the Response has - /// been received, or an error has occurred. When this pollable is ready, - /// the `get` method will return `some`. - subscribe: func() -> pollable; - - /// Returns the incoming HTTP Response, or an error, once one is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the response or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the incoming HTTP Response - /// status and headers have received successfully, or that an error - /// occurred. Errors may also occur while consuming the response body, - /// but those will be reported by the `incoming-body` and its - /// `output-stream` child. - get: func() -> option>>; - - } -} diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http.wat b/crates/wit-component/tests/interfaces/wasi-http.canon-names.wat similarity index 100% rename from crates/wit-component/tests/interfaces/canon-names-wasi-http.wat rename to crates/wit-component/tests/interfaces/wasi-http.canon-names.wat diff --git a/crates/wit-component/tests/interfaces/canon-names-wasi-http/http.wit.print b/crates/wit-component/tests/interfaces/wasi-http/http.canon-names.wit.print similarity index 100% rename from crates/wit-component/tests/interfaces/canon-names-wasi-http/http.wit.print rename to crates/wit-component/tests/interfaces/wasi-http/http.canon-names.wit.print diff --git a/crates/wit-parser/tests/all.rs b/crates/wit-parser/tests/all.rs index 8cdc85986c..af96d6daee 100644 --- a/crates/wit-parser/tests/all.rs +++ b/crates/wit-parser/tests/all.rs @@ -25,7 +25,7 @@ fn main() { let mut trials = Vec::new(); for test in tests { let name = test.file_stem().and_then(|s| s.to_str()).unwrap_or(""); - if cfg!(feature = "canon-names") != name.starts_with("canon-names-") { + if name.starts_with("canon-names-") { continue; } let trial = Trial::test(format!("{test:?}"), move || { @@ -125,6 +125,16 @@ impl Runner { } else { test.with_extension(format!("wit.{extension}")) }; + let result_file = if cfg!(feature = "canon-names") { + let canon_file = result_file.with_extension(format!("canon-names.{extension}")); + if env::var_os("BLESS").is_some() || canon_file.exists() { + canon_file + } else { + result_file + } + } else { + result_file + }; if env::var_os("BLESS").is_some() { let normalized = normalize(&result, extension); if let Ok(prev) = fs::read(&result_file) { diff --git a/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit b/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit deleted file mode 100644 index 1f438b7141..0000000000 --- a/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit +++ /dev/null @@ -1,24 +0,0 @@ -package foo:root; -package foo:name@1.0.0 { - interface i1 { - type a = u32; - } - - world w1 { - import imp1: interface { - use i1.{a}; - } - } -} - -package foo:name@1.0.1 { - interface i1 { - type a = u32; - } - - world w1 { - import imp1: interface { - use i1.{a}; - } - } -} diff --git a/crates/wit-parser/tests/ui/canon-names-version-syntax.wit b/crates/wit-parser/tests/ui/canon-names-version-syntax.wit deleted file mode 100644 index 14d08afe82..0000000000 --- a/crates/wit-parser/tests/ui/canon-names-version-syntax.wit +++ /dev/null @@ -1,10 +0,0 @@ -package foo:root; -package a:b@1.0.0 {} -package a:b@1.0.1 {} -package a:b@1.0.1-- {} -package a:b@1.0.1-a+a {} -package a:b@1.0.1-1+1 {} -package a:b@1.0.1-1a+1a {} -package a:b@1.0.0-11-a {} -package a:b@1.0.0-a1.1-a {} -package a:b@1.0.0-11ab {} diff --git a/crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit.json b/crates/wit-parser/tests/ui/packages-nested-with-semver.wit.canon-names.json similarity index 100% rename from crates/wit-parser/tests/ui/canon-names-nested-with-semver.wit.json rename to crates/wit-parser/tests/ui/packages-nested-with-semver.wit.canon-names.json diff --git a/crates/wit-parser/tests/ui/canon-names-version-syntax.wit.json b/crates/wit-parser/tests/ui/version-syntax.wit.canon-names.json similarity index 100% rename from crates/wit-parser/tests/ui/canon-names-version-syntax.wit.json rename to crates/wit-parser/tests/ui/version-syntax.wit.canon-names.json From 8041f775e38881e24f4f229b1744d245f9ba1e52 Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Thu, 13 Aug 2026 19:59:34 -0700 Subject: [PATCH 5/8] tests --- crates/wit-component/tests/interfaces.rs | 2 +- .../canon-names-merge.canon-names.wat | 25 ++++ .../app.canon-names.wit.print | 5 + .../interfaces/canon-names-merge/app.wit | 5 + .../canon-names-merge/deps/lib-v1/lib.wit | 8 ++ .../canon-names-merge/deps/lib-v2/lib.wit | 8 ++ crates/wit-parser/Cargo.toml | 4 +- crates/wit-parser/src/lib.rs | 9 -- crates/wit-parser/src/resolve/mod.rs | 110 +----------------- 9 files changed, 56 insertions(+), 120 deletions(-) create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge.canon-names.wat create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/app.canon-names.wit.print create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/app.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit create mode 100644 crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit diff --git a/crates/wit-component/tests/interfaces.rs b/crates/wit-component/tests/interfaces.rs index aecbde8f0b..415a637d82 100644 --- a/crates/wit-component/tests/interfaces.rs +++ b/crates/wit-component/tests/interfaces.rs @@ -30,7 +30,7 @@ fn main() -> Result<()> { }; let is_dir = path.is_dir(); let is_test = is_dir || name.ends_with(".wit"); - if name.starts_with("canon-names-") { + if !cfg!(feature = "canon-names") && name.starts_with("canon-names-") { continue; } if is_test { diff --git a/crates/wit-component/tests/interfaces/canon-names-merge.canon-names.wat b/crates/wit-component/tests/interfaces/canon-names-merge.canon-names.wat new file mode 100644 index 0000000000..2cc004636d --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge.canon-names.wat @@ -0,0 +1,25 @@ +(component + (type (;0;) + (component + (type (;0;) + (component + (type (;0;) + (instance + (type (;0;) (record (field "name" string))) + (export (;1;) "info" (type (eq 0))) + (type (;2;) (func (result 1))) + (export (;0;) "get-info" (func (type 2))) + ) + ) + (import "test:lib/api@1" (versionsuffix ".2.2") (instance (;0;) (type 0))) + ) + ) + (export (;0;) "test:app/app@1.0.0" (component (type 0))) + ) + ) + (export (;1;) "app" (type 0)) + (@custom "package-docs" "\01{}") + (@producers + (processed-by "wit-component" "$CARGO_PKG_VERSION") + ) +) diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/app.canon-names.wit.print b/crates/wit-component/tests/interfaces/canon-names-merge/app.canon-names.wit.print new file mode 100644 index 0000000000..ed56295187 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/app.canon-names.wit.print @@ -0,0 +1,5 @@ +package test:app@1.0.0; + +world app { + import test:lib/api@1.2.2; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/app.wit b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit new file mode 100644 index 0000000000..5565ad65d0 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/app.wit @@ -0,0 +1,5 @@ +package test:app@1.0.0; + +world app { + import test:lib/api@1.2.0; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit new file mode 100644 index 0000000000..5306a47a97 --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v1/lib.wit @@ -0,0 +1,8 @@ +package test:lib@1.0.1; + +interface api { + record info { + name: string, + } + get-info: func() -> info; +} diff --git a/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit new file mode 100644 index 0000000000..d47b191cde --- /dev/null +++ b/crates/wit-component/tests/interfaces/canon-names-merge/deps/lib-v2/lib.wit @@ -0,0 +1,8 @@ +package test:lib@1.2.2; + +interface api { + record info { + name: string, + } + get-info: func() -> info; +} diff --git a/crates/wit-parser/Cargo.toml b/crates/wit-parser/Cargo.toml index feaadafac2..efa6df3bac 100644 --- a/crates/wit-parser/Cargo.toml +++ b/crates/wit-parser/Cargo.toml @@ -38,8 +38,8 @@ std = ['semver/std'] # Enables canonical interface name support where PackageName equality uses the # canonical version prefix (from canon_version_split) rather than the full -# semver version. This allows packages on the same canonical version track to -# be merged, keeping the largest version. +# semver version. This allows packages on the same canonical version to be +# merged, keeping the largest version. canon-names = [] # Enables support for `derive(Serialize, Deserialize)` on many structures, such diff --git a/crates/wit-parser/src/lib.rs b/crates/wit-parser/src/lib.rs index 86d641855d..cf152429c8 100644 --- a/crates/wit-parser/src/lib.rs +++ b/crates/wit-parser/src/lib.rs @@ -247,9 +247,6 @@ pub struct PackageName { #[cfg(feature = "canon-names")] impl PackageName { /// Returns the canonical version prefix for comparison purposes. - /// - /// When `canon-names` is enabled, this returns only the canonical prefix - /// from [`PackageName::canon_version_split`]. fn version_key(&self) -> Option { let version = self.version.as_ref()?; let (prefix, _) = Self::canon_version_split(version); @@ -1693,12 +1690,6 @@ mod test { ("2".to_string(), ".0.0".to_string()) ); - let v = Version::parse("10.20.30").unwrap(); - assert_eq!( - PackageName::canon_version_split(&v), - ("10".to_string(), ".20.30".to_string()) - ); - // major == 0, minor > 0: split after minor let v = Version::parse("0.2.6-rc.1").unwrap(); assert_eq!( diff --git a/crates/wit-parser/src/resolve/mod.rs b/crates/wit-parser/src/resolve/mod.rs index 71b1ae549b..b23e21c0c2 100644 --- a/crates/wit-parser/src/resolve/mod.rs +++ b/crates/wit-parser/src/resolve/mod.rs @@ -297,9 +297,7 @@ impl Resolve { pkg_details_map .insert(name, (prev_pkg, prev_source_map_index)); } - std::cmp::Ordering::Less => { - // Current (just inserted) is larger, keep it - } + std::cmp::Ordering::Less => {} std::cmp::Ordering::Equal => { let prev_offset = source_map_offsets[prev_source_map_index]; let mut span1 = my_span; @@ -1607,10 +1605,7 @@ impl Resolve { /// Returns the version suffix for the given interface's package, if any. /// - /// This is the second element of [`PackageName::canon_version_split`]: - /// e.g. for version `2.0.1` the canonical name uses `@2` and this - /// returns `Some(".0.1")`. Returns `None` only if the package has no - /// version. + /// See the component model explainer and 🔗 for more information on this feature. pub fn version_suffix_of(&self, interface: InterfaceId) -> Option { let iface = &self.interfaces[interface]; let pkg = &self.packages[iface.package?]; @@ -6163,56 +6158,6 @@ interface iface { Ok(()) } - #[cfg(feature = "canon-names")] - #[test] - fn canon_names_merge_keeps_larger_version() -> Result<()> { - let mut resolve1 = Resolve::default(); - resolve1.push_str( - "a.wit", - r#" - package foo:bar@2.0.0; - - interface my-iface { - type my-type = u32; - my-func: func(); - } - "#, - )?; - - let mut resolve2 = Resolve::default(); - resolve2.push_str( - "b.wit", - r#" - package foo:bar@2.0.1; - - interface my-iface { - type my-type = u32; - my-func: func(); - } - "#, - )?; - - resolve1.merge(resolve2)?; - - // Should have exactly one package (merged on canonical prefix "2") - assert_eq!(resolve1.packages.len(), 1); - let (_, pkg) = resolve1.packages.iter().next().unwrap(); - assert_eq!( - pkg.name.version.as_ref().unwrap().to_string(), - "2.0.1", - "should keep the larger version" - ); - - // Interface should be present with its type and function - let iface_id = pkg.interfaces["my-iface"]; - assert!(resolve1.interfaces[iface_id].types.contains_key("my-type")); - assert!(resolve1.interfaces[iface_id] - .functions - .contains_key("my-func")); - - Ok(()) - } - #[cfg(feature = "canon-names")] #[test] fn canon_names_merge_larger_into_smaller() -> Result<()> { @@ -6318,8 +6263,6 @@ interface iface { #[cfg(feature = "canon-names")] #[test] fn canon_names_different_tracks_not_merged() -> Result<()> { - // Packages on different canonical tracks should NOT merge. - // 0.1.x and 0.2.x have different canonical prefixes ("0.1" vs "0.2"). let mut resolve1 = Resolve::default(); resolve1.push_str( "a.wit", @@ -6351,53 +6294,4 @@ interface iface { Ok(()) } - - #[cfg(feature = "canon-names")] - #[test] - fn canon_names_merge_with_extra_interface() -> Result<()> { - // When the larger version adds a new interface, it should be added - // to the merged package. - let mut resolve1 = Resolve::default(); - resolve1.push_str( - "a.wit", - r#" - package foo:bar@3.0.0; - - interface existing { - base-func: func(); - } - "#, - )?; - - let mut resolve2 = Resolve::default(); - resolve2.push_str( - "b.wit", - r#" - package foo:bar@3.1.0; - - interface existing { - base-func: func(); - } - - interface added { - new-func: func(); - } - "#, - )?; - - resolve1.merge(resolve2)?; - - assert_eq!(resolve1.packages.len(), 1); - let (_, pkg) = resolve1.packages.iter().next().unwrap(); - assert_eq!(pkg.name.version.as_ref().unwrap().to_string(), "3.1.0"); - assert!(pkg.interfaces.contains_key("existing")); - assert!(pkg.interfaces.contains_key("added")); - - let added_id = pkg.interfaces["added"]; - assert!(resolve1.interfaces[added_id] - .functions - .contains_key("new-func")); - - Ok(()) - } } From a4cc3920792ad5df3a9172fed3c801a9164b7a1b Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Thu, 13 Aug 2026 20:37:02 -0700 Subject: [PATCH 6/8] fmt --- crates/wit-component/src/encoding.rs | 24 ++++++++++++++++++------ crates/wit-component/src/encoding/wit.rs | 11 +++++++---- crates/wit-parser/src/ast/resolve.rs | 4 +--- crates/wit-parser/src/lib.rs | 20 +++++++++----------- crates/wit-parser/src/resolve/mod.rs | 15 ++++++--------- 5 files changed, 41 insertions(+), 33 deletions(-) diff --git a/crates/wit-component/src/encoding.rs b/crates/wit-component/src/encoding.rs index b4c93df178..2730874691 100644 --- a/crates/wit-component/src/encoding.rs +++ b/crates/wit-component/src/encoding.rs @@ -1823,9 +1823,13 @@ impl<'a> EncodingState<'a> { for_module, iface.map(|_| { #[cfg(feature = "canon-names")] - { resolve.name_canonicalized_world_key(key) } + { + resolve.name_canonicalized_world_key(key) + } #[cfg(not(feature = "canon-names"))] - { resolve.name_world_key(key) } + { + resolve.name_world_key(key) + } }), &format!("{name}_drop"), key, @@ -1998,9 +2002,13 @@ impl<'a> EncodingState<'a> { for_module, Some({ #[cfg(feature = "canon-names")] - { resolve.name_canonicalized_world_key(key) } + { + resolve.name_canonicalized_world_key(key) + } #[cfg(not(feature = "canon-names"))] - { resolve.name_world_key(key) } + { + resolve.name_world_key(key) + } }), name, key, @@ -3050,9 +3058,13 @@ impl<'a> Shims<'a> { name, Some({ #[cfg(feature = "canon-names")] - { resolve.name_canonicalized_world_key(key) } + { + resolve.name_canonicalized_world_key(key) + } #[cfg(not(feature = "canon-names"))] - { resolve.name_world_key(key) } + { + resolve.name_world_key(key) + } }), *abi, )?; diff --git a/crates/wit-component/src/encoding/wit.rs b/crates/wit-component/src/encoding/wit.rs index ac853441f8..f9d307fb05 100644 --- a/crates/wit-component/src/encoding/wit.rs +++ b/crates/wit-component/src/encoding/wit.rs @@ -136,8 +136,7 @@ fn component_extern_name( (name, suffix) }; #[cfg(not(feature = "canon-names"))] - let (name, version_suffix): (String, Option) = - (resolve.name_world_key(key), None); + let (name, version_suffix): (String, Option) = (resolve.name_world_key(key), None); ComponentExternName { name: name.into(), @@ -231,7 +230,9 @@ impl Encoder<'_> { if interface == id { let idx = encoder.encode_instance(interface)?; log::trace!("exporting self as {idx}"); - encoder.outer.export(extern_name, ComponentTypeRef::Instance(idx)); + encoder + .outer + .export(extern_name, ComponentTypeRef::Instance(idx)); } else { encoder.push_instance(); for (_, id) in iface.types.iter() { @@ -242,7 +243,9 @@ impl Encoder<'_> { encoder.outer.ty().instance(&instance); encoder.import_map.insert(interface, encoder.instances); encoder.instances += 1; - encoder.outer.import(extern_name, ComponentTypeRef::Instance(idx)); + encoder + .outer + .import(extern_name, ComponentTypeRef::Instance(idx)); } } diff --git a/crates/wit-parser/src/ast/resolve.rs b/crates/wit-parser/src/ast/resolve.rs index df1cdc1b33..532326e45d 100644 --- a/crates/wit-parser/src/ast/resolve.rs +++ b/crates/wit-parser/src/ast/resolve.rs @@ -723,9 +723,7 @@ impl<'a> Resolver<'a> { }; return Err(ParseError::new_syntax( kind.span(), - format!( - "interface `{full_name}` cannot be {desc}ed more than once", - ), + format!("interface `{full_name}` cannot be {desc}ed more than once",), )); } } diff --git a/crates/wit-parser/src/lib.rs b/crates/wit-parser/src/lib.rs index cf152429c8..4a3098ea47 100644 --- a/crates/wit-parser/src/lib.rs +++ b/crates/wit-parser/src/lib.rs @@ -267,18 +267,16 @@ impl core::hash::Hash for PackageName { impl PartialEq for PackageName { fn eq(&self, other: &Self) -> bool { - self.namespace == other.namespace - && self.name == other.name - && { - #[cfg(feature = "canon-names")] - { - self.version_key() == other.version_key() - } - #[cfg(not(feature = "canon-names"))] - { - self.version == other.version - } + self.namespace == other.namespace && self.name == other.name && { + #[cfg(feature = "canon-names")] + { + self.version_key() == other.version_key() } + #[cfg(not(feature = "canon-names"))] + { + self.version == other.version + } + } } } diff --git a/crates/wit-parser/src/resolve/mod.rs b/crates/wit-parser/src/resolve/mod.rs index b23e21c0c2..8e7c3b8715 100644 --- a/crates/wit-parser/src/resolve/mod.rs +++ b/crates/wit-parser/src/resolve/mod.rs @@ -294,8 +294,7 @@ impl Resolve { match prev_pkg.name.full_version_cmp(¤t_pkg.name) { std::cmp::Ordering::Greater => { // Previous package had larger version, put it back - pkg_details_map - .insert(name, (prev_pkg, prev_source_map_index)); + pkg_details_map.insert(name, (prev_pkg, prev_source_map_index)); } std::cmp::Ordering::Less => {} std::cmp::Ordering::Equal => { @@ -304,13 +303,11 @@ impl Resolve { span1.adjust(offset); let mut span2 = prev_pkg.package_name_span; span2.adjust(prev_offset); - return Err(ResolveError::from( - ResolveErrorKind::DuplicatePackage { - name, - span1, - span2, - }, - )); + return Err(ResolveError::from(ResolveErrorKind::DuplicatePackage { + name, + span1, + span2, + })); } } } From 5dff8e757f88c49215346ca9f74e0880c639cefe Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Fri, 14 Aug 2026 13:42:46 -0700 Subject: [PATCH 7/8] remove feature flag --- crates/wit-component/Cargo.toml | 1 - crates/wit-component/src/encoding.rs | 75 ++++++----- crates/wit-component/src/encoding/wit.rs | 24 ++-- crates/wit-component/src/encoding/world.rs | 9 +- crates/wit-component/src/linking.rs | 12 +- crates/wit-component/tests/components.rs | 36 +++-- crates/wit-component/tests/interfaces.rs | 47 +++++-- crates/wit-parser/Cargo.toml | 6 - crates/wit-parser/src/lib.rs | 141 +++++++++++++------- crates/wit-parser/src/resolve/mod.rs | 146 +++++++++++---------- crates/wit-parser/tests/all.rs | 46 +++++-- 11 files changed, 328 insertions(+), 215 deletions(-) diff --git a/crates/wit-component/Cargo.toml b/crates/wit-component/Cargo.toml index 0972f5b0f7..86b0a5ccda 100644 --- a/crates/wit-component/Cargo.toml +++ b/crates/wit-component/Cargo.toml @@ -51,7 +51,6 @@ wasmtime = { workspace = true } dummy-module = ['dep:wat'] wat = ['dep:wast', 'dep:wat'] semver-check = ['dummy-module'] -canon-names = ['wit-parser/canon-names'] [[test]] name = "components" diff --git a/crates/wit-component/src/encoding.rs b/crates/wit-component/src/encoding.rs index 2730874691..d9f0ee7926 100644 --- a/crates/wit-component/src/encoding.rs +++ b/crates/wit-component/src/encoding.rs @@ -577,10 +577,11 @@ impl<'a> EncodingState<'a> { let instance_type_idx = self .component .type_instance(Some(&format!("ty-{name}")), &ty); - #[cfg(feature = "canon-names")] - let version_suffix = resolve.version_suffix_of(interface_id); - #[cfg(not(feature = "canon-names"))] - let version_suffix: Option = None; + let version_suffix = if resolve.use_canonical_names { + resolve.version_suffix_of(interface_id) + } else { + None + }; let instance_idx = self.component.import( wasm_encoder::ComponentExternName { @@ -751,10 +752,11 @@ impl<'a> EncodingState<'a> { let world = &resolve.worlds[self.info.encoder.metadata.world]; for export_name in exports { - #[cfg(feature = "canon-names")] - let export_string = resolve.name_canonicalized_world_key(export_name); - #[cfg(not(feature = "canon-names"))] - let export_string = resolve.name_world_key(export_name); + let export_string = if resolve.use_canonical_names { + resolve.name_canonicalized_world_key(export_name) + } else { + resolve.name_world_key(export_name) + }; match &world.exports[export_name] { WorldItem::Function(func) => { let ty = self @@ -985,10 +987,11 @@ impl<'a> EncodingState<'a> { component_index, imports, ); - #[cfg(feature = "canon-names")] - let version_suffix = resolve.version_suffix_of(export); - #[cfg(not(feature = "canon-names"))] - let version_suffix: Option = None; + let version_suffix = if resolve.use_canonical_names { + resolve.version_suffix_of(export) + } else { + None + }; let idx = self.component.export( wasm_encoder::ComponentExternName { @@ -1822,12 +1825,9 @@ impl<'a> EncodingState<'a> { shims, for_module, iface.map(|_| { - #[cfg(feature = "canon-names")] - { + if resolve.use_canonical_names { resolve.name_canonicalized_world_key(key) - } - #[cfg(not(feature = "canon-names"))] - { + } else { resolve.name_world_key(key) } }), @@ -2000,15 +2000,10 @@ impl<'a> EncodingState<'a> { Import::InterfaceFunc(key, _, name, abi) => self.materialize_wit_import( shims, for_module, - Some({ - #[cfg(feature = "canon-names")] - { - resolve.name_canonicalized_world_key(key) - } - #[cfg(not(feature = "canon-names"))] - { - resolve.name_world_key(key) - } + Some(if resolve.use_canonical_names { + resolve.name_canonicalized_world_key(key) + } else { + resolve.name_world_key(key) }), name, key, @@ -3056,15 +3051,10 @@ impl<'a> Shims<'a> { field, key, name, - Some({ - #[cfg(feature = "canon-names")] - { - resolve.name_canonicalized_world_key(key) - } - #[cfg(not(feature = "canon-names"))] - { - resolve.name_world_key(key) - } + Some(if resolve.use_canonical_names { + resolve.name_canonicalized_world_key(key) + } else { + resolve.name_world_key(key) }), *abi, )?; @@ -3343,6 +3333,7 @@ pub struct ComponentEncoder { merge_imports_based_on_semver: Option, pub(super) reject_legacy_names: bool, debug_names: bool, + use_canonical_names: bool, } impl ComponentEncoder { @@ -3376,7 +3367,9 @@ impl ComponentEncoder { } fn merge_metadata(&mut self, metadata: Bindgen) -> Result> { - self.metadata.merge(metadata) + let result = self.metadata.merge(metadata); + self.metadata.resolve.use_canonical_names = self.use_canonical_names; + result } /// Sets whether or not the encoder will validate its output. @@ -3385,6 +3378,16 @@ impl ComponentEncoder { self } + /// Sets whether to use canonical interface names during encoding. + /// + /// When enabled, interface names use canonical version prefixes and version + /// suffixes (e.g., `ns:pkg/iface@0.2` + versionsuffix `.1`) instead of full + /// version strings. + pub fn use_canonical_names(mut self, canonical: bool) -> Self { + self.use_canonical_names = canonical; + self + } + /// Sets whether or not to generate debug names in the output component. pub fn debug_names(mut self, debug_names: bool) -> Self { self.debug_names = debug_names; diff --git a/crates/wit-component/src/encoding/wit.rs b/crates/wit-component/src/encoding/wit.rs index f9d307fb05..f9f05abb16 100644 --- a/crates/wit-component/src/encoding/wit.rs +++ b/crates/wit-component/src/encoding/wit.rs @@ -126,17 +126,16 @@ fn component_extern_name( key: &WorldKey, item: &WorldItem, ) -> wasm_encoder::ComponentExternName<'static> { - #[cfg(feature = "canon-names")] - let (name, version_suffix) = { + let (name, version_suffix) = if resolve.use_canonical_names { let name = resolve.name_canonicalized_world_key(key); let suffix = match key { WorldKey::Interface(id) => resolve.version_suffix_of(*id), WorldKey::Name(_) => None, }; (name, suffix) + } else { + (resolve.name_world_key(key), None) }; - #[cfg(not(feature = "canon-names"))] - let (name, version_suffix): (String, Option) = (resolve.name_world_key(key), None); ComponentExternName { name: name.into(), @@ -209,8 +208,7 @@ impl Encoder<'_> { for interface in interfaces { encoder.interface = Some(interface); let iface = &self.resolve.interfaces[interface]; - #[cfg(feature = "canon-names")] - let extern_name = { + let extern_name = if self.resolve.use_canonical_names { let name = self.resolve.canonicalized_id_of(interface).unwrap(); let suffix = self.resolve.version_suffix_of(interface); ComponentExternName { @@ -219,13 +217,13 @@ impl Encoder<'_> { external_id: None, version_suffix: suffix.map(|s| s.into()), } - }; - #[cfg(not(feature = "canon-names"))] - let extern_name = ComponentExternName { - name: self.resolve.id_of(interface).unwrap().into(), - implements: None, - external_id: None, - version_suffix: None, + } else { + ComponentExternName { + name: self.resolve.id_of(interface).unwrap().into(), + implements: None, + external_id: None, + version_suffix: None, + } }; if interface == id { let idx = encoder.encode_instance(interface)?; diff --git a/crates/wit-component/src/encoding/world.rs b/crates/wit-component/src/encoding/world.rs index fe69891d66..af79d40e70 100644 --- a/crates/wit-component/src/encoding/world.rs +++ b/crates/wit-component/src/encoding/world.rs @@ -265,10 +265,11 @@ impl<'a> ComponentWorld<'a> { item: &WorldItem, required: &Required<'_>, ) -> Result<()> { - #[cfg(feature = "canon-names")] - let name = resolve.name_canonicalized_world_key(key); - #[cfg(not(feature = "canon-names"))] - let name = resolve.name_world_key(key); + let name = if resolve.use_canonical_names { + resolve.name_canonicalized_world_key(key) + } else { + resolve.name_world_key(key) + }; log::trace!("register import `{name}`"); let import_map_key = match item { WorldItem::Function(_) | WorldItem::Type { .. } => None, diff --git a/crates/wit-component/src/linking.rs b/crates/wit-component/src/linking.rs index dda280eef7..94c004651a 100644 --- a/crates/wit-component/src/linking.rs +++ b/crates/wit-component/src/linking.rs @@ -1686,6 +1686,9 @@ pub struct Linker { /// from two different libraries, whether their imports are unified when the /// semver version ranges for interface allow it. merge_imports_based_on_semver: Option, + + /// Whether to use canonical interface names. + use_canonical_names: bool, } impl Linker { @@ -1749,6 +1752,12 @@ impl Linker { self } + /// Whether to use canonical interface names. + pub fn use_canonical_names(mut self, canonical: bool) -> Self { + self.use_canonical_names = canonical; + self + } + /// Encode the component and return the bytes pub fn encode(mut self) -> Result> { if self.use_built_in_libdl { @@ -1894,7 +1903,8 @@ impl Linker { let mut encoder = ComponentEncoder::default() .validate(self.validate) - .debug_names(self.debug_names); + .debug_names(self.debug_names) + .use_canonical_names(self.use_canonical_names); if let Some(merge) = self.merge_imports_based_on_semver { encoder = encoder.merge_imports_based_on_semver(merge); }; diff --git a/crates/wit-component/tests/components.rs b/crates/wit-component/tests/components.rs index 5cbdd27fa2..8aaba6fb7f 100644 --- a/crates/wit-component/tests/components.rs +++ b/crates/wit-component/tests/components.rs @@ -62,14 +62,21 @@ fn main() -> Result<()> { if !path.is_dir() { continue; } - let name = path.file_name().unwrap().to_str().unwrap(); + let name = path.file_name().unwrap().to_str().unwrap().to_string(); if name.starts_with("canon-names-") { - continue; + trials.push(Trial::test(path.to_str().unwrap().to_string(), move || { + run_test(&path, true).map_err(|e| format!("{e:?}").into()) + })); + } else { + let path2 = path.clone(); + trials.push(Trial::test(path.to_str().unwrap().to_string(), move || { + run_test(&path, false).map_err(|e| format!("{e:?}").into()) + })); + let canon_name = format!("{}@canon-names", path2.to_str().unwrap()); + trials.push(Trial::test(canon_name, move || { + run_test(&path2, true).map_err(|e| format!("{e:?}").into()) + })); } - - trials.push(Trial::test(path.to_str().unwrap().to_string(), move || { - run_test(&path).map_err(|e| format!("{e:?}").into()) - })); } let mut args = Arguments::from_args(); @@ -83,8 +90,8 @@ fn is_error_test(test_case: &str) -> bool { test_case.starts_with("error-") } -fn canon_names_output(path: &Path, name: &str) -> std::path::PathBuf { - if cfg!(feature = "canon-names") { +fn canon_names_output(path: &Path, name: &str, use_canonical: bool) -> std::path::PathBuf { + if use_canonical { let parts: Vec<&str> = name.splitn(2, '.').collect(); let canon_name = if parts.len() == 2 { format!("{}.canon-names.{}", parts[0], parts[1]) @@ -99,9 +106,10 @@ fn canon_names_output(path: &Path, name: &str) -> std::path::PathBuf { path.join(name) } -fn run_test(path: &Path) -> Result<()> { +fn run_test(path: &Path, use_canonical: bool) -> Result<()> { let test_case = path.file_stem().unwrap().to_str().unwrap(); let mut resolve = Resolve::default(); + resolve.use_canonical_names = use_canonical; let (pkg_id, _) = match resolve.push_dir(&path) { Ok(v) => v, Err(err) => { @@ -127,6 +135,7 @@ fn run_test(path: &Path) -> Result<()> { .try_fold( ComponentEncoder::default() .debug_names(true) + .use_canonical_names(use_canonical) .module(&module)?, |encoder, path| { let (name, wasm) = read_name_and_module("adapt-", &path?, &resolve, pkg_id)?; @@ -146,7 +155,10 @@ fn run_test(path: &Path) -> Result<()> { // Sort list to ensure deterministic order, which determines priority in cases of duplicate symbols: libs.sort_by(|(_, a, _), (_, b, _)| a.cmp(b)); - let mut linker = Linker::default().validate(false).debug_names(true); + let mut linker = Linker::default() + .validate(false) + .debug_names(true) + .use_canonical_names(use_canonical); if path.join("stub-missing-functions").is_file() { linker = linker.stub_missing_functions(true); @@ -170,8 +182,8 @@ fn run_test(path: &Path) -> Result<()> { })? .encode() }; - let component_path = canon_names_output(&path, "component.wat"); - let component_wit_path = canon_names_output(&path, "component.wit.print"); + let component_path = canon_names_output(&path, "component.wat", use_canonical); + let component_wit_path = canon_names_output(&path, "component.wit.print", use_canonical); let error_path = path.join("error.txt"); let bytes = match result { diff --git a/crates/wit-component/tests/interfaces.rs b/crates/wit-component/tests/interfaces.rs index 415a637d82..e87061e7ff 100644 --- a/crates/wit-component/tests/interfaces.rs +++ b/crates/wit-component/tests/interfaces.rs @@ -25,20 +25,32 @@ fn main() -> Result<()> { for entry in fs::read_dir("tests/interfaces")? { let path = entry?.path(); let name = match path.file_name().and_then(|s| s.to_str()) { - Some(s) => s, + Some(s) => s.to_string(), None => continue, }; let is_dir = path.is_dir(); let is_test = is_dir || name.ends_with(".wit"); - if !cfg!(feature = "canon-names") && name.starts_with("canon-names-") { + if !is_test { continue; } - if is_test { - trials.push(Trial::test(name.to_string(), move || { - run_test(&path, is_dir) + if name.starts_with("canon-names-") { + trials.push(Trial::test(name, move || { + run_test(&path, is_dir, true) .context(format!("failed test `{}`", path.display())) .map_err(|e| format!("{e:?}").into()) })); + } else { + let path2 = path.clone(); + trials.push(Trial::test(name.clone(), move || { + run_test(&path, is_dir, false) + .context(format!("failed test `{}`", path.display())) + .map_err(|e| format!("{e:?}").into()) + })); + trials.push(Trial::test(format!("{name}@canon-names"), move || { + run_test(&path2, is_dir, true) + .context(format!("failed test `{}`", path2.display())) + .map_err(|e| format!("{e:?}").into()) + })); } } @@ -49,8 +61,8 @@ fn main() -> Result<()> { libtest_mimic::run(&args, trials).exit(); } -fn canon_names_path(path: &Path, ext: &str) -> std::path::PathBuf { - if cfg!(feature = "canon-names") { +fn canon_names_path(path: &Path, ext: &str, use_canonical: bool) -> std::path::PathBuf { + if use_canonical { let canon_ext = format!("canon-names.{ext}"); let canon_path = path.with_extension(&canon_ext); if std::env::var_os("BLESS").is_some() || canon_path.exists() { @@ -60,22 +72,23 @@ fn canon_names_path(path: &Path, ext: &str) -> std::path::PathBuf { path.with_extension(ext) } -fn run_test(path: &Path, is_dir: bool) -> Result<()> { +fn run_test(path: &Path, is_dir: bool, use_canonical: bool) -> Result<()> { let mut resolve = Resolve::new(); + resolve.use_canonical_names = use_canonical; let package = if is_dir { resolve.push_dir(path)?.0 } else { resolve.push_file(path)? }; - assert_print(&resolve, package, path, is_dir)?; + assert_print(&resolve, package, path, is_dir, use_canonical)?; // First convert the WIT package to a binary WebAssembly output, then // convert that binary wasm to textual wasm, then assert it matches the // expectation. let wasm = wit_component::encode(&resolve, package)?; let wat = wasmprinter::print_bytes(&wasm)?; - assert_output(&canon_names_path(path, "wat"), &wat)?; + assert_output(&canon_names_path(path, "wat", use_canonical), &wat)?; wasmparser::Validator::new_with_features(WasmFeatures::all()) .validate_all(&wasm) .context("failed to validate wasm output")?; @@ -87,7 +100,7 @@ fn run_test(path: &Path, is_dir: bool) -> Result<()> { let decoded_package = decoded.package(); let resolve = decoded.resolve(); - assert_print(resolve, decoded.package(), path, is_dir)?; + assert_print(resolve, decoded.package(), path, is_dir, use_canonical)?; // Finally convert the decoded package to wasm again and make sure it // matches the prior wasm. @@ -100,14 +113,20 @@ fn run_test(path: &Path, is_dir: bool) -> Result<()> { Ok(()) } -fn assert_print(resolve: &Resolve, pkg_id: PackageId, path: &Path, is_dir: bool) -> Result<()> { +fn assert_print( + resolve: &Resolve, + pkg_id: PackageId, + path: &Path, + is_dir: bool, + use_canonical: bool, +) -> Result<()> { let mut printer = WitPrinter::default(); printer.print(resolve, pkg_id, &[])?; let output = printer.output.to_string(); let pkg = &resolve.packages[pkg_id]; let expected = if is_dir { let base = path.join(format!("{}.wit.print", &pkg.name.name)); - if cfg!(feature = "canon-names") { + if use_canonical { let canon = path.join(format!("{}.canon-names.wit.print", &pkg.name.name)); if std::env::var_os("BLESS").is_some() || canon.exists() { canon @@ -118,7 +137,7 @@ fn assert_print(resolve: &Resolve, pkg_id: PackageId, path: &Path, is_dir: bool) base } } else { - canon_names_path(path, "wit.print") + canon_names_path(path, "wit.print", use_canonical) }; assert_output(&expected, &output)?; diff --git a/crates/wit-parser/Cargo.toml b/crates/wit-parser/Cargo.toml index efa6df3bac..830ac0ff5b 100644 --- a/crates/wit-parser/Cargo.toml +++ b/crates/wit-parser/Cargo.toml @@ -36,12 +36,6 @@ default = ['std', 'serde', 'decoding'] # Enables use of std::path::Path and filesystem-related APIs. std = ['semver/std'] -# Enables canonical interface name support where PackageName equality uses the -# canonical version prefix (from canon_version_split) rather than the full -# semver version. This allows packages on the same canonical version to be -# merged, keeping the largest version. -canon-names = [] - # Enables support for `derive(Serialize, Deserialize)` on many structures, such # as `Resolve`, which can assist when encoding `Resolve` as JSON for example. serde = ['dep:serde', 'dep:serde_derive', 'indexmap/serde', 'serde_json'] diff --git a/crates/wit-parser/src/lib.rs b/crates/wit-parser/src/lib.rs index 4a3098ea47..12273f7f93 100644 --- a/crates/wit-parser/src/lib.rs +++ b/crates/wit-parser/src/lib.rs @@ -232,7 +232,7 @@ pub enum AstItem { /// /// This is directly encoded as an "ID" in the binary component representation /// with an interfaced tacked on as well. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] #[cfg_attr(feature = "serde", derive(Serialize))] #[cfg_attr(feature = "serde", serde(into = "String"))] pub struct PackageName { @@ -244,77 +244,120 @@ pub struct PackageName { pub version: Option, } -#[cfg(feature = "canon-names")] -impl PackageName { - /// Returns the canonical version prefix for comparison purposes. - fn version_key(&self) -> Option { - let version = self.version.as_ref()?; - let (prefix, _) = Self::canon_version_split(version); - Some(prefix) +/// A key type for comparing packages, optionally by canonical version prefix. +/// +/// When `use_canonical` is true, the version is reduced to its canonical +/// prefix (e.g., `1.2.3` → `"1"`, `0.2.1` → `"0.2"`), compared as a string. +/// When false, the full `semver::Version` is used, preserving proper semver +/// ordering. +#[derive(Clone, Debug)] +pub struct PackageKey { + namespace: String, + name: String, + version_key: VersionKey, +} + +#[derive(Clone, Debug)] +enum VersionKey { + Exact(Option), + Canonical(Option), +} + +impl PartialEq for PackageKey { + fn eq(&self, other: &Self) -> bool { + self.namespace == other.namespace + && self.name == other.name + && self.version_key == other.version_key } } +impl Eq for PackageKey {} -impl core::hash::Hash for PackageName { - fn hash(&self, state: &mut H) { +impl std::hash::Hash for PackageKey { + fn hash(&self, state: &mut H) { self.namespace.hash(state); self.name.hash(state); - #[cfg(feature = "canon-names")] - self.version_key().hash(state); - #[cfg(not(feature = "canon-names"))] - self.version.hash(state); + self.version_key.hash(state); + } +} + +impl PartialOrd for PackageKey { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) } } -impl PartialEq for PackageName { +impl Ord for PackageKey { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.namespace + .cmp(&other.namespace) + .then_with(|| self.name.cmp(&other.name)) + .then_with(|| self.version_key.cmp(&other.version_key)) + } +} + +impl PartialEq for VersionKey { fn eq(&self, other: &Self) -> bool { - self.namespace == other.namespace && self.name == other.name && { - #[cfg(feature = "canon-names")] - { - self.version_key() == other.version_key() + match (self, other) { + (VersionKey::Exact(a), VersionKey::Exact(b)) => a == b, + (VersionKey::Canonical(a), VersionKey::Canonical(b)) => a == b, + _ => false, + } + } +} +impl Eq for VersionKey {} + +impl std::hash::Hash for VersionKey { + fn hash(&self, state: &mut H) { + match self { + VersionKey::Exact(v) => { + 0u8.hash(state); + v.hash(state); } - #[cfg(not(feature = "canon-names"))] - { - self.version == other.version + VersionKey::Canonical(s) => { + 1u8.hash(state); + s.hash(state); } } } } -impl Eq for PackageName {} - -impl PartialOrd for PackageName { - fn partial_cmp(&self, other: &Self) -> Option { +impl PartialOrd for VersionKey { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl Ord for PackageName { - fn cmp(&self, other: &Self) -> core::cmp::Ordering { - self.namespace - .cmp(&other.namespace) - .then_with(|| self.name.cmp(&other.name)) - .then_with(|| { - #[cfg(feature = "canon-names")] - { - self.version_key().cmp(&other.version_key()) - } - #[cfg(not(feature = "canon-names"))] - { - self.version.cmp(&other.version) - } - }) +impl Ord for VersionKey { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + match (self, other) { + (VersionKey::Exact(a), VersionKey::Exact(b)) => a.cmp(b), + (VersionKey::Canonical(a), VersionKey::Canonical(b)) => a.cmp(b), + (_, _) => unreachable!(), + } } } -impl PackageName { - /// Compares the full version of two package names. +impl PackageKey { + /// Creates a new `PackageKey` from a `PackageName`. /// - /// Unlike `Ord` (which may compare only canonical prefixes when - /// `canon-names` is enabled), this always compares the complete semver - /// version. Useful for determining which package has the larger version - /// during merging. - pub fn full_version_cmp(&self, other: &Self) -> core::cmp::Ordering { - self.version.cmp(&other.version) + /// If `use_canonical` is true, the version is reduced to its canonical + /// prefix for comparison purposes. Otherwise the full semver `Version` is + /// used, preserving proper semver ordering. + pub fn new(pkg: &PackageName, use_canonical: bool) -> Self { + let version_key = if use_canonical { + VersionKey::Canonical( + pkg.version + .as_ref() + .map(|v| PackageName::canon_version_split(v).0), + ) + } else { + VersionKey::Exact(pkg.version.clone()) + }; + PackageKey { + namespace: pkg.namespace.clone(), + name: pkg.name.clone(), + version_key, + } } } diff --git a/crates/wit-parser/src/resolve/mod.rs b/crates/wit-parser/src/resolve/mod.rs index 8e7c3b8715..4ebe20bf3a 100644 --- a/crates/wit-parser/src/resolve/mod.rs +++ b/crates/wit-parser/src/resolve/mod.rs @@ -104,6 +104,12 @@ pub struct Resolve { /// Source map for converting spans to file locations. #[cfg_attr(feature = "serde", serde(skip))] pub source_map: SourceMap, + + /// When true, packages are compared and encoded using canonical version + /// prefixes (e.g., `1.2.3` and `1.3.0` share the canonical prefix `"1"`). + /// When false (the default), full exact versions are used. + #[cfg_attr(feature = "serde", serde(skip))] + pub use_canonical_names: bool, } /// A WIT package within a `Resolve`. @@ -193,40 +199,44 @@ impl PackageSources { /// Visitor helper for performing topological sort on a group of packages. fn visit<'a>( pkg: &'a UnresolvedPackage, - pkg_details_map: &'a BTreeMap, - order: &mut IndexSet, - visiting: &mut HashSet<&'a PackageName>, + pkg_details_map: &'a BTreeMap, + order: &mut IndexSet, + visiting: &mut HashSet, source_map_offsets: &[u32], + use_canonical: bool, ) -> ResolveResult<()> { - if order.contains(&pkg.name) { + let key = PackageKey::new(&pkg.name, use_canonical); + if order.contains(&key) { return Ok(()); } let (_, source_map_index) = pkg_details_map - .get(&pkg.name) + .get(&key) .expect("No pkg_details found for package when doing topological sort"); let offset = source_map_offsets[*source_map_index]; for (i, (dep, _)) in pkg.foreign_deps.iter().enumerate() { let mut span = pkg.foreign_dep_spans[i]; span.adjust(offset); - if !visiting.insert(dep) { + let dep_key = PackageKey::new(dep, use_canonical); + if !visiting.insert(dep_key.clone()) { return Err(ResolveError::from(ResolveErrorKind::PackageCycle { package: dep.clone(), span, })); } - if let Some((dep_pkg, _)) = pkg_details_map.get(dep) { + if let Some((dep_pkg, _)) = pkg_details_map.get(&dep_key) { visit( dep_pkg, pkg_details_map, order, visiting, source_map_offsets, + use_canonical, )?; } - assert!(visiting.remove(dep)); + assert!(visiting.remove(&dep_key)); } - assert!(order.insert(pkg.name.clone())); + assert!(order.insert(key)); Ok(()) } @@ -236,6 +246,20 @@ impl Resolve { Resolve::default() } + /// Looks up a package ID by name. When `use_canonical_names` is enabled, + /// matches by canonical version prefix rather than exact version. + pub fn find_package(&self, name: &PackageName) -> Option { + if self.use_canonical_names { + let key = PackageKey::new(name, true); + self.package_names + .iter() + .find(|(n, _)| PackageKey::new(n, true) == key) + .map(|(_, id)| *id) + } else { + self.package_names.get(name).copied() + } + } + /// Merge `main` and `deps` into this [`Resolve`], topologically sorting /// them internally. Returns the [`PackageId`] of `main` and a /// [`PackageSources`] covering all groups. @@ -275,26 +299,24 @@ impl Resolve { .map(|sm| self.push_source_map(sm.clone())) .collect(); - let mut pkg_details_map: BTreeMap = - BTreeMap::new(); + let mut pkg_details_map: BTreeMap = BTreeMap::new(); for (pkg, source_map_index) in all_packages { - let name = pkg.name.clone(); + let key = PackageKey::new(&pkg.name, self.use_canonical_names); let my_span = pkg.package_name_span; let offset = source_map_offsets[source_map_index]; if let Some((prev_pkg, prev_source_map_index)) = - pkg_details_map.insert(name.clone(), (pkg, source_map_index)) + pkg_details_map.insert(key.clone(), (pkg, source_map_index)) { - #[cfg(feature = "canon-names")] - { - // When canon-names is enabled, packages with the same + if self.use_canonical_names { + // When canonical names are enabled, packages with the same // canonical version prefix are considered equivalent. // Keep the one with the larger full version. // If full versions are exactly equal, it's a true duplicate error. - let (current_pkg, _) = pkg_details_map.get(&name).unwrap(); - match prev_pkg.name.full_version_cmp(¤t_pkg.name) { + let (current_pkg, _) = pkg_details_map.get(&key).unwrap(); + match prev_pkg.name.version.cmp(¤t_pkg.name.version) { std::cmp::Ordering::Greater => { // Previous package had larger version, put it back - pkg_details_map.insert(name, (prev_pkg, prev_source_map_index)); + pkg_details_map.insert(key, (prev_pkg, prev_source_map_index)); } std::cmp::Ordering::Less => {} std::cmp::Ordering::Equal => { @@ -304,22 +326,20 @@ impl Resolve { let mut span2 = prev_pkg.package_name_span; span2.adjust(prev_offset); return Err(ResolveError::from(ResolveErrorKind::DuplicatePackage { - name, + name: prev_pkg.name, span1, span2, })); } } - } - #[cfg(not(feature = "canon-names"))] - { + } else { let prev_offset = source_map_offsets[prev_source_map_index]; let mut span1 = my_span; span1.adjust(offset); let mut span2 = prev_pkg.package_name_span; span2.adjust(prev_offset); return Err(ResolveError::from(ResolveErrorKind::DuplicatePackage { - name, + name: prev_pkg.name, span1, span2, })); @@ -340,14 +360,15 @@ impl Resolve { &mut order, &mut visiting, &source_map_offsets, + self.use_canonical_names, )?; } } let mut package_id_to_source_map_idx = BTreeMap::new(); let mut main_pkg_id = None; - for name in order { - let (pkg, source_map_index) = pkg_details_map.remove(&name).unwrap(); + for key in order { + let (pkg, source_map_index) = pkg_details_map.remove(&key).unwrap(); let span_offset = source_map_offsets[source_map_index]; let is_main = pkg.name == main_name; let id = self.push(pkg, span_offset)?; @@ -545,7 +566,6 @@ impl Resolve { let mut map = MergeMap::new(&resolve, &self); map.build()?; - #[cfg(feature = "canon-names")] let version_upgrades = map.version_upgrades.clone(); let MergeMap { package_map, @@ -746,10 +766,10 @@ impl Resolve { } } - // When canon-names is enabled and a package from `from` had a larger - // version than the matching package in `into`, upgrade the version - // stored on the `into` package and update the `package_names` index. - #[cfg(feature = "canon-names")] + // When canonical names are enabled and a package from `from` had a + // larger version than the matching package in `into`, upgrade the + // version stored on the `into` package and update the `package_names` + // index. for (into_id, version) in version_upgrades { let pkg = &mut self.packages[into_id]; pkg.name.version = Some(version); @@ -1335,13 +1355,10 @@ impl Resolve { base.push_str(name); if let Some(version) = &package.name.version { base.push_str("@"); - #[cfg(feature = "canon-names")] - { + if self.use_canonical_names { let (prefix, _) = PackageName::canon_version_split(version); base.push_str(&prefix); - } - #[cfg(not(feature = "canon-names"))] - { + } else { let string = PackageName::version_compat_track_string(version); base.push_str(&string); } @@ -1503,8 +1520,8 @@ impl Resolve { // The world name is fully-qualified. (_, ParsedUsePath::Package(pkg, world_name)) => { - let pkg = match self.package_names.get(&pkg) { - Some(pkg) => *pkg, + let pkg = match self.find_package(&pkg) { + Some(pkg) => pkg, None => { let mut candidates = self.package_names.iter().filter(|(name, _)| { @@ -3811,17 +3828,13 @@ impl Remap { None => break, }; - let pkgid = resolve - .package_names - .get(pkg_name) - .copied() - .ok_or_else(|| { - ResolveError::from(ResolveErrorKind::PackageNotFound { - span, - requested: pkg_name.clone(), - known: resolve.package_names.keys().cloned().collect(), - }) - })?; + let pkgid = resolve.find_package(pkg_name).ok_or_else(|| { + ResolveError::from(ResolveErrorKind::PackageNotFound { + span, + requested: pkg_name.clone(), + known: resolve.package_names.keys().cloned().collect(), + }) + })?; // Functions can't be imported so this should be empty. assert!(unresolved_iface.functions.is_empty()); @@ -3877,17 +3890,13 @@ impl Remap { None => break, }; - let pkgid = resolve - .package_names - .get(pkg_name) - .copied() - .ok_or_else(|| { - ResolveError::from(ResolveErrorKind::PackageNotFound { - span, - requested: pkg_name.clone(), - known: resolve.package_names.keys().cloned().collect(), - }) - })?; + let pkgid = resolve.find_package(pkg_name).ok_or_else(|| { + ResolveError::from(ResolveErrorKind::PackageNotFound { + span, + requested: pkg_name.clone(), + known: resolve.package_names.keys().cloned().collect(), + }) + })?; let pkg = &resolve.packages[pkgid]; let world_span = unresolved_world.span; @@ -4533,7 +4542,6 @@ struct MergeMap<'a> { /// Packages in `into` whose version should be upgraded because `from` /// had a larger version on the same canonical track. Maps `into` package /// ID to the larger version from `from`. - #[cfg(feature = "canon-names")] version_upgrades: HashMap, /// Which `Resolve` is being merged from. @@ -4552,7 +4560,6 @@ impl<'a> MergeMap<'a> { world_map: Default::default(), interfaces_to_add: Default::default(), worlds_to_add: Default::default(), - #[cfg(feature = "canon-names")] version_upgrades: Default::default(), from, into, @@ -4562,8 +4569,8 @@ impl<'a> MergeMap<'a> { fn build(&mut self) -> anyhow::Result<()> { for from_id in self.from.topological_packages() { let from = &self.from.packages[from_id]; - let into_id = match self.into.package_names.get(&from.name) { - Some(id) => *id, + let into_id = match self.into.find_package(&from.name) { + Some(id) => id, // This package, according to its name and url, is not present // in `self` so it needs to get added below. @@ -4574,10 +4581,9 @@ impl<'a> MergeMap<'a> { }; log::trace!("merging duplicate package {}", from.name); - #[cfg(feature = "canon-names")] - { + if self.into.use_canonical_names { let into = &self.into.packages[into_id]; - if from.name.full_version_cmp(&into.name).is_gt() { + if from.name.version.cmp(&into.name.version).is_gt() { if let Some(version) = from.name.version.clone() { self.version_upgrades.insert(into_id, version); } @@ -6155,12 +6161,12 @@ interface iface { Ok(()) } - #[cfg(feature = "canon-names")] #[test] fn canon_names_merge_larger_into_smaller() -> Result<()> { // The larger version (from) is merged into the smaller (into). // Extra types/functions from the larger version should appear in the result. let mut resolve1 = Resolve::default(); + resolve1.use_canonical_names = true; resolve1.push_str( "a.wit", r#" @@ -6204,12 +6210,12 @@ interface iface { Ok(()) } - #[cfg(feature = "canon-names")] #[test] fn canon_names_merge_smaller_into_larger() -> Result<()> { // The smaller version (from) is merged into the larger (into). // The larger version's content should be preserved as-is. let mut resolve1 = Resolve::default(); + resolve1.use_canonical_names = true; resolve1.push_str( "a.wit", r#" @@ -6257,10 +6263,10 @@ interface iface { Ok(()) } - #[cfg(feature = "canon-names")] #[test] fn canon_names_different_tracks_not_merged() -> Result<()> { let mut resolve1 = Resolve::default(); + resolve1.use_canonical_names = true; resolve1.push_str( "a.wit", r#" diff --git a/crates/wit-parser/tests/all.rs b/crates/wit-parser/tests/all.rs index af96d6daee..7b5e55396b 100644 --- a/crates/wit-parser/tests/all.rs +++ b/crates/wit-parser/tests/all.rs @@ -24,17 +24,42 @@ fn main() { let mut trials = Vec::new(); for test in tests { - let name = test.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + let name = test + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_string(); if name.starts_with("canon-names-") { - continue; - } - let trial = Trial::test(format!("{test:?}"), move || { - Runner {} + let trial = Trial::test(format!("{test:?}"), move || { + Runner { + use_canonical: true, + } .run(&test) .context(format!("test {test:?} failed")) .map_err(|e| format!("{e:?}").into()) - }); - trials.push(trial); + }); + trials.push(trial); + } else { + let test2 = test.clone(); + let trial = Trial::test(format!("{test:?}"), move || { + Runner { + use_canonical: false, + } + .run(&test) + .context(format!("test {test:?} failed")) + .map_err(|e| format!("{e:?}").into()) + }); + trials.push(trial); + let trial = Trial::test(format!("{test2:?}@canon-names"), move || { + Runner { + use_canonical: true, + } + .run(&test2) + .context(format!("test {test2:?}@canon-names failed")) + .map_err(|e| format!("{e:?}").into()) + }); + trials.push(trial); + } } let mut args = Arguments::from_args(); @@ -74,11 +99,14 @@ fn find_tests() -> Vec { } } -struct Runner {} +struct Runner { + use_canonical: bool, +} impl Runner { fn run(&mut self, test: &Path) -> Result<()> { let mut resolve = Resolve::new(); + resolve.use_canonical_names = self.use_canonical; resolve.features.insert("active".to_string()); let result = resolve.push_path(test); let result = if test.iter().any(|s| s == "parse-fail") { @@ -125,7 +153,7 @@ impl Runner { } else { test.with_extension(format!("wit.{extension}")) }; - let result_file = if cfg!(feature = "canon-names") { + let result_file = if self.use_canonical { let canon_file = result_file.with_extension(format!("canon-names.{extension}")); if env::var_os("BLESS").is_some() || canon_file.exists() { canon_file From af97cd6c188022f9f31981f5bd46c7bc4272beb8 Mon Sep 17 00:00:00 2001 From: Yan Chen Date: Fri, 14 Aug 2026 16:37:06 -0700 Subject: [PATCH 8/8] add CLI flag --- crates/wit-component/src/encoding.rs | 36 ++++++++-------------- crates/wit-component/src/lib.rs | 39 ++++++++++++++++++++++++ crates/wit-component/src/linking.rs | 35 +++++++-------------- crates/wit-component/tests/components.rs | 16 ++++++++-- src/bin/wasm-tools/component.rs | 39 ++++++++++++++---------- 5 files changed, 99 insertions(+), 66 deletions(-) diff --git a/crates/wit-component/src/encoding.rs b/crates/wit-component/src/encoding.rs index d9f0ee7926..5fc6b02a5c 100644 --- a/crates/wit-component/src/encoding.rs +++ b/crates/wit-component/src/encoding.rs @@ -71,11 +71,11 @@ //! otherwise there's no way to run a `wasi_snapshot_preview1` module within the //! component model. -use crate::StringEncoding; use crate::metadata::{self, Bindgen, ModuleMetadata}; use crate::validation::{ Export, ExportMap, Import, ImportInstance, ImportMap, PayloadInfo, PayloadType, }; +use crate::{SemverCompat, StringEncoding}; use anyhow::{Context, Result, anyhow, bail}; use indexmap::{IndexMap, IndexSet}; use std::borrow::Cow; @@ -3330,10 +3330,9 @@ pub struct ComponentEncoder { pub(super) adapters: IndexMap, import_name_map: HashMap, realloc_via_memory_grow: bool, - merge_imports_based_on_semver: Option, + semver_compat: SemverCompat, pub(super) reject_legacy_names: bool, debug_names: bool, - use_canonical_names: bool, } impl ComponentEncoder { @@ -3368,7 +3367,7 @@ impl ComponentEncoder { fn merge_metadata(&mut self, metadata: Bindgen) -> Result> { let result = self.metadata.merge(metadata); - self.metadata.resolve.use_canonical_names = self.use_canonical_names; + self.metadata.resolve.use_canonical_names = self.semver_compat == SemverCompat::Canonical; result } @@ -3378,31 +3377,22 @@ impl ComponentEncoder { self } - /// Sets whether to use canonical interface names during encoding. - /// - /// When enabled, interface names use canonical version prefixes and version - /// suffixes (e.g., `ns:pkg/iface@0.2` + versionsuffix `.1`) instead of full - /// version strings. - pub fn use_canonical_names(mut self, canonical: bool) -> Self { - self.use_canonical_names = canonical; - self - } - /// Sets whether or not to generate debug names in the output component. pub fn debug_names(mut self, debug_names: bool) -> Self { self.debug_names = debug_names; self } - /// Sets whether to merge imports based on semver to the specified value. - /// - /// This affects how when to WIT worlds are merged together, for example - /// from two different libraries, whether their imports are unified when the - /// semver version ranges for interface allow it. + /// Sets the semver compatibility mode for this encoder. /// - /// This is enabled by default. - pub fn merge_imports_based_on_semver(mut self, merge: bool) -> Self { - self.merge_imports_based_on_semver = Some(merge); + /// - `SemverCompat::None`: exact version matching, no merging. Same as the old flag + /// `merge_imports_based_on_semver(false)`. + /// - `SemverCompat::Merge`: merge imports based on semver. + /// Same as the old flag `merge_imports_based_on_semver(true)`. + /// This is the default behavior. + /// - `SemverCompat::Canonical`: merge imports based on the canonical version prefixes. + pub fn semver_compat(mut self, compat: SemverCompat) -> Self { + self.semver_compat = compat; self } @@ -3540,7 +3530,7 @@ impl ComponentEncoder { bail!("a module is required when encoding a component"); } - if self.merge_imports_based_on_semver.unwrap_or(true) { + if self.semver_compat != SemverCompat::None { self.metadata .resolve .merge_world_imports_based_on_semver(self.metadata.world)?; diff --git a/crates/wit-component/src/lib.rs b/crates/wit-component/src/lib.rs index 11f57201e5..2b0635e0d9 100644 --- a/crates/wit-component/src/lib.rs +++ b/crates/wit-component/src/lib.rs @@ -81,6 +81,45 @@ impl From for wasm_encoder::CanonicalOption { } } +/// Controls how semver is used when resolving and encoding interfaces. +#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum SemverCompat { + /// Exact version matching everywhere. No merging or canonicalization. + None, + /// Merge imports based on semver. This is the default behavior. + /// Package identity still use exact versions. + #[default] + Merge, + /// Merge imports based on the canonical version prefixes. + /// Package identity uses canonical version prefixes only. + Canonical, +} + +impl Display for SemverCompat { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + SemverCompat::None => write!(f, "none"), + SemverCompat::Merge => write!(f, "merge"), + SemverCompat::Canonical => write!(f, "canonical"), + } + } +} + +impl FromStr for SemverCompat { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s { + "none" => Ok(SemverCompat::None), + "merge" => Ok(SemverCompat::Merge), + "canonical" => Ok(SemverCompat::Canonical), + _ => { + bail!("unknown semver compat mode `{s}`, expected `none`, `merge`, or `canonical`") + } + } + } +} + /// A producer section to be added to all modules and components synthesized by /// this crate pub(crate) fn base_producers() -> wasm_metadata::Producers { diff --git a/crates/wit-component/src/linking.rs b/crates/wit-component/src/linking.rs index 94c004651a..63a3b1f151 100644 --- a/crates/wit-component/src/linking.rs +++ b/crates/wit-component/src/linking.rs @@ -23,6 +23,7 @@ //! ahead-of-time. use { + crate::SemverCompat, crate::encoding::{ComponentEncoder, Instance, Item, LibraryInfo, MainOrAdapter}, anyhow::{Context, Result, anyhow, bail}, indexmap::{IndexMap, IndexSet, map::Entry}, @@ -1682,13 +1683,8 @@ pub struct Linker { /// If `None`, use `DEFAULT_STACK_SIZE_BYTES`. stack_size: Option, - /// This affects how when to WIT worlds are merged together, for example - /// from two different libraries, whether their imports are unified when the - /// semver version ranges for interface allow it. - merge_imports_based_on_semver: Option, - - /// Whether to use canonical interface names. - use_canonical_names: bool, + /// Controls how semver is used when resolving and encoding interfaces. + semver_compat: Option, } impl Linker { @@ -1742,19 +1738,11 @@ impl Linker { self } - /// This affects how when to WIT worlds are merged together, for example - /// from two different libraries, whether their imports are unified when the - /// semver version ranges for interface allow it. + /// Sets the semver compatibility mode for this linker. /// - /// This is enabled by default. - pub fn merge_imports_based_on_semver(mut self, merge: bool) -> Self { - self.merge_imports_based_on_semver = Some(merge); - self - } - - /// Whether to use canonical interface names. - pub fn use_canonical_names(mut self, canonical: bool) -> Self { - self.use_canonical_names = canonical; + /// See [`SemverCompat`] for available modes. + pub fn semver_compat(mut self, compat: SemverCompat) -> Self { + self.semver_compat = Some(compat); self } @@ -1903,11 +1891,10 @@ impl Linker { let mut encoder = ComponentEncoder::default() .validate(self.validate) - .debug_names(self.debug_names) - .use_canonical_names(self.use_canonical_names); - if let Some(merge) = self.merge_imports_based_on_semver { - encoder = encoder.merge_imports_based_on_semver(merge); - }; + .debug_names(self.debug_names); + if let Some(compat) = self.semver_compat { + encoder = encoder.semver_compat(compat); + } encoder = encoder.module(&env_module)?; for (name, module) in &self.adapters { diff --git a/crates/wit-component/tests/components.rs b/crates/wit-component/tests/components.rs index 8aaba6fb7f..8e8c673766 100644 --- a/crates/wit-component/tests/components.rs +++ b/crates/wit-component/tests/components.rs @@ -5,7 +5,9 @@ use std::{borrow::Cow, fs, path::Path}; use wasm_encoder::{Encode, Section}; use wasm_metadata::{Metadata, Payload}; use wasmparser::{Parser, Validator, WasmFeatures}; -use wit_component::{ComponentEncoder, DecodedWasm, Linker, StringEncoding, WitPrinter}; +use wit_component::{ + ComponentEncoder, DecodedWasm, Linker, SemverCompat, StringEncoding, WitPrinter, +}; use wit_parser::{PackageId, Resolve, UnresolvedPackageGroup}; /// Tests the encoding of components. @@ -135,7 +137,11 @@ fn run_test(path: &Path, use_canonical: bool) -> Result<()> { .try_fold( ComponentEncoder::default() .debug_names(true) - .use_canonical_names(use_canonical) + .semver_compat(if use_canonical { + SemverCompat::Canonical + } else { + SemverCompat::Merge + }) .module(&module)?, |encoder, path| { let (name, wasm) = read_name_and_module("adapt-", &path?, &resolve, pkg_id)?; @@ -158,7 +164,11 @@ fn run_test(path: &Path, use_canonical: bool) -> Result<()> { let mut linker = Linker::default() .validate(false) .debug_names(true) - .use_canonical_names(use_canonical); + .semver_compat(if use_canonical { + SemverCompat::Canonical + } else { + SemverCompat::Merge + }); if path.join("stub-missing-functions").is_file() { linker = linker.stub_missing_functions(true); diff --git a/src/bin/wasm-tools/component.rs b/src/bin/wasm-tools/component.rs index 310658184f..d70b131762 100644 --- a/src/bin/wasm-tools/component.rs +++ b/src/bin/wasm-tools/component.rs @@ -14,8 +14,8 @@ use wasmparser::types::{CoreTypeId, EntityType, Types}; use wasmparser::{Payload, ValidPayload, WasmFeatures}; use wat::Detect; use wit_component::{ - ComponentEncoder, DecodedWasm, Linker, StringEncoding, WitPrinter, embed_component_metadata, - metadata, + ComponentEncoder, DecodedWasm, Linker, SemverCompat, StringEncoding, WitPrinter, + embed_component_metadata, metadata, }; use wit_parser::{LiftLowerAbi, Mangling, ManglingAndAbi, WorldItem, WorldKey}; @@ -148,12 +148,20 @@ pub struct NewOpts { #[clap(long)] realloc_via_memory_grow: bool, - /// Indicates whether imports into the final component are merged based on - /// semver ranges. + /// Controls how semver is used when resolving and encoding interfaces. /// - /// This is enabled by default. - #[clap(long, value_name = "")] - merge_imports_based_on_semver: Option, + /// Possible values: `none`, `merge` (default), `canonical`. + /// + /// - `none`: exact version matching, no merging. Same as the old flag + /// `merge_imports_based_on_semver = false`. + /// + /// - `merge`: merge imports based on semver. + /// Same as the old flag `merge_imports_based_on_semver = true`. + /// This is the default behavior. + /// + /// - `canonical`: merge imports based on the canonical version prefixes. + #[clap(long, value_name = "MODE")] + semver_compat: Option, /// Reject usage of the "legacy" naming scheme of `wit-component` and /// require the new naming scheme to be used. @@ -179,8 +187,8 @@ impl NewOpts { .validate(!self.skip_validation) .reject_legacy_names(self.reject_legacy_names); - if let Some(merge) = self.merge_imports_based_on_semver { - encoder = encoder.merge_imports_based_on_semver(merge); + if let Some(compat) = self.semver_compat { + encoder = encoder.semver_compat(compat); } encoder = encoder.module(&wasm)?; @@ -517,12 +525,11 @@ pub struct LinkOpts { #[clap(long)] use_built_in_libdl: bool, - /// Indicates whether imports into the final component are merged based on - /// semver ranges. + /// Controls how semver is used when resolving and encoding interfaces. /// - /// This is enabled by default. - #[arg(long, require_equals = true, value_name = "true|false")] - merge_imports_based_on_semver: Option>, + /// Possible values: `none`, `merge` (default), `canonical`. + #[arg(long, value_name = "MODE")] + semver_compat: Option, /// Whether or not to add debug names to the generated binary. #[arg(long, require_equals = true, value_name = "true|false")] @@ -554,8 +561,8 @@ impl LinkOpts { linker = linker.stack_size(stack_size); } - if let Some(merge) = self.merge_imports_based_on_semver { - linker = linker.merge_imports_based_on_semver(merge.unwrap_or(true)); + if let Some(compat) = self.semver_compat { + linker = linker.semver_compat(compat); } for (name, wasm) in &self.inputs {