wasmrun 0.19.0

A WebAssembly Runtime
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::compiler::builder::{BuildConfig, BuildResult, OptimizationLevel, WasmBuilder};
use crate::error::{CompilationError, CompilationResult};
use crate::plugin::{Plugin, PluginCapabilities, PluginInfo, PluginType};
use crate::utils::{CommandExecutor, PathResolver};
use std::fs;
use std::path::{Path, PathBuf};

/// C WebAssembly plugin
#[derive(Clone)]
pub struct CPlugin {
    info: PluginInfo,
}

impl CPlugin {
    pub fn new() -> Self {
        let info = PluginInfo {
            name: "c".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            description: "C WebAssembly compiler using Emscripten".to_string(),
            author: "Wasmrun Team".to_string(),
            extensions: vec!["c".to_string(), "h".to_string()],
            entry_files: vec!["main.c".to_string(), "Makefile".to_string()],
            plugin_type: PluginType::Builtin,
            source: None,
            dependencies: vec![],
            capabilities: PluginCapabilities {
                compile_wasm: true,
                compile_webapp: true,
                live_reload: true,
                optimization: true,
                custom_targets: vec!["wasm".to_string(), "web".to_string()],
                supported_languages: Some(vec!["c".to_string(), "cpp".to_string()]),
            },
        };

        Self { info }
    }

    /// Find main.c or similar entry point
    fn find_entry_file(&self, project_path: &str) -> CompilationResult<PathBuf> {
        let common_entry_files = ["main.c", "src/main.c", "app.c", "index.c"];

        for entry_name in common_entry_files.iter() {
            let entry_path = Path::new(project_path).join(entry_name);
            if entry_path.exists() {
                return Ok(entry_path);
            }
        }

        // If no common entry file found, look for any .c file
        if let Ok(entries) = fs::read_dir(project_path) {
            for entry in entries.flatten() {
                if let Some(extension) = entry.path().extension() {
                    if extension == "c" {
                        return Ok(entry.path());
                    }
                }
            }
        }

        Err(CompilationError::MissingEntryFile {
            language: self.language_name().to_string(),
            candidates: vec![
                "main.c".to_string(),
                "src/main.c".to_string(),
                "app.c".to_string(),
                "index.c".to_string(),
            ],
        })
    }

    /// Check if project uses a Makefile
    fn has_makefile(&self, project_path: &str) -> bool {
        let makefile_variants = ["Makefile", "makefile", "GNUmakefile"];

        for variant in makefile_variants {
            let makefile_path = PathResolver::join_paths(project_path, variant);
            if Path::new(&makefile_path).exists() {
                return true;
            }
        }

        false
    }

    /// Build using Makefile if available
    fn build_with_makefile(&self, config: &BuildConfig) -> CompilationResult<BuildResult> {
        // Check if make is installed
        if !CommandExecutor::is_tool_installed("make") {
            return Err(CompilationError::BuildToolNotFound {
                tool: "make".to_string(),
                language: self.language_name().to_string(),
            });
        }

        // Execute make
        let build_output = CommandExecutor::execute_command(
            "make",
            &["wasm"],
            &config.project_path,
            config.verbose,
        )?;

        if !build_output.status.success() {
            let build_output = CommandExecutor::execute_command(
                "make",
                &[],
                &config.project_path,
                config.verbose,
            )?;

            if !build_output.status.success() {
                return Err(CompilationError::BuildFailed {
                    language: self.language_name().to_string(),
                    reason: format!(
                        "Make build failed: {}",
                        String::from_utf8_lossy(&build_output.stderr)
                    ),
                });
            }
        }

        let wasm_files = PathResolver::find_files_with_extension(&config.project_path, "wasm")
            .map_err(|e| CompilationError::BuildFailed {
                language: self.language_name().to_string(),
                reason: format!("Failed to find WASM files after make build: {e}"),
            })?;

        if wasm_files.is_empty() {
            return Err(CompilationError::BuildFailed {
                language: self.language_name().to_string(),
                reason: "No WASM file found after make build".to_string(),
            });
        }

        let output_path = CommandExecutor::copy_to_output(&wasm_files[0], &config.output_dir, "C")?;

        // Look for JS files (for Emscripten)
        let js_files =
            PathResolver::find_files_with_extension(&config.project_path, "js").unwrap_or_default();

        let js_output_path = if !js_files.is_empty() {
            Some(CommandExecutor::copy_to_output(
                &js_files[0],
                &config.output_dir,
                "C",
            )?)
        } else {
            None
        };

        let has_js_bindings = js_output_path.is_some();

        Ok(BuildResult {
            wasm_path: output_path,
            js_path: js_output_path,
            additional_files: vec![],
            is_wasm_bindgen: has_js_bindings,
        })
    }

