Skip to content

Commit

Permalink
Add a debugging utility for Rust generate!
Browse files Browse the repository at this point in the history
Lift the approach I added in bytecodealliance/wasmtime#7794
  • Loading branch information
alexcrichton committed Jan 31, 2024
1 parent f98a146 commit 9641a19
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
5 changes: 5 additions & 0 deletions crates/rust-macro/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fn main() {
println!("cargo:rerun-if-changed=build.rs");
let out_dir = std::env::var("OUT_DIR").unwrap();
println!("cargo:rustc-env=DEBUG_OUTPUT_DIR={out_dir}");
}
27 changes: 26 additions & 1 deletion crates/rust-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use proc_macro2::{Span, TokenStream};
use quote::ToTokens;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use syn::parse::{Error, Parse, ParseStream, Result};
use syn::punctuated::Punctuated;
use syn::{braced, token, Token};
Expand Down Expand Up @@ -154,7 +155,31 @@ impl Config {
.generate(&self.resolve, self.world, &mut files)
.map_err(|e| Error::new(Span::call_site(), e))?;
let (_, src) = files.iter().next().unwrap();
let src = std::str::from_utf8(src).unwrap();
let mut src = std::str::from_utf8(src).unwrap().to_string();

// If a magical `WIT_BINDGEN_DEBUG` environment variable is set 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.
if std::env::var("WIT_BINDGEN_DEBUG").is_ok() {
static INVOCATION: AtomicUsize = AtomicUsize::new(0);
let root = Path::new(env!("DEBUG_OUTPUT_DIR"));
let world_name = &self.resolve.worlds[self.world].name;
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(),
);

src = format!("include!({path:?});");
}
let mut contents = src.parse::<TokenStream>().unwrap();

// Include a dummy `include_str!` for any files we read so rustc knows that
Expand Down

0 comments on commit 9641a19

Please sign in to comment.