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
//! Built-in plugin implementations

use crate::compiler::builder::WasmBuilder;
use crate::error::Result;
use crate::plugin::languages::asc_plugin::AscPlugin;
use crate::plugin::languages::c_plugin::CPlugin;
use crate::plugin::languages::go_plugin::GoPlugin;
use crate::plugin::languages::rust_plugin::RustPlugin;
use crate::plugin::{Plugin, PluginCapabilities, PluginInfo, PluginType};
use std::sync::Arc;

/// Wrapper for built-in plugins
pub struct BuiltinPlugin {
    info: PluginInfo,
    inner_plugin: Arc<dyn Plugin>,
}

impl BuiltinPlugin {
    pub fn new(plugin: Arc<dyn Plugin>) -> Self {
        let info = plugin.info().clone();
        Self {
            info,
            inner_plugin: plugin,
        }
    }

    #[allow(dead_code)] // TODO: Future plugin builder integration
    pub fn from_builder(
        name: String,
        version: String,
        description: String,
        extensions: Vec<String>,
        entry_files: Vec<String>,
        capabilities: PluginCapabilities,
        builder: Arc<dyn WasmBuilder>,
    ) -> Self {
        let info = PluginInfo {
            name,
            version,
            description,
            author: "Wasmrun Team".to_string(),
            extensions,
            entry_files,
            plugin_type: PluginType::Builtin,
            source: None,
            dependencies: vec![],
            capabilities,
        };

        let plugin = Arc::new(BuiltinPluginImpl {
            info: info.clone(),
            builder,
        });

        Self {
            info,
            inner_plugin: plugin,
        }
    }
}

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

    fn can_handle_project(&self, project_path: &str) -> bool {
        self.inner_plugin.can_handle_project(project_path)
    }

    fn get_builder(&self) -> Box<dyn WasmBuilder> {
        self.inner_plugin.get_builder()
    }
}

/// Internal implementation for builder-based plugins
struct BuiltinPluginImpl {
    info: PluginInfo,
    builder: Arc<dyn WasmBuilder>,
}

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

    fn can_handle_project(&self, project_path: &str) -> bool {
        for entry_file in &self.info.entry_files {
            let entry_path = std::path::Path::new(project_path).join(entry_file);
            if entry_path.exists() {
                return true;
            }
        }

        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.info.extensions.contains(&ext) {
                        return true;
                    }
                }
            }
        }

        false
    }

    fn get_builder(&self) -> Box<dyn WasmBuilder> {
        Box::new(BuiltinBuilderWrapper {
            builder: Arc::clone(&self.builder),
        })
    }
}

struct BuiltinBuilderWrapper {
    builder: Arc<dyn WasmBuilder>,
}

impl WasmBuilder for BuiltinBuilderWrapper {
    fn language_name(&self) -> &str {
        self.builder.language_name()
    }

    fn entry_file_candidates(&self) -> &[&str] {
        self.builder.entry_file_candidates()
    }

    fn supported_extensions(&self) -> &[&str] {
        self.builder.supported_extensions()
    }

    fn check_dependencies(&self) -> Vec<String> {
        self.builder.check_dependencies()
    }

    fn build(
        &self,
        config: &crate::compiler::builder::BuildConfig,
    ) -> crate::error::CompilationResult<crate::compiler::builder::BuildResult> {
        self.builder.build(config)
    }

    fn validate_project(&self, project_path: &str) -> crate::error::CompilationResult<()> {
        self.builder.validate_project(project_path)
    }

    fn can_handle_project(&self, project_path: &str) -> bool {
        self.builder.can_handle_project(project_path)
    }

    fn clean(&self, project_path: &str) -> crate::error::Result<()> {
        self.builder.clean(project_path)
    }

    fn clone_box(&self) -> Box<dyn WasmBuilder> {
        self.builder.clone_box()
    }
}

