ryo-plugin-loader 0.1.0

[experimental] WASM plugin loader for ryo mutations
Documentation
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! # Ryo Plugin Loader
//!
//! WASM plugin loader for ryo mutation plugins.
//!
//! This crate provides the [`PluginLoader`] which loads WASM mutation plugins
//! and provides an interface to call their exported functions.
//!
//! ## Architecture
//!
//! ```text
//! ryo-plugin-loader                   ryo-executor
//! ┌───────────────────────┐          ┌─────────────────────────┐
//! │ PluginLoader          │          │ MutationRegistry        │
//! │ ├─ load(bytes)        │──────────│ ├─ register_plugin()    │
//! │ └─ LoadedPlugin       │          │ └─ Apply mutations      │
//! └───────────────────────┘          └─────────────────────────┘
//! ```
//!
//! ## Usage
//!
//! ```rust,ignore
//! use ryo_plugin_loader::PluginLoader;
//!
//! let loader = PluginLoader::new()?;
//! let mut plugin = loader.load(&wasm_bytes)?;
//!
//! println!("Loaded mutation: {}", plugin.manifest.name);
//!
//! // For complex transforms (TransformDef::WasmExecute)
//! let edits = plugin.execute_transform(matches, context)?;
//! ```
//!
//! ## Security
//!
//! - Fuel limits prevent infinite loops (10M instructions for init, 1M per transform)
//! - Stack size limits prevent stack overflow (1MB)
//! - WASI sandbox restricts filesystem/network access

use std::sync::Arc;
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, Store};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};

// Generate WIT component bindings for the mutation plugin interface
wasmtime::component::bindgen!({
    world: "mutation-plugin",
    path: "wit",
});

// Re-export API types for convenience
pub use ryo_plugin_api::{
    Capture, MatchResult, MutationCategory, MutationManifest, NodeKind, TextEdit, TransformContext,
    TransformDef, TransformError, TypeHint, CURRENT_API_VERSION,
};

