Skip to main content

wasmtime_cli/commands/
explore.rs

1//! The module that implements the `wasmtime explore` command.
2
3use clap::Parser;
4use std::{borrow::Cow, path::PathBuf};
5use tempfile::tempdir;
6use wasmtime::{Result, Strategy, error::Context as _};
7use wasmtime_cli_flags::CommonOptions;
8
9/// Explore the compilation of a WebAssembly module to native code.
10#[derive(Parser)]
11pub struct ExploreCommand {
12    #[command(flatten)]
13    common: CommonOptions,
14
15    /// The path of the WebAssembly module to compile
16    #[arg(required = true, value_name = "MODULE")]
17    module: PathBuf,
18
19    /// The path of the explorer output (derived from the MODULE name if none
20    /// provided)
21    #[arg(short, long)]
22    output: Option<PathBuf>,
23}
24
25impl ExploreCommand {
26    /// Executes the command.
27    pub fn execute(mut self) -> Result<()> {
28        self.common.init_logging()?;
29
30        let mut config = self.common.config(None)?;
31
32        let bytes =
33            Cow::Owned(std::fs::read(&self.module).with_context(|| {
34                format!("failed to read Wasm module: {}", self.module.display())
35            })?);
36        #[cfg(feature = "wat")]
37        let bytes = wat::parse_bytes(&bytes).map_err(|mut e| {
38            e.set_path(&self.module);
39            e
40        })?;
41
42        let output = self
43            .output
44            .unwrap_or_else(|| self.module.with_extension("explore.html"));
45        let output_file = std::fs::File::create(&output)
46            .with_context(|| format!("failed to create file: {}", output.display()))?;
47        let mut output_file = std::io::BufWriter::new(output_file);
48
49        let clif_dir = if let Some(Strategy::Cranelift) | None = self.common.codegen.compiler {
50            let clif_dir = tempdir()?;
51            config.emit_clif(clif_dir.path());
52            config.cache(None); // cache does not emit clif
53            Some(clif_dir)
54        } else {
55            None
56        };
57
58        wasmtime_explorer::generate(
59            &config,
60            self.common.target.as_deref(),
61            clif_dir.as_ref().map(|tmp_dir| tmp_dir.path()),
62            &bytes,
63            &mut output_file,
64        )?;
65
66        println!("Exploration written to {}", output.display());
67        Ok(())
68    }
69}