Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some clean-up work. #391

Merged
merged 6 commits into from
Oct 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ fn commit_info() {
let mut next = || parts.next().unwrap();
println!("cargo:rustc-env=CARGO_GIT_HASH={}", next());
println!(
"cargo:rustc-env=CARGO_VERSION_INFO={}",
format!("{} ({} {})", env!("CARGO_PKG_VERSION"), next(), next())
"cargo:rustc-env=CARGO_VERSION_INFO={} ({} {})",
env!("CARGO_PKG_VERSION"),
next(),
next()
);
}
2 changes: 1 addition & 1 deletion crates/bindgen-core/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub fn generate(
// will likely change as worlds are iterated on in the component model
// standard. Regardless though this is the step where types are learned
// and `Interface`s are constructed for further code generation below.
let interfaces = wit_component::decode_interface_component(binary)
let interfaces = wit_component::decode_component_interfaces(binary)
.context("failed to extract interface information from component")?;

// Components are complicated, there's no real way around that. To
Expand Down
12 changes: 6 additions & 6 deletions crates/bindgen-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ pub trait Generator {

for f in iface.functions.iter() {
match dir {
Direction::Import => self.import(iface, &f),
Direction::Export => self.export(iface, &f),
Direction::Import => self.import(iface, f),
Direction::Export => self.export(iface, f),
}
}

Expand Down Expand Up @@ -266,7 +266,7 @@ impl Types {
}
}
self.type_info.insert(ty, info);
return info;
info
}