/// Error type for plugin loading and execution
#[derive(Debug, thiserror::Error)]
pub enum LoaderError {
    /// Failed to create WASM engine
    #[error("Failed to create WASM engine: {0}")]
    EngineCreation(#[source] wasmtime::Error),

    /// Failed to add WASI to linker
    #[error("Failed to add WASI to linker: {0}")]
    WasiSetup(#[source] wasmtime::Error),

    /// Failed to parse WASM component
    #[error("Failed to parse WASM component: {0}")]
    ComponentParse(#[source] wasmtime::Error),

    /// Failed to set fuel limit
    #[error("Failed to set fuel limit: {0}")]
    FuelSetup(#[source] wasmtime::Error),

    /// Failed to instantiate WASM component
    #[error("Failed to instantiate WASM component: {0}")]
    Instantiation(#[source] wasmtime::Error),

    /// API version mismatch between host and plugin
    #[error("API version mismatch: expected {expected}, got {actual}")]
    ApiVersionMismatch { expected: u32, actual: u32 },

    /// Failed to call WASM function
    #[error("Failed to call WASM function '{function}': {source}")]
    FunctionCall {
        function: &'static str,
        #[source]
        source: wasmtime::Error,
    },

    /// Transform execution error from plugin
    #[error("Transform error: {0}")]
    TransformError(String),

    /// IO error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// WASM Plugin Loader
///
/// Loads WASM mutation plugins and provides access to their exported functions.
/// Thread-safe and can be shared across threads.
///
/// ## Security
///
/// - Fuel limits prevent infinite loops (10M instructions)
/// - Stack size limits prevent stack overflow (1MB)
/// - WASI sandbox restricts filesystem/network access
pub struct PluginLoader {
    engine: Engine,
    linker: Arc<Linker<PluginState>>,
}

/// State passed to WASM instances
struct PluginState {
    wasi_ctx: WasiCtx,
    resource_table: wasmtime::component::ResourceTable,
}

impl WasiView for PluginState {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi_ctx,
            table: &mut self.resource_table,
        }
    }
}

impl PluginLoader {
    /// Create a new plugin loader with default security settings
    ///
    /// Configures:
    /// - Component model support (for WIT)
    /// - Fuel limits (CPU usage)
    /// - Stack limits (1MB)
    /// - WASI support (minimal sandbox)
    pub fn new() -> Result<Self, LoaderError> {
        let mut config = Config::new();

        // Enable Component Model for WIT support
        config.wasm_component_model(true);

        // Security: Enable fuel for CPU limiting
        config.consume_fuel(true);

        // Security: Limit WASM stack size (1MB)
        config.max_wasm_stack(1024 * 1024);

        // Create engine with security config
        let engine = Engine::new(&config).map_err(LoaderError::EngineCreation)?;

        // Create component linker and add WASI
        let mut linker = Linker::new(&engine);
        wasmtime_wasi::p2::add_to_linker_sync(&mut linker).map_err(LoaderError::WasiSetup)?;

        Ok(Self {
            engine,
            linker: Arc::new(linker),
        })
    }

    /// Load a WASM mutation plugin from bytes
    ///
    /// Steps:
    /// 1. Parse WASM component
    /// 2. Instantiate with fuel limit
    /// 3. Call get-manifest()
    /// 4. Validate API version
    /// 5. Call get-pattern-source()
    /// 6. Return LoadedPlugin
    pub fn load(&self, wasm_bytes: &[u8]) -> Result<LoadedPlugin, LoaderError> {
        // Parse WASM component
        let component =
            Component::new(&self.engine, wasm_bytes).map_err(LoaderError::ComponentParse)?;

        // Create WASI context (minimal sandbox)
        let wasi_ctx = WasiCtxBuilder::new()
            .inherit_stdout() // Allow plugins to print debug info
            .inherit_stderr()
            .build();

        // Create store with fuel limit
        let mut store = Store::new(
            &self.engine,
            PluginState {
                wasi_ctx,
                resource_table: wasmtime::component::ResourceTable::new(),
            },
        );

        // Set fuel limit: 10 million instructions for initialization
        store.set_fuel(10_000_000).map_err(LoaderError::FuelSetup)?;

        // Instantiate component
        let bindings = MutationPlugin::instantiate(&mut store, &component, &self.linker)
            .map_err(LoaderError::Instantiation)?;

        // Get the mutation interface (exported functions)
        let iface = bindings.ryo_transform_mutation();

        // Call get-manifest()
        let wasm_manifest =
            iface
                .call_get_manifest(&mut store)
                .map_err(|e| LoaderError::FunctionCall {
                    function: "get-manifest",
                    source: e,
                })?;

        // Validate API version before proceeding
        let expected_version = CURRENT_API_VERSION;
        if wasm_manifest.api_version != expected_version {
            return Err(LoaderError::ApiVersionMismatch {
                expected: expected_version,
                actual: wasm_manifest.api_version,
            });
        }

        // Convert wasmtime types to API types
        let manifest = convert_manifest(&wasm_manifest);

        // Call get-pattern-source()
        let additional_patterns =
            iface
                .call_get_pattern_source(&mut store)
                .map_err(|e| LoaderError::FunctionCall {
                    function: "get-pattern-source",
                    source: e,
                })?;

        tracing::info!("Loaded mutation plugin: {}", manifest.name);

        Ok(LoadedPlugin {
            manifest,
            additional_patterns,
            bindings,
            store,
        })
    }
}

/// A loaded mutation plugin with live WASM instance
///
/// Contains the plugin metadata and a live WASM instance that can be used
/// to call `execute_transform()` for complex transformations.
pub struct LoadedPlugin {
    /// Plugin manifest containing metadata
    pub manifest: MutationManifest,
    /// Additional pattern sources (may be empty)
    pub additional_patterns: String,
    /// WASM bindings
    bindings: MutationPlugin,
    /// WASM store
    store: Store<PluginState>,
}

impl LoadedPlugin {
    /// Execute transform on matched nodes
    ///
    /// This is only called when `manifest.transform` is `TransformDef::WasmExecute`.
    /// For template-based transforms, the host should handle expansion directly.
    ///
    /// ## Fuel Limit
    ///
    /// Each call is limited to 1 million instructions to prevent runaway execution.
    pub fn execute_transform(
        &mut self,
        matches: Vec<MatchResult>,
        context: TransformContext,
    ) -> Result<Vec<TextEdit>, LoaderError> {
        // Reset fuel for this transform call
        self.store
            .set_fuel(1_000_000)
            .map_err(LoaderError::FuelSetup)?;

        // Convert API types to wasmtime types
        let wasm_matches = matches
            .iter()
            .map(convert_match_to_wasm)
            .collect::<Vec<_>>();
        let wasm_context = convert_context_to_wasm(&context);

        // Get the mutation interface
        let iface = self.bindings.ryo_transform_mutation();

        // Call execute-transform()
        let result = iface
            .call_execute_transform(&mut self.store, &wasm_matches, &wasm_context)
            .map_err(|e| LoaderError::FunctionCall {
                function: "execute-transform",
                source: e,
            })?;

        // Convert result
        match result {
            Ok(edits) => Ok(edits.into_iter().map(convert_text_edit).collect()),
            Err(e) => Err(LoaderError::TransformError(format_transform_error(&e))),
        }
    }
}

// =============================================================================
// Type Conversion: API types <-> WASM types
// =============================================================================

fn convert_manifest(
    wasm: &exports::ryo::transform::mutation::MutationManifest,
) -> MutationManifest {
    MutationManifest {
        api_version: wasm.api_version,
        name: wasm.name.clone(),
        description: wasm.description.clone(),
        category: convert_category(&wasm.category),
        tier: wasm.tier,
        pattern: wasm.pattern.clone(),
        transform: convert_transform_def(&wasm.transform),
    }
}

fn convert_category(
    wasm: &exports::ryo::transform::mutation::MutationCategory,
) -> MutationCategory {
    match wasm {
        exports::ryo::transform::mutation::MutationCategory::Idiom => MutationCategory::Idiom,
        exports::ryo::transform::mutation::MutationCategory::Refactor => MutationCategory::Refactor,
        exports::ryo::transform::mutation::MutationCategory::Generate => MutationCategory::Generate,
        exports::ryo::transform::mutation::MutationCategory::Custom => MutationCategory::Custom,
    }
}

fn convert_transform_def(wasm: &exports::ryo::transform::mutation::TransformDef) -> TransformDef {
    match wasm {
        exports::ryo::transform::mutation::TransformDef::Template(t) => {
            TransformDef::Template(t.clone())
        }
        exports::ryo::transform::mutation::TransformDef::WasmExecute => TransformDef::WasmExecute,
    }
}

fn convert_match_to_wasm(m: &MatchResult) -> exports::ryo::transform::mutation::MatchResult {
    exports::ryo::transform::mutation::MatchResult {
        kind: convert_node_kind_to_wasm(&m.kind),
        start_byte: m.start_byte,
        end_byte: m.end_byte,
        captures: m.captures.iter().map(convert_capture_to_wasm).collect(),
    }
}

fn convert_node_kind_to_wasm(k: &NodeKind) -> exports::ryo::transform::types::NodeKind {
    match k {
        NodeKind::FnCall => exports::ryo::transform::types::NodeKind::FnCall,
        NodeKind::MethodCall => exports::ryo::transform::types::NodeKind::MethodCall,
        NodeKind::MatchExpr => exports::ryo::transform::types::NodeKind::MatchExpr,
        NodeKind::IfExpr => exports::ryo::transform::types::NodeKind::IfExpr,
        NodeKind::IfLetExpr => exports::ryo::transform::types::NodeKind::IfLetExpr,
        NodeKind::LoopExpr => exports::ryo::transform::types::NodeKind::LoopExpr,
        NodeKind::ForExpr => exports::ryo::transform::types::NodeKind::ForExpr,
        NodeKind::WhileExpr => exports::ryo::transform::types::NodeKind::WhileExpr,
        NodeKind::Block => exports::ryo::transform::types::NodeKind::Block,
        NodeKind::Ident => exports::ryo::transform::types::NodeKind::Ident,
        NodeKind::Literal => exports::ryo::transform::types::NodeKind::Literal,
        NodeKind::BinaryExpr => exports::ryo::transform::types::NodeKind::BinaryExpr,
        NodeKind::UnaryExpr => exports::ryo::transform::types::NodeKind::UnaryExpr,
        NodeKind::FieldAccess => exports::ryo::transform::types::NodeKind::FieldAccess,
        NodeKind::IndexExpr => exports::ryo::transform::types::NodeKind::IndexExpr,
        NodeKind::Closure => exports::ryo::transform::types::NodeKind::Closure,
        NodeKind::StructExpr => exports::ryo::transform::types::NodeKind::StructExpr,
        NodeKind::TupleExpr => exports::ryo::transform::types::NodeKind::TupleExpr,
        NodeKind::ArrayExpr => exports::ryo::transform::types::NodeKind::ArrayExpr,
        NodeKind::Path => exports::ryo::transform::types::NodeKind::Path,
        NodeKind::TypePath => exports::ryo::transform::types::NodeKind::TypePath,
    }
}

fn convert_capture_to_wasm(c: &Capture) -> exports::ryo::transform::types::Capture {
    exports::ryo::transform::types::Capture {
        name: c.name.clone(),
        start_byte: c.start_byte,
        end_byte: c.end_byte,
        text: c.text.clone(),
    }
}

fn convert_context_to_wasm(
    ctx: &TransformContext,
) -> exports::ryo::transform::mutation::TransformContext {
    exports::ryo::transform::mutation::TransformContext {
        file_path: ctx.file_path.clone(),
        source_text: ctx.source_text.clone(),
        type_hints: ctx
            .type_hints
            .iter()
            .map(convert_type_hint_to_wasm)
            .collect(),
        fn_return_type: ctx.fn_return_type.clone(),
    }
}

fn convert_type_hint_to_wasm(h: &TypeHint) -> exports::ryo::transform::types::TypeHint {
    exports::ryo::transform::types::TypeHint {
        node_id: h.node_id,
        type_name: h.type_name.clone(),
        is_result: h.is_result,
        is_option: h.is_option,
        is_copy: h.is_copy,
        is_iterator: h.is_iterator,
    }
}

fn convert_text_edit(e: exports::ryo::transform::types::TextEdit) -> TextEdit {
    TextEdit {
        start_byte: e.start_byte,
        end_byte: e.end_byte,
        replacement: e.replacement,
    }
}

fn format_transform_error(e: &exports::ryo::transform::mutation::TransformError) -> String {
    match e {
        exports::ryo::transform::mutation::TransformError::MissingCapture(name) => {
            format!("Missing capture: {}", name)
        }
        exports::ryo::transform::mutation::TransformError::InvalidContext(msg) => {
            format!("Invalid context: {}", msg)
        }
        exports::ryo::transform::mutation::TransformError::TypeMismatch(msg) => {
            format!("Type mismatch: {}", msg)
        }
        exports::ryo::transform::mutation::TransformError::PatternNotApplicable(msg) => {
            format!("Pattern not applicable: {}", msg)
        }
        exports::ryo::transform::mutation::TransformError::Internal(msg) => {
            format!("Internal error: {}", msg)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_loader_creation() {
        let loader = PluginLoader::new();
        assert!(loader.is_ok());
    }
}