A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Revert part of #15000, allow mixing imports/exports (#15165)
Alex Crichtonbe5af2b57323
diff --git a/crates/component-macro/src/bindgen.rs b/crates/component-macro/src/bindgen.rsindex 7bd65741ac..1657e7472e 100644--- a/crates/component-macro/src/bindgen.rs+++ b/crates/component-macro/src/bindgen.rs@@ -10,7 +10,7 @@ use syn::{Token, braced, token};use wasmtime_wit_bindgen::{FunctionConfig, FunctionFilter, FunctionFlags, Opts, Ownership, TrappableError,};-use wit_parser::{Function, IndexMap, PackageId, Resolve, WorldId, WorldItem, WorldKey};+use wit_parser::{PackageId, Resolve, WorldId};pub struct Config {opts: Opts,@@ -30,8 +30,6 @@ pub fn expand(input: &mut Config) -> Result<TokenStream> {return Ok(quote::quote!(#src));}- check_for_sync_exports_and_async_imports(input)?;-// If debugging is enabled then place a formatted version of the expanded// code into a file. This file will then show up in rustc error messages for// any codegen issues and can be inspected manually.@@ -140,67 +138,6 @@ impl Config {}}-fn check_for_sync_exports_and_async_imports(input: &Config) -> Result<()> {- let world = &input.resolve.worlds[input.world];- let async_imports =- filter_function_names(&input.resolve, &world.imports, |f| f.kind.is_async());- let sync_exports =- filter_function_names(&input.resolve, &world.exports, |f| !f.kind.is_async());-- if !sync_exports.is_empty() && !async_imports.is_empty() {- let format_list = |names: &[String]| {- names- .iter()- .map(|n| format!(" - {n}\n"))- .collect::<String>()- };-- return Err(Error::new(- Span::call_site(),- format!(- "World `{world}` mixes synchronous exports with asynchronous imports, which is not allowed.\n\- \n\- synchronous exports:\n{sync_exports}\n\- asynchronous imports:\n{async_imports}\n\- help: This error will resolve if either all imports are non-async or all exports \- are async. For more details, see the async bindgen example:\n\- https://docs.wasmtime.dev/api/wasmtime/component/bindgen_examples/_7_async/index.html",- world = world.name,- sync_exports = format_list(&sync_exports),- async_imports = format_list(&async_imports),- ),- ));- }-- Ok(())-}--/// Get a list of world and interface-level function names that match some predicate-fn filter_function_names(- resolve: &Resolve,- items: &IndexMap<WorldKey, WorldItem>,- pred: impl Fn(&Function) -> bool,-) -> Vec<String> {- let mut names = vec![];- for (key, item) in items {- match item {- WorldItem::Function(f) if pred(f) => names.push(f.name.clone()),- WorldItem::Interface { id, .. } => {- let iface = resolve.name_world_key(key);- names.extend(- resolve.interfaces[*id]- .functions- .values()- .filter(|f| pred(f))- .map(|f| format!("{iface}.{}", f.name)),- );- }- _ => {}- }- }- names-}-impl Parse for Config {fn parse(input: ParseStream<'_>) -> Result<Self> {let call_site = Span::call_site();diff --git a/tests/all/component_model/bindgen.rs b/tests/all/component_model/bindgen.rsindex 673b678ef5..e4f3bf16a4 100644--- a/tests/all/component_model/bindgen.rs+++ b/tests/all/component_model/bindgen.rs@@ -292,6 +292,99 @@ mod one_import_concurrent {}}+mod sync_export_async_import {+ use super::*;+ use wasmtime::Trap;+ use wasmtime::component::{Accessor, HasData};++ wasmtime::component::bindgen!({+ inline: "+ package foo:foo;++ world sync-export-async-import {+ import foo: interface {+ foo: async func(block: bool);+ }++ export bar: func(block: bool);+ }+ ",+ exports: { default: async },+ });++ const COMPONENT: &str = r#"+ (component+ (import "foo" (instance $foo-instance+ (export "foo" (func async (param "block" bool)))+ ))+ (core func $foo (canon lower (func $foo-instance "foo")))+ (core module $m+ (import "" "foo" (func $foo (param i32)))+ (func (export "bar") (param i32)+ local.get 0+ call $foo+ )+ )+ (core instance $i (instantiate $m+ (with "" (instance (export "foo" (func $foo))))+ ))+ (func (export "bar") (param "block" bool)+ (canon lift (core func $i "bar"))+ )+ )+ "#;++ #[derive(Default)]+ struct MyImports {+ hit: bool,+ }++ impl HasData for MyImports {+ type Data<'a> = &'a mut MyImports;+ }++ impl<T> foo::HostWithStore<T> for MyImports {+ async fn foo(accessor: &Accessor<T, Self>, block: bool) {+ if block {+ std::future::pending::<()>().await;+ }+ accessor.with(|mut view| view.get().hit = true);+ }+ }++ impl foo::Host for MyImports {}++ async fn setup() -> Result<(Store<MyImports>, SyncExportAsyncImport)> {+ let mut config = Config::new();+ config.wasm_component_model_async(true);+ let engine = Engine::new(&config)?;+ let component = Component::new(&engine, COMPONENT)?;+ let mut linker = Linker::new(&engine);+ foo::add_to_linker::<_, MyImports>(&mut linker, |x| x)?;+ let mut store = Store::new(&engine, MyImports::default());+ let instance =+ SyncExportAsyncImport::instantiate_async(&mut store, &component, &linker).await?;+ Ok((store, instance))+ }++ #[tokio::test]+ async fn non_blocking() -> Result<()> {+ let (mut store, instance) = setup().await?;+ instance.call_bar(&mut store, false).await?;+ assert!(store.data().hit);+ Ok(())+ }++ #[tokio::test]+ async fn blocking_traps() -> Result<()> {+ let (mut store, instance) = setup().await?;+ let err = instance.call_bar(&mut store, true).await.unwrap_err();+ assert_eq!(err.downcast_ref::<Trap>(), Some(&Trap::CannotBlockSyncTask));+ assert!(!store.data().hit);+ Ok(())+ }+}+mod resources_at_world_level {use super::*;use wasmtime::component::{HasSelf, Resource};