Skip to content

Commit

Permalink
replace rustfmt with prettyplease for codegen (#971)
Browse files Browse the repository at this point in the history
* replace `rustfmt` with `prettyplease` for codegen

* rename the `rustfmt` cli option to `format`
  • Loading branch information
yoshuawuyts committed Jun 9, 2024
1 parent 76c5401 commit 58ade72
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 39 deletions.
21 changes: 17 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ heck = { version = "0.5" }
pulldown-cmark = { version = "0.9", default-features = false }
clap = { version = "4.3.19", features = ["derive"] }
indexmap = "2.0.0"
prettyplease = "0.2.20"
syn = { version = "2.0", features = ["printing"] }

wasmparser = "0.209.0"
wasm-encoder = "0.209.0"
Expand Down
4 changes: 4 additions & 0 deletions crates/core/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ impl Source {
pub fn as_mut_string(&mut self) -> &mut String {
&mut self.s
}

pub fn as_str(&self) -> &str {
&self.s
}
}

impl Write for Source {
Expand Down
4 changes: 3 additions & 1 deletion crates/guest-rust/macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ test = false

[dependencies]
proc-macro2 = "1.0"
syn = { version = "2.0", features = ["printing"] }
quote = "1"
wit-bindgen-core = { workspace = true }
wit-bindgen-rust = { workspace = true }
anyhow = { workspace = true }
syn = { workspace = true }
prettyplease = { workspace = true }

19 changes: 11 additions & 8 deletions crates/guest-rust/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,15 +191,12 @@ impl Config {
let n = INVOCATION.fetch_add(1, Relaxed);
let path = root.join(format!("{world_name}{n}.rs"));

std::fs::write(&path, &src).unwrap();

// optimistically format the code but don't require success
drop(
std::process::Command::new("rustfmt")
.arg(&path)
.arg("--edition=2021")
.output(),
);
let contents = match fmt(&src) {
Ok(formatted) => formatted,
Err(_) => src.clone(),
};
std::fs::write(&path, contents.as_bytes()).unwrap();

src = format!("include!({path:?});");
}
Expand Down Expand Up @@ -472,3 +469,9 @@ fn with_field_parse(input: ParseStream<'_>) -> Result<(String, String)> {

Ok((interface, buf))
}

/// Format a valid Rust string
fn fmt(input: &str) -> Result<String> {
let syntax_tree = syn::parse_file(&input)?;
Ok(prettyplease::unparse(&syntax_tree))
}
2 changes: 2 additions & 0 deletions crates/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ wasm-metadata = { workspace = true }
heck = { workspace = true }
clap = { workspace = true, optional = true }
indexmap = { workspace = true }
syn = { workspace = true }
prettyplease = { workspace = true }

[dev-dependencies]
wit-bindgen = { path = '../guest-rust' }
Expand Down
31 changes: 5 additions & 26 deletions crates/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ use heck::*;
use indexmap::IndexSet;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::{self, Write as _};
use std::io::{Read, Write};
use std::mem;
use std::process::{Command, Stdio};
use std::str::FromStr;
use wit_bindgen_core::abi::{Bitcast, WasmType};
use wit_bindgen_core::{
Expand Down Expand Up @@ -86,9 +84,9 @@ fn parse_with(s: &str) -> Result<(String, String), String> {
#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "clap", derive(clap::Args))]
pub struct Opts {
/// Whether or not `rustfmt` is executed to format generated code.
/// Whether or not a formatter is executed to format generated code.
#[cfg_attr(feature = "clap", arg(long))]
pub rustfmt: bool,
pub format: bool,

/// If true, code generation should qualify any features that depend on
/// `std` with `cfg(feature = "std")`.
Expand Down Expand Up @@ -1022,28 +1020,9 @@ impl WorldGenerator for RustWasm {
}

let mut src = mem::take(&mut self.src);
if self.opts.rustfmt {
let mut child = Command::new("rustfmt")
.arg("--edition=2018")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("failed to spawn `rustfmt`");
child
.stdin
.take()
.unwrap()
.write_all(src.as_bytes())
.unwrap();
src.as_mut_string().truncate(0);
child
.stdout
.take()
.unwrap()
.read_to_string(src.as_mut_string())
.unwrap();
let status = child.wait().unwrap();
assert!(status.success());
if self.opts.format {
let syntax_tree = syn::parse_file(src.as_str()).unwrap();
*src.as_mut_string() = prettyplease::unparse(&syntax_tree);
}

let module_name = name.to_snake_case();
Expand Down

0 comments on commit 58ade72

Please sign in to comment.