1 #include <gtest/gtest.h>
2 #include <wasmtime.h>
3 
4 #define CHECK(err)                                                             \
5   do {                                                                         \
6     if (err) {                                                                 \
7       auto msg = wasm_name_t{};                                                \
8       wasmtime_error_message(err, &msg);                                       \
9       EXPECT_EQ(err, nullptr) << std::string_view{msg.data, msg.size};         \
10     }                                                                          \
11   } while (false)
12 
13 TEST(component, define_module) {
14   static constexpr auto module_wat = std::string_view{
15       R"END(
16 (module
17     (func $function (param $x i32) (result i32)
18         local.get $x)
19     (export "function" (func $function))
20 )
21       )END",
22   };
23 
24   static constexpr auto component_text = std::string_view{
25       R"END(
26 (component
27     (import "x:y/z" (instance
28         (export "mod" (core module
29             (export "function" (func (param i32) (result i32)))
30         ))
31     ))
32 )
33       )END",
34   };
35   const auto engine = wasm_engine_new();
36   EXPECT_NE(engine, nullptr);
37 
38   wasm_byte_vec_t wasm;
39   auto err = wasmtime_wat2wasm(module_wat.data(), module_wat.size(), &wasm);
40   CHECK(err);
41 
42   wasmtime_module_t *module = nullptr;
43   err = wasmtime_module_new(
44       engine, reinterpret_cast<const uint8_t *>(wasm.data), wasm.size, &module);
45   CHECK(err);
46 
47   const auto store = wasmtime_store_new(engine, nullptr, nullptr);
48   const auto context = wasmtime_store_context(store);
49 
50   wasmtime_component_t *component = nullptr;
51 
52   err = wasmtime_component_new(
53       engine, reinterpret_cast<const uint8_t *>(component_text.data()),
54       component_text.size(), &component);
55 
56   CHECK(err);
57 
58   const auto linker = wasmtime_component_linker_new(engine);
59 
60   const auto root = wasmtime_component_linker_root(linker);
61 
62   wasmtime_component_linker_instance_t *x_y_z = nullptr;
63   err = wasmtime_component_linker_instance_add_instance(root, "x:y/z", &x_y_z);
64   CHECK(err);
65 
66   err = wasmtime_component_linker_instance_add_module(x_y_z, "mod", module);
67   CHECK(err);
68 
69   wasmtime_component_linker_instance_delete(x_y_z);
70   wasmtime_component_linker_instance_delete(root);
71 
72   wasmtime_component_instance_t instance = {};
73   err = wasmtime_component_linker_instantiate(linker, context, component,
74                                               &instance);
75   CHECK(err);
76 
77   wasmtime_component_linker_delete(linker);
78 
79   wasmtime_store_delete(store);
80   wasm_engine_delete(engine);
81 }
82