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            .clone()
45            .unwrap_or_else(|| self.module.with_extension("explore.html"));
46        let output_file = std::fs::File::create(&output)
47            .with_context(|| format!("failed to create file: {}", output.display()))?;
48        let mut output_file = std::io::BufWriter::new(output_file);
49
50        let clif_dir = if let Some(Strategy::Cranelift) | None = self.common.codegen.compiler {
51            let clif_dir = tempdir()?;
52            config.emit_clif(clif_dir.path());
53            config.cache(None); // cache does not emit clif
54            Some(clif_dir)
55        } else {
56            None
57        };
58
59        wasmtime_explorer::generate(
60            &config,
61            self.common.target.as_deref(),
62            clif_dir.as_ref().map(|tmp_dir| tmp_dir.path()),
63            &bytes,
64            &mut output_file,
65        )?;
66
67        println!("Exploration written to {}", output.display());
68        Ok(())
69    }
70}