Skip to content

Commit 5be459e

Browse files
authored
Some clean-up work. (bytecodealliance#391)
* Fix some typos and linter warnings. This commit fixes some random comment typos and various linter warnings. * wit-component: rename `decode_interface_component`. This commit renames `decode_interface_component` to `decode_component_interfaces` to better describe what the function does. Previously it was meant to decode an "interface-only" component, but now it returns all the interfaces (i.e. the "world") of the component. * wit-component: implement multi-value return printing. This commit implements printing of multi-value returns of interfaces decoded from a component. * Remove `module` field from `Interface`. The `module` field was originally used by `cargo component` but is no longer necessary and otherwise unused from `wit-bindgen` itself. * Remove `symbol_namespace` from Rust generator. This field is no longer used anywhere in the wit-bindgen repo. * Add method to `Interface` for determining core export names. This commit extracts the expected core export name out of `wit-component` and into `Interface`, allowing generators to conform to the name expected by `wit-component`.
1 parent 0cde4dc commit 5be459e

File tree

20 files changed

+123
-131
lines changed

20 files changed

+123
-131
lines changed

Diff for: build.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ fn commit_info() {
2626
let mut next = || parts.next().unwrap();
2727
println!("cargo:rustc-env=CARGO_GIT_HASH={}", next());
2828
println!(
29-
"cargo:rustc-env=CARGO_VERSION_INFO={}",
30-
format!("{} ({} {})", env!("CARGO_PKG_VERSION"), next(), next())
29+
"cargo:rustc-env=CARGO_VERSION_INFO={} ({} {})",
30+
env!("CARGO_PKG_VERSION"),
31+
next(),
32+
next()
3133
);
3234
}

Diff for: crates/bindgen-core/src/component.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ pub fn generate(
3131
// will likely change as worlds are iterated on in the component model
3232
// standard. Regardless though this is the step where types are learned
3333
// and `Interface`s are constructed for further code generation below.
34-
let interfaces = wit_component::decode_interface_component(binary)
34+
let interfaces = wit_component::decode_component_interfaces(binary)
3535
.context("failed to extract interface information from component")?;
3636

3737
// Components are complicated, there's no real way around that. To

Diff for: crates/bindgen-core/src/lib.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ pub trait Generator {
139139

140140
for f in iface.functions.iter() {
141141
match dir {
142-
Direction::Import => self.import(iface, &f),
143-
Direction::Export => self.export(iface, &f),
142+
Direction::Import => self.import(iface, f),
143+
Direction::Export => self.export(iface, f),
144144
}
145145
}
146146

@@ -266,7 +266,7 @@ impl Types {
266266
}
267267
}
268268
self.type_info.insert(ty, info);
269-
return info;
269+
info
270270
}
271271

272272
pub fn type_info(&mut self, iface: &Interface, ty: &Type) -> TypeInfo {
@@ -415,7 +415,7 @@ impl Source {
415415
let lines = src.lines().collect::<Vec<_>>();
416416
for (i, line) in lines.iter().enumerate() {
417417
let trimmed = line.trim();
418-
if trimmed.starts_with("}") && self.s.ends_with(" ") {
418+
if trimmed.starts_with('}') && self.s.ends_with(" ") {
419419
self.s.pop();
420420
self.s.pop();
421421
}
@@ -434,7 +434,7 @@ impl Source {
434434
// looking at the source code rather than getting a panic.
435435
self.indent = self.indent.saturating_sub(1);
436436
}
437-
if i != lines.len() - 1 || src.ends_with("\n") {
437+
if i != lines.len() - 1 || src.ends_with('\n') {
438438
self.newline();
439439
}
440440
}
@@ -449,7 +449,7 @@ impl Source {
449449
}
450450

451451
fn newline(&mut self) {
452-
self.s.push_str("\n");
452+
self.s.push('\n');
453453
for _ in 0..self.indent {
454454
self.s.push_str(" ");
455455
}

Diff for: crates/gen-guest-c/src/lib.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -1098,6 +1098,10 @@ impl Generator for C {
10981098

10991099
let sig = iface.wasm_signature(AbiVariant::GuestExport, func);
11001100

1101+
// Currently the C generator always emits default exports
1102+
// This needs to change once the generator works from a world
1103+
let export_name = iface.core_export_name(true, func);
1104+
11011105
// Print the actual header for this function into the header file, and
11021106
// it's what we'll be calling.
11031107
let c_sig = self.print_sig(iface, func);
@@ -1106,8 +1110,7 @@ impl Generator for C {
11061110
// canonical ABI.
11071111
uwriteln!(
11081112
self.src.c_adapters,
1109-
"\n__attribute__((export_name(\"{}\")))",
1110-
func.name
1113+
"__attribute__((export_name(\"{export_name}\")))"
11111114
);
11121115
let import_name = self.names.tmp(&format!(
11131116
"__wasm_export_{}_{}",
@@ -1151,8 +1154,7 @@ impl Generator for C {
11511154
if iface.guest_export_needs_post_return(func) {
11521155
uwriteln!(
11531156
self.src.c_fns,
1154-
"\n__attribute__((weak, export_name(\"cabi_post_{}\")))",
1155-
func.name
1157+
"__attribute__((export_name(\"cabi_post_{export_name}\")))"
11561158
);
11571159
uwrite!(self.src.c_fns, "void {import_name}_post_return(");
11581160

Diff for: crates/gen-guest-rust/src/lib.rs

+11-26
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,6 @@ pub struct Opts {
3232
#[cfg_attr(feature = "clap", arg(long))]
3333
pub unchecked: bool,
3434

35-
/// A prefix to prepend to all exported symbols. Note that this is only
36-
/// intended for testing because it breaks the general form of the ABI.
37-
#[cfg_attr(feature = "clap", arg(skip))]
38-
pub symbol_namespace: String,
39-
4035
/// If true, code generation should avoid any features that depend on `std`.
4136
#[cfg_attr(feature = "clap", arg(long))]
4237
pub no_std: bool,
@@ -106,12 +101,12 @@ impl WorldGenerator for RustWasm {
106101

107102
fn export(&mut self, name: &str, iface: &Interface, _files: &mut Files) {
108103
self.interface(iface, TypeMode::Owned, false)
109-
.generate_exports(name);
104+
.generate_exports(name, false);
110105
}
111106

112107
fn export_default(&mut self, name: &str, iface: &Interface, _files: &mut Files) {
113108
self.interface(iface, TypeMode::Owned, false)
114-
.generate_exports(name);
109+
.generate_exports(name, true);
115110
}
116111

117112
fn finish(&mut self, name: &str, interfaces: &ComponentInterfaces, files: &mut Files) {
@@ -214,7 +209,7 @@ struct InterfaceGenerator<'a> {
214209
}
215210

216211
impl InterfaceGenerator<'_> {
217-
fn generate_exports(mut self, name: &str) {
212+
fn generate_exports(mut self, name: &str, default_export: bool) {
218213
self.types();
219214

220215
let camel = name.to_upper_camel_case();
@@ -228,7 +223,7 @@ impl InterfaceGenerator<'_> {
228223
uwriteln!(self.src, "}}");
229224

230225
for func in self.iface.functions.iter() {
231-
self.generate_guest_export(name, func);
226+
self.generate_guest_export(name, func, default_export);
232227
}
233228

234229
self.append_submodule(name);
@@ -301,18 +296,12 @@ impl InterfaceGenerator<'_> {
301296
}
302297
}
303298

304-
fn generate_guest_export(&mut self, module_name: &str, func: &Function) {
299+
fn generate_guest_export(&mut self, module_name: &str, func: &Function, default_export: bool) {
305300
let module_name = module_name.to_snake_case();
306301
let trait_bound = module_name.to_upper_camel_case();
307302
let iface_snake = self.iface.name.to_snake_case();
308303
let name_snake = func.name.to_snake_case();
309-
let name = match &self.iface.module {
310-
Some(module) => {
311-
format!("{module}#{}", func.name)
312-
}
313-
None => format!("{}{}", self.gen.opts.symbol_namespace, func.name),
314-
};
315-
304+
let export_name = self.iface.core_export_name(default_export, func);
316305
let mut macro_src = Source::default();
317306

318307
// Generate, simultaneously, the actual lifting/lowering function within
@@ -333,7 +322,7 @@ impl InterfaceGenerator<'_> {
333322
uwrite!(
334323
macro_src,
335324
"
336-
#[export_name = \"{name}\"]
325+
#[export_name = \"{export_name}\"]
337326
unsafe extern \"C\" fn export_{iface_snake}_{name_snake}(\
338327
",
339328
);
@@ -397,11 +386,9 @@ impl InterfaceGenerator<'_> {
397386
uwrite!(
398387
macro_src,
399388
"
400-
#[export_name = \"{}cabi_post_{}\"]
389+
#[export_name = \"cabi_post_{export_name}\"]
401390
pub unsafe extern \"C\" fn post_return_{iface_snake}_{name_snake}(\
402-
",
403-
self.gen.opts.symbol_namespace,
404-
func.name,
391+
"
405392
);
406393
let mut params = Vec::new();
407394
for (i, result) in sig.results.iter().enumerate() {
@@ -620,18 +607,16 @@ impl<'a, 'b> FunctionBindgen<'a, 'b> {
620607
params: &[WasmType],
621608
results: &[WasmType],
622609
) -> String {
623-
let module = iface.module.as_deref().unwrap_or(&iface.name);
624-
625610
// Define the actual function we're calling inline
626611
self.push_str("#[link(wasm_import_module = \"");
627-
self.push_str(module);
612+
self.push_str(&iface.name);
628613
self.push_str("\")]\n");
629614
self.push_str("extern \"C\" {\n");
630615
self.push_str("#[cfg_attr(target_arch = \"wasm32\", link_name = \"");
631616
self.push_str(name);
632617
self.push_str("\")]\n");
633618
self.push_str("#[cfg_attr(not(target_arch = \"wasm32\"), link_name = \"");
634-
self.push_str(module);
619+
self.push_str(&iface.name);
635620
self.push_str("_");
636621
self.push_str(name);
637622
self.push_str("\")]\n");

Diff for: crates/gen-guest-teavm-java/src/lib.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,10 @@ impl Generator for TeaVmJava {
645645
fn export(&mut self, iface: &Interface, func: &Function) {
646646
let sig = iface.wasm_signature(AbiVariant::GuestExport, func);
647647

648+
// Currently the Java generator always emits default exports
649+
// This needs to change once the generator works from a world
650+
let export_name = iface.core_export_name(true, func);
651+
648652
let mut bindgen = FunctionBindgen::new(
649653
self,
650654
&func.name,
@@ -661,7 +665,6 @@ impl Generator for TeaVmJava {
661665
assert!(!bindgen.needs_cleanup_list);
662666

663667
let src = bindgen.src;
664-
let name = &func.name;
665668

666669
let result_type = match &sig.results[..] {
667670
[] => "void",
@@ -685,16 +688,14 @@ impl Generator for TeaVmJava {
685688
uwrite!(
686689
self.src,
687690
r#"
688-
@Export(name = "{name}")
691+
@Export(name = "{export_name}")
689692
private static {result_type} wasmExport{camel_name}({params}) {{
690693
{src}
691694
}}
692695
"#
693696
);
694697

695698
if iface.guest_export_needs_post_return(func) {
696-
let name = &func.name;
697-
698699
let params = sig
699700
.results
700701
.iter()
@@ -719,7 +720,7 @@ impl Generator for TeaVmJava {
719720
uwrite!(
720721
self.src,
721722
r#"
722-
@Export(name = "cabi_post_{name}")
723+
@Export(name = "cabi_post_{export_name}")
723724
private static void wasmExport{camel_name}PostReturn({params}) {{
724725
{src}
725726
}}

Diff for: crates/wit-component/src/cli.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
//! The WebAssembly component tool command line interface.
22
3-
#![deny(missing_docs)]
4-
53
use crate::extract::{extract_module_interfaces, ModuleInterfaces};
64
use crate::{
7-
decode_interface_component, ComponentEncoder, ComponentInterfaces, InterfacePrinter,
5+
decode_component_interfaces, ComponentEncoder, ComponentInterfaces, InterfacePrinter,
86
StringEncoding,
97
};
108
use anyhow::{anyhow, bail, Context, Result};
@@ -71,7 +69,7 @@ fn parse_adapter(s: &str) -> Result<(String, Vec<u8>, Interface)> {
7169
default,
7270
},
7371
} = extract_module_interfaces(&wasm)?;
74-
if exports.len() > 0 || default.is_some() {
72+
if !exports.is_empty() || default.is_some() {
7573
bail!("adapter modules cannot have an exported interface");
7674
}
7775
let import = match imports.len() {
@@ -233,7 +231,7 @@ impl WasmToWitApp {
233231
let bytes = wat::parse_file(&self.component)
234232
.with_context(|| format!("failed to parse component `{}`", self.component.display()))?;
235233

236-
let interfaces = decode_interface_component(&bytes).with_context(|| {
234+
let interfaces = decode_component_interfaces(&bytes).with_context(|| {
237235
format!("failed to decode component `{}`", self.component.display())
238236
})?;
239237
let which = match &self.import {

Diff for: crates/wit-component/src/decoding.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,11 @@ struct InterfaceDecoder<'a> {
9191
#[derive(Default)]
9292
pub struct ComponentInterfaces {
9393
/// The "default export" which is the interface directly exported from the
94-
/// component at the first level.
94+
/// component at the top level.
9595
pub default: Option<Interface>,
96-
/// Imported interfaces, keyed by name, to the component.
96+
/// Imported interfaces, keyed by name, of the component.
9797
pub imports: IndexMap<String, Interface>,
98-
/// Exported interfaces, keyed by name, to the component.
98+
/// Exported interfaces, keyed by name, of the component.
9999
pub exports: IndexMap<String, Interface>,
100100
}
101101

@@ -112,7 +112,7 @@ pub struct ComponentInterfaces {
112112
///
113113
/// This can fail if the input component is invalid or otherwise isn't of the
114114
/// expected shape. At this time not all component shapes are supported here.
115-
pub fn decode_interface_component(bytes: &[u8]) -> Result<ComponentInterfaces> {
115+
pub fn decode_component_interfaces(bytes: &[u8]) -> Result<ComponentInterfaces> {
116116
let info = ComponentInfo::new(bytes)?;
117117
let mut imports = IndexMap::new();
118118
let mut exports = IndexMap::new();
@@ -224,7 +224,7 @@ impl<'a> InterfaceDecoder<'a> {
224224
}
225225

226226
// Iterate over all exports an interpret them as defined items within
227-
// the interface, either functiosn or types at this time.
227+
// the interface, either functions or types at this time.
228228
for (name, ty) in map {
229229
match ty {
230230
types::ComponentEntityType::Func(ty) => {

0 commit comments

Comments
 (0)