    /// Build using Emscripten directly
    fn build_with_emscripten(&self, config: &BuildConfig) -> CompilationResult<BuildResult> {
        let entry_path = self.find_entry_file(&config.project_path)?;

        PathResolver::ensure_output_directory(&config.output_dir).map_err(|_| {
            CompilationError::OutputDirectoryCreationFailed {
                path: config.output_dir.clone(),
            }
        })?;

        let output_name = entry_path
            .file_stem()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let wasm_output_file = Path::new(&config.output_dir).join(format!("{output_name}.wasm"));
        let js_output_file = Path::new(&config.output_dir).join(format!("{output_name}.js"));

        println!("🔨 Building with Emscripten...");

        // Collect all .c files in the project
        let c_files = self.collect_c_files(&config.project_path)?;

        // Build args for emcc
        let mut args = vec![
            "-o",
            js_output_file.to_str().unwrap(),
            "-s",
            "WASM=1",
            "-s",
            "EXPORTED_RUNTIME_METHODS=['cwrap']",
        ];

        // Add optimization flags based on build config
        match config.optimization_level {
            OptimizationLevel::Debug => {
                args.extend(&["-g", "-O0"]);
            }
            OptimizationLevel::Release => {
                args.extend(&["-O3"]);
            }
            OptimizationLevel::Size => {
                args.extend(&["-Os", "-s", "ELIMINATE_DUPLICATE_FUNCTIONS=1"]);
            }
        }

        // Add all C files
        for c_file in &c_files {
            args.push(c_file);
        }

        // Run emcc
        let build_output =
            CommandExecutor::execute_command("emcc", &args, &config.project_path, config.verbose)?;

        if !build_output.status.success() {
            return Err(CompilationError::BuildFailed {
                language: self.language_name().to_string(),
                reason: format!(
                    "Emscripten build failed: {}",
                    String::from_utf8_lossy(&build_output.stderr)
                ),
            });
        }

        if !wasm_output_file.exists() || !js_output_file.exists() {
            return Err(CompilationError::BuildFailed {
                language: self.language_name().to_string(),
                reason: "Emscripten build completed but output files were not created".to_string(),
            });
        }

        Ok(BuildResult {
            wasm_path: wasm_output_file.to_string_lossy().to_string(),
            js_path: Some(js_output_file.to_string_lossy().to_string()),
            additional_files: vec![],
            is_wasm_bindgen: true,
        })
    }

    /// Collect all .c files in the project directory
    fn collect_c_files(&self, project_path: &str) -> CompilationResult<Vec<String>> {
        let mut c_files = Vec::new();

        let entries = fs::read_dir(project_path).map_err(|e| CompilationError::BuildFailed {
            language: self.language_name().to_string(),
            reason: format!("Failed to read project directory: {e}"),
        })?;

        for entry in entries.flatten() {
            let path = entry.path();
            if let Some(extension) = path.extension() {
                if extension == "c" {
                    if let Some(path_str) = path.to_str() {
                        c_files.push(path_str.to_string());
                    }
                }
            }
        }

        if c_files.is_empty() {
            return Err(CompilationError::BuildFailed {
                language: self.language_name().to_string(),
                reason: "No .c files found in project directory".to_string(),
            });
        }

        Ok(c_files)
    }
}