pub fn type_info(&mut self, iface: &Interface, ty: &Type) -> TypeInfo {
Expand Down Expand Up @@ -415,7 +415,7 @@ impl Source {
let lines = src.lines().collect::<Vec<_>>();
for (i, line) in lines.iter().enumerate() {
let trimmed = line.trim();
if trimmed.starts_with("}") && self.s.ends_with(" ") {
if trimmed.starts_with('}') && self.s.ends_with(" ") {
self.s.pop();
self.s.pop();
}
Expand All @@ -434,7 +434,7 @@ impl Source {
// looking at the source code rather than getting a panic.
self.indent = self.indent.saturating_sub(1);
}
if i != lines.len() - 1 || src.ends_with("\n") {
if i != lines.len() - 1 || src.ends_with('\n') {
self.newline();
}
}
Expand All @@ -449,7 +449,7 @@ impl Source {
}

fn newline(&mut self) {
self.s.push_str("\n");
self.s.push('\n');
for _ in 0..self.indent {
self.s.push_str(" ");
}
Expand Down
10 changes: 6 additions & 4 deletions crates/gen-guest-c/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1098,6 +1098,10 @@ impl Generator for C {

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

// Currently the C generator always emits default exports
// This needs to change once the generator works from a world
let export_name = iface.core_export_name(true, func);

// Print the actual header for this function into the header file, and
// it's what we'll be calling.
let c_sig = self.print_sig(iface, func);
Expand All @@ -1106,8 +1110,7 @@ impl Generator for C {
// canonical ABI.
uwriteln!(
self.src.c_adapters,
"\n__attribute__((export_name(\"{}\")))",
func.name
"__attribute__((export_name(\"{export_name}\")))"
);
let import_name = self.names.tmp(&format!(
"__wasm_export_{}_{}",
Expand Down Expand Up @@ -1151,8 +1154,7 @@ impl Generator for C {
if iface.guest_export_needs_post_return(func) {
uwriteln!(
self.src.c_fns,
"\n__attribute__((weak, export_name(\"cabi_post_{}\")))",
func.name
"__attribute__((export_name(\"cabi_post_{export_name}\")))"
);
uwrite!(self.src.c_fns, "void {import_name}_post_return(");

Expand Down
37 changes: 11 additions & 26 deletions crates/gen-guest-rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ pub struct Opts {
#[cfg_attr(feature = "clap", arg(long))]
pub unchecked: bool,

/// A prefix to prepend to all exported symbols. Note that this is only
/// intended for testing because it breaks the general form of the ABI.
#[cfg_attr(feature = "clap", arg(skip))]
pub symbol_namespace: String,

/// If true, code generation should avoid any features that depend on `std`.
#[cfg_attr(feature = "clap", arg(long))]
pub no_std: bool,
Expand Down Expand Up @@ -106,12 +101,12 @@ impl WorldGenerator for RustWasm {

fn export(&mut self, name: &str, iface: &Interface, _files: &mut Files) {
self.interface(iface, TypeMode::Owned, false)
.generate_exports(name);
.generate_exports(name, false);
}

fn export_default(&mut self, name: &str, iface: &Interface, _files: &mut Files) {
self.interface(iface, TypeMode::Owned, false)
.generate_exports(name);
.generate_exports(name, true);
}

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

impl InterfaceGenerator<'_> {
fn generate_exports(mut self, name: &str) {
fn generate_exports(mut self, name: &str, default_export: bool) {
self.types();

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

for func in self.iface.functions.iter() {
self.generate_guest_export(name, func);
self.generate_guest_export(name, func, default_export);
}

self.append_submodule(name);
Expand Down Expand Up @@ -301,18 +296,12 @@ impl InterfaceGenerator<'_> {
}
}

fn generate_guest_export(&mut self, module_name: &str, func: &Function) {
fn generate_guest_export(&mut self, module_name: &str, func: &Function, default_export: bool) {
let module_name = module_name.to_snake_case();
let trait_bound = module_name.to_upper_camel_case();
let iface_snake = self.iface.name.to_snake_case();
let name_snake = func.name.to_snake_case();
let name = match &self.iface.module {
Some(module) => {
format!("{module}#{}", func.name)
}
None => format!("{}{}", self.gen.opts.symbol_namespace, func.name),
};

let export_name = self.iface.core_export_name(default_export, func);
let mut macro_src = Source::default();

// Generate, simultaneously, the actual lifting/lowering function within
Expand All @@ -333,7 +322,7 @@ impl InterfaceGenerator<'_> {
uwrite!(
macro_src,
"
#[export_name = \"{name}\"]
#[export_name = \"{export_name}\"]
unsafe extern \"C\" fn export_{iface_snake}_{name_snake}(\
",
);
Expand Down Expand Up @@ -397,11 +386,9 @@ impl InterfaceGenerator<'_> {
uwrite!(
macro_src,
"
#[export_name = \"{}cabi_post_{}\"]
#[export_name = \"cabi_post_{export_name}\"]
pub unsafe extern \"C\" fn post_return_{iface_snake}_{name_snake}(\
",
self.gen.opts.symbol_namespace,
func.name,
"
);
let mut params = Vec::new();
for (i, result) in sig.results.iter().enumerate() {
Expand Down Expand Up @@ -620,18 +607,16 @@ impl<'a, 'b> FunctionBindgen<'a, 'b> {
params: &[WasmType],
results: &[WasmType],
) -> String {
let module = iface.module.as_deref().unwrap_or(&iface.name);

// Define the actual function we're calling inline
self.push_str("#[link(wasm_import_module = \"");
self.push_str(module);
self.push_str(&iface.name);
self.push_str("\")]\n");
self.push_str("extern \"C\" {\n");
self.push_str("#[cfg_attr(target_arch = \"wasm32\", link_name = \"");
self.push_str(name);
self.push_str("\")]\n");
self.push_str("#[cfg_attr(not(target_arch = \"wasm32\"), link_name = \"");
self.push_str(module);
self.push_str(&iface.name);
self.push_str("_");
self.push_str(name);
self.push_str("\")]\n");
Expand Down
11 changes: 6 additions & 5 deletions crates/gen-guest-teavm-java/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,10 @@ impl Generator for TeaVmJava {
fn export(&mut self, iface: &Interface, func: &Function) {
let sig = iface.wasm_signature(AbiVariant::GuestExport, func);

// Currently the Java generator always emits default exports
// This needs to change once the generator works from a world
let export_name = iface.core_export_name(true, func);

let mut bindgen = FunctionBindgen::new(
self,
&func.name,
Expand All @@ -661,7 +665,6 @@ impl Generator for TeaVmJava {
assert!(!bindgen.needs_cleanup_list);

let src = bindgen.src;
let name = &func.name;

let result_type = match &sig.results[..] {
[] => "void",
Expand All @@ -685,16 +688,14 @@ impl Generator for TeaVmJava {
uwrite!(
self.src,
r#"
@Export(name = "{name}")
@Export(name = "{export_name}")
private static {result_type} wasmExport{camel_name}({params}) {{
{src}
}}
"#
);

if iface.guest_export_needs_post_return(func) {
let name = &func.name;

let params = sig
.results
.iter()
Expand All @@ -719,7 +720,7 @@ impl Generator for TeaVmJava {
uwrite!(
self.src,
r#"
@Export(name = "cabi_post_{name}")
@Export(name = "cabi_post_{export_name}")
private static void wasmExport{camel_name}PostReturn({params}) {{
{src}
}}
Expand Down
8 changes: 3 additions & 5 deletions crates/wit-component/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
//! The WebAssembly component tool command line interface.

#![deny(missing_docs)]

use crate::extract::{extract_module_interfaces, ModuleInterfaces};
use crate::{
decode_interface_component, ComponentEncoder, ComponentInterfaces, InterfacePrinter,
decode_component_interfaces, ComponentEncoder, ComponentInterfaces, InterfacePrinter,
StringEncoding,
};
use anyhow::{anyhow, bail, Context, Result};
Expand Down Expand Up @@ -71,7 +69,7 @@ fn parse_adapter(s: &str) -> Result<(String, Vec<u8>, Interface)> {
default,
},
} = extract_module_interfaces(&wasm)?;
if exports.len() > 0 || default.is_some() {
if !exports.is_empty() || default.is_some() {
bail!("adapter modules cannot have an exported interface");
}
let import = match imports.len() {
Expand Down Expand Up @@ -233,7 +231,7 @@ impl WasmToWitApp {
let bytes = wat::parse_file(&self.component)
.with_context(|| format!("failed to parse component `{}`", self.component.display()))?;

let interfaces = decode_interface_component(&bytes).with_context(|| {
let interfaces = decode_component_interfaces(&bytes).with_context(|| {
format!("failed to decode component `{}`", self.component.display())
})?;
let which = match &self.import {
Expand Down
10 changes: 5 additions & 5 deletions crates/wit-component/src/decoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ struct InterfaceDecoder<'a> {
#[derive(Default)]
pub struct ComponentInterfaces {
/// The "default export" which is the interface directly exported from the
/// component at the first level.
/// component at the top level.
pub default: Option<Interface>,
/// Imported interfaces, keyed by name, to the component.
/// Imported interfaces, keyed by name, of the component.
pub imports: IndexMap<String, Interface>,
/// Exported interfaces, keyed by name, to the component.
/// Exported interfaces, keyed by name, of the component.
pub exports: IndexMap<String, Interface>,
}

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

// Iterate over all exports an interpret them as defined items within
// the interface, either functiosn or types at this time.
// the interface, either functions or types at this time.
for (name, ty) in map {
match ty {
types::ComponentEntityType::Func(ty) => {
Expand Down
Loading