1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! Defines WasmEdge ahead-of-time compiler.

use crate::{config::Config, WasmEdgeResult};
use std::path::{Path, PathBuf};
use wasmedge_sys as sys;

/// Defines WasmEdge ahead-of-time(AOT) compiler and the relevant APIs.
#[derive(Debug)]
pub struct Compiler {
    pub(crate) inner: sys::Compiler,
}
impl Compiler {
    /// Creates a new AOT compiler.
    ///
    /// # Error
    ///
    /// If fail to create a AOT compiler, then an error is returned.
    pub fn new(config: Option<&Config>) -> WasmEdgeResult<Self> {
        let inner = match config {
            Some(cfg) => sys::Compiler::create(Some(&cfg.inner))?,
            None => sys::Compiler::create(None)?,
        };

        Ok(Self { inner })
    }

    /// Compiles the given wasm file into a shared library file (*.so in Linux, *.dylib in macOS, or *.dll in Windows). The file path of the generated shared library file will be returned if the method works successfully.
    ///
    /// # Arguments
    ///
    /// * `wasm_file` - The target wasm file.
    ///
    /// * `filename` - The filename of the generated shared library file.
    ///
    /// * `out_dir` - The target directory to save the generated shared library file.
    ///
    /// # Error
    ///
    /// If fail to compile, then an error is returned.
    pub fn compile_from_file(
        &self,
        wasm_file: impl AsRef<Path>,
        filename: impl AsRef<str>,
        out_dir: impl AsRef<Path>,
    ) -> WasmEdgeResult<PathBuf> {
        #[cfg(target_os = "linux")]
        let extension = "so";
        #[cfg(target_os = "macos")]
        let extension = "dylib";
        #[cfg(target_os = "windows")]
        let extension = "dll";
        let aot_file = out_dir
            .as_ref()
            .join(format!("{}.{}", filename.as_ref(), extension));
        self.inner.compile_from_file(wasm_file, &aot_file)?;

        Ok(aot_file)
    }

    /// Compiles the given wasm bytes into a shared library file (*.so in Linux, *.dylib in macOS, or *.dll in Windows). The file path of the generated shared library file will be returned if the method works successfully.
    ///
    /// # Argument
    ///
    /// * `bytes` - A in-memory WASM bytes.
    ///
    /// * `filename` - The filename of the generated shared library file.
    ///
    /// * `out_dir` - The target directory to save the generated shared library file.
    ///
    /// # Error
    ///
    /// If fail to compile, then an error is returned.
    pub fn compile_from_bytes(
        &self,
        bytes: impl AsRef<[u8]>,
        filename: impl AsRef<str>,
        out_dir: impl AsRef<Path>,
    ) -> WasmEdgeResult<PathBuf> {
        #[cfg(target_os = "linux")]
        let extension = "so";
        #[cfg(target_os = "macos")]
        let extension = "dylib";
        #[cfg(target_os = "windows")]
        let extension = "dll";
        let aot_file = out_dir
            .as_ref()
            .join(format!("{}.{}", filename.as_ref(), extension));
        self.inner.compile_from_bytes(bytes, &aot_file)?;

        Ok(aot_file)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        config::{CompilerConfigOptions, ConfigBuilder},
        params, wat2wasm, CompilerOutputFormat, VmBuilder, WasmVal,
    };
    use std::io::Read;

    #[test]
    fn test_compiler_compile_from_file() -> Result<(), Box<dyn std::error::Error>> {
        // compile from file
        {
            let config = ConfigBuilder::default()
                .with_compiler_config(
                    CompilerConfigOptions::new().out_format(CompilerOutputFormat::Native),
                )
                .build()?;

            let compiler = Compiler::new(Some(&config))?;
            let wasm_file = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
                .join("bindings/rust/wasmedge-sdk/examples/data/fibonacci.wat");
            let out_dir = std::env::current_dir()?;
            let aot_filename = "aot_fibonacci_1";
            let aot_file_path = compiler.compile_from_file(wasm_file, aot_filename, out_dir)?;
            assert!(aot_file_path.exists());
            #[cfg(target_os = "macos")]
            assert!(aot_file_path.ends_with("aot_fibonacci_1.dylib"));
            #[cfg(target_os = "linux")]
            assert!(aot_file_path.ends_with("aot_fibonacci_1.so"));
            #[cfg(target_os = "windows")]
            assert!(aot_file_path.ends_with("aot_fibonacci_1.dll"));

            // read buffer
            let mut aot_file = std::fs::File::open(&aot_file_path)?;
            let mut buffer = [0u8; 4];
            aot_file.read_exact(&mut buffer)?;
            let wasm_magic: [u8; 4] = [0x00, 0x61, 0x73, 0x6D];
            assert_ne!(buffer, wasm_magic);

            let res =
                VmBuilder::new()
                    .build()?
                    .run_func_from_file(&aot_file_path, "fib", params!(5))?;
            assert_eq!(res[0].to_i32(), 8);

            // cleanup
            assert!(std::fs::remove_file(aot_file_path).is_ok());
        }

        // compile from bytes
        {
            let wasm_bytes = wat2wasm(
                br#"(module
                    (export "fib" (func $fib))
                    (func $fib (param $n i32) (result i32)
                     (if
                      (i32.lt_s
                       (get_local $n)
                       (i32.const 2)
                      )
                      (return
                       (i32.const 1)
                      )
                     )
                     (return
                      (i32.add
                       (call $fib
                        (i32.sub
                         (get_local $n)
                         (i32.const 2)
                        )
                       )
                       (call $fib
                        (i32.sub
                         (get_local $n)
                         (i32.const 1)
                        )
                       )
                      )
                     )
                    )
                   )
              "#,
            )?;

            // create a aot compiler
            let config = ConfigBuilder::default()
                .with_compiler_config(
                    CompilerConfigOptions::new().out_format(CompilerOutputFormat::Native),
                )
                .build()?;
            let compiler = Compiler::new(Some(&config))?;

            // compile wasm bytes into a shared library file
            let out_dir = std::env::current_dir()?;
            let aot_filename = "aot_fibonacci_2";
            let aot_file_path = compiler.compile_from_bytes(wasm_bytes, aot_filename, out_dir)?;
            assert!(aot_file_path.exists());
            #[cfg(target_os = "macos")]
            assert!(aot_file_path.ends_with("aot_fibonacci_2.dylib"));
            #[cfg(target_os = "linux")]
            assert!(aot_file_path.ends_with("aot_fibonacci_2.so"));
            #[cfg(target_os = "windows")]
            assert!(aot_file_path.ends_with("aot_fibonacci_2.dll"));

            // read buffer
            let mut aot_file = std::fs::File::open(&aot_file_path)?;
            let mut buffer = [0u8; 4];
            aot_file.read_exact(&mut buffer)?;
            let wasm_magic: [u8; 4] = [0x00, 0x61, 0x73, 0x6D];
            assert_ne!(buffer, wasm_magic);

            let res =
                VmBuilder::new()
                    .build()?
                    .run_func_from_file(&aot_file_path, "fib", params!(5))?;
            assert_eq!(res[0].to_i32(), 8);

            // cleanup
            assert!(std::fs::remove_file(aot_file_path).is_ok());
        }

        Ok(())
    }
}