impl Plugin for CPlugin {
    fn info(&self) -> &PluginInfo {
        &self.info
    }

    fn can_handle_project(&self, project_path: &str) -> bool {
        // Check for Makefile
        if self.has_makefile(project_path) {
            return true;
        }

        // Look for .c files
        if let Ok(entries) = fs::read_dir(project_path) {
            for entry in entries.flatten() {
                if let Some(extension) = entry.path().extension() {
                    let ext = extension.to_string_lossy().to_lowercase();
                    if ext == "c" {
                        return true;
                    }
                }
            }
        }

        false
    }

    fn get_builder(&self) -> Box<dyn WasmBuilder> {
        Box::new(CPlugin::new())
    }
}

impl WasmBuilder for CPlugin {
    fn supported_extensions(&self) -> &[&str] {
        &["c", "h", "cpp", "hpp", "cc", "cxx"]
    }

    fn entry_file_candidates(&self) -> &[&str] {
        &[
            "main.c",
            "src/main.c",
            "app.c",
            "index.c",
            "Makefile",
            "CMakeLists.txt",
        ]
    }

    fn language_name(&self) -> &str {
        "C"
    }

    fn check_dependencies(&self) -> Vec<String> {
        let mut missing = Vec::new();

        if !CommandExecutor::is_tool_installed("emcc") {
            missing.push(
                "emcc (Emscripten compiler - install from https://emscripten.org)".to_string(),
            );
        }

        if self.has_makefile(&BuildConfig::default().project_path)
            && !CommandExecutor::is_tool_installed("make")
        {
            missing.push("make (build system)".to_string());
        }

        missing
    }

    fn validate_project(&self, project_path: &str) -> CompilationResult<()> {
        PathResolver::validate_directory_exists(project_path).map_err(|e| {
            CompilationError::InvalidProjectStructure {
                language: self.language_name().to_string(),
                reason: format!("Project directory validation failed: {e}"),
            }
        })?;

        // Check if we have either a Makefile or can find C files
        if !self.has_makefile(project_path) {
            let _ = self.find_entry_file(project_path)?;
        }

        Ok(())
    }

    fn build(&self, config: &BuildConfig) -> CompilationResult<BuildResult> {
        // Check if Emscripten is installed
        if !CommandExecutor::is_tool_installed("emcc") {
            return Err(CompilationError::BuildToolNotFound {
                tool: "emcc".to_string(),
                language: self.language_name().to_string(),
            });
        }

        if self.has_makefile(&config.project_path) {
            self.build_with_makefile(config)
        } else {
            self.build_with_emscripten(config)
        }
    }

    fn can_handle_project(&self, project_path: &str) -> bool {
        if let Ok(entries) = std::fs::read_dir(project_path) {
            for entry in entries.flatten() {
                if let Some(extension) = entry.path().extension() {
                    let ext = extension.to_string_lossy().to_lowercase();
                    if self.supported_extensions().contains(&ext.as_str()) {
                        return true;
                    }
                }
            }
        }

        for entry_file in self.entry_file_candidates() {
            let file_path = std::path::Path::new(project_path).join(entry_file);
            if file_path.exists() {
                return true;
            }
        }
        false
    }

    fn clean(&self, project_path: &str) -> crate::error::Result<()> {
        // Clean C/C++ build artifacts
        let artifacts = ["*.o", "*.wasm", "*.js", "build"];
        for artifact in artifacts {
            let path = std::path::Path::new(project_path).join(artifact);
            if path.exists() {
                if path.is_dir() {
                    let _ = std::fs::remove_dir_all(path);
                } else {
                    let _ = std::fs::remove_file(path);
                }
            }
        }
        Ok(())
    }

    fn clone_box(&self) -> Box<dyn WasmBuilder> {
        Box::new(self.clone())
    }
}

impl Default for CPlugin {
    fn default() -> Self {
        Self::new()
    }
}