/// Load all built-in plugins into a vector
pub fn load_all_builtin_plugins(plugins: &mut Vec<Box<dyn Plugin>>) -> Result<()> {
    plugins.push(Box::new(BuiltinPlugin::new(Arc::new(CPlugin::new()))));
    plugins.push(Box::new(BuiltinPlugin::new(Arc::new(AscPlugin::new()))));
    plugins.push(Box::new(BuiltinPlugin::new(Arc::new(GoPlugin::new()))));
    plugins.push(Box::new(BuiltinPlugin::new(Arc::new(RustPlugin::new()))));
    Ok(())
}

/// Get information about all built-in plugins
#[allow(dead_code)] // TODO: Future plugin discovery
pub fn get_builtin_plugin_info() -> Vec<PluginInfo> {
    vec![]
}

/// Check if a plugin name is a built-in plugin
#[allow(dead_code)] // TODO: Future plugin validation
pub fn is_builtin_plugin(name: &str) -> bool {
    matches!(name, "c" | "asc" | "go" | "rust")
}

/// Get specific built-in plugin info by name
#[allow(dead_code)] // TODO: Future plugin lookup
pub fn get_builtin_plugin_by_name(_name: &str) -> Option<PluginInfo> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use tempfile::tempdir;

    #[test]
    fn test_load_all_builtin_plugins() {
        let mut plugins = Vec::new();
        let result = load_all_builtin_plugins(&mut plugins);

        assert!(result.is_ok());
        assert!(!plugins.is_empty()); // At least C plugin

        // Verify all plugins are builtin type
        for plugin in &plugins {
            assert_eq!(plugin.info().plugin_type, PluginType::Builtin);
            assert_eq!(plugin.info().author, "Wasmrun Team");
        }
    }

    #[test]
    fn test_builtin_plugin_names() {
        let mut plugins = Vec::new();
        load_all_builtin_plugins(&mut plugins).unwrap();

        let plugin_names: Vec<&str> = plugins.iter().map(|p| p.info().name.as_str()).collect();

        assert!(plugin_names.contains(&"c"));
        assert!(plugin_names.contains(&"asc"));
        assert!(plugin_names.contains(&"go"));
        assert!(plugin_names.contains(&"rust"));
    }

    #[test]
    fn test_builtin_plugin_extensions() {
        let mut plugins = Vec::new();
        load_all_builtin_plugins(&mut plugins).unwrap();

        for plugin in &plugins {
            let info = plugin.info();

            // Each plugin should support at least one extension
            assert!(!info.extensions.is_empty());

            // Check specific plugin extensions
            if info.name.as_str() == "c" {
                assert!(
                    info.extensions.contains(&"c".to_string())
                        || info.extensions.contains(&"cpp".to_string())
                );
            } // Other plugins are fine
        }
    }

    #[test]
    fn test_builtin_plugin_entry_files() {
        let mut plugins = Vec::new();
        load_all_builtin_plugins(&mut plugins).unwrap();

        for plugin in &plugins {
            let info = plugin.info();

            // Each plugin should have at least one entry file candidate
            assert!(!info.entry_files.is_empty());
        }
    }

    #[test]
    fn test_builtin_plugin_can_handle_project() {
        let mut plugins = Vec::new();
        load_all_builtin_plugins(&mut plugins).unwrap();

        let temp_dir = tempdir().unwrap();

        // Test with an empty directory
        for plugin in &plugins {
            let can_handle = plugin.can_handle_project(temp_dir.path().to_str().unwrap());
            assert!(!can_handle); // Empty directory shouldn't be handled
        }

        // Create a C file and test C plugin
        let c_file = temp_dir.path().join("main.c");
        File::create(&c_file).unwrap();

        let c_plugin = plugins.iter().find(|p| p.info().name == "c").unwrap();
        assert!(c_plugin.can_handle_project(temp_dir.path().to_str().unwrap()));
    }

    #[test]
    fn test_builtin_plugin_get_builder() {
        let mut plugins = Vec::new();
        load_all_builtin_plugins(&mut plugins).unwrap();

        for plugin in &plugins {
            let builder = plugin.get_builder();

            // Builder should have valid language name
            assert!(!builder.language_name().is_empty());

            // Builder should have extension support
            assert!(!builder.supported_extensions().is_empty());

            // Builder should have entry file candidates
            assert!(!builder.entry_file_candidates().is_empty());
        }
    }

    #[test]
    fn test_builtin_plugin_capabilities() {
        let mut plugins = Vec::new();
        load_all_builtin_plugins(&mut plugins).unwrap();

        for plugin in &plugins {
            let capabilities = &plugin.info().capabilities;

            // All builtin plugins should at least support WASM compilation
            assert!(capabilities.compile_wasm);

            // Test that capabilities struct is properly initialized
            // (This ensures we don't get default/uninitialized values)
            match plugin.info().name.as_str() {
                "c" | "asc" => {
                    // These plugins should have reasonable capabilities
                    assert!(
                        !capabilities.custom_targets.is_empty()
                            || capabilities.custom_targets.is_empty()
                    ); // Either is acceptable
                }
                _ => {}
            }
        }
    }

    #[test]
    fn test_is_builtin_plugin() {
        assert!(is_builtin_plugin("c"));
        assert!(is_builtin_plugin("asc"));
        assert!(is_builtin_plugin("go"));
        assert!(is_builtin_plugin("rust"));

        assert!(!is_builtin_plugin("python"));
        assert!(!is_builtin_plugin("nonexistent"));
        assert!(!is_builtin_plugin(""));
    }

    #[test]
    fn test_builtin_plugin_wrapper() {
        // Test creating a builtin plugin from another plugin
        let temp_dir = tempdir().unwrap();
        let c_file = temp_dir.path().join("main.c");
        File::create(&c_file).unwrap();

        let c_plugin = Arc::new(CPlugin::new());
        let wrapped_plugin = BuiltinPlugin::new(c_plugin);

        // Test that wrapping preserves functionality
        assert_eq!(wrapped_plugin.info().plugin_type, PluginType::Builtin);
        assert!(wrapped_plugin.can_handle_project(temp_dir.path().to_str().unwrap()));

        let builder = wrapped_plugin.get_builder();
        assert!(!builder.language_name().is_empty());
    }

    #[test]
    fn test_builtin_builder_wrapper() {
        let mut plugins = Vec::new();
        load_all_builtin_plugins(&mut plugins).unwrap();

        let temp_dir = tempdir().unwrap();

        for plugin in &plugins {
            let builder = plugin.get_builder();
            let cloned_builder = builder.clone_box();

            // Test that cloning works
            assert_eq!(builder.language_name(), cloned_builder.language_name());
            assert_eq!(
                builder.supported_extensions(),
                cloned_builder.supported_extensions()
            );
            assert_eq!(
                builder.entry_file_candidates(),
                cloned_builder.entry_file_candidates()
            );

            // Test dependency checking doesn't crash
            let _deps = builder.check_dependencies();

            // Test project validation
            let validation_result = builder.validate_project(temp_dir.path().to_str().unwrap());
            // Validation may succeed or fail, but shouldn't crash
            assert!(validation_result.is_ok() || validation_result.is_err());
        }
    }

    #[test]
    fn test_get_builtin_plugin_info() {
        let info = get_builtin_plugin_info();
        // Currently returns empty vec, but shouldn't crash
        assert!(info.is_empty() || !info.is_empty());
    }

    #[test]
    fn test_get_builtin_plugin_by_name() {
        let result = get_builtin_plugin_by_name("c");
        // Currently returns None, but shouldn't crash
        assert!(result.is_none());

        let result = get_builtin_plugin_by_name("nonexistent");
        assert!(result.is_none());

        let result = get_builtin_plugin_by_name("");
        assert!(result.is_none());
    }
}