Skip to main content

cha_core/
wasm.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4use wasmtime::component::{Component, Linker};
5use wasmtime::{Engine, Store};
6use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
7
8use crate::plugin::{Finding, Location, Severity, SmellCategory};
9use crate::{AnalysisContext, Plugin};
10
11mod bindings {
12    wasmtime::component::bindgen!({
13        path: "wit/plugin.wit",
14        world: "analyzer",
15    });
16}
17
18use bindings::Analyzer;
19use bindings::cha::plugin::types as wit;
20
21struct HostState {
22    wasi: WasiCtx,
23    table: ResourceTable,
24}
25
26impl WasiView for HostState {
27    fn ctx(&mut self) -> WasiCtxView<'_> {
28        WasiCtxView {
29            ctx: &mut self.wasi,
30            table: &mut self.table,
31        }
32    }
33}
34
35fn new_host_state() -> HostState {
36    let wasi = WasiCtxBuilder::new().build();
37    HostState {
38        wasi,
39        table: ResourceTable::new(),
40    }
41}
42
43/// Adapter that loads a WASM component and wraps it as a Plugin.
44pub struct WasmPlugin {
45    engine: Engine,
46    component: Component,
47    plugin_name: String,
48    plugin_version: String,
49    plugin_description: String,
50    plugin_authors: Vec<String>,
51    options: Vec<(String, wit::OptionValue)>,
52}
53
54impl WasmPlugin {
55    pub fn load(path: &Path) -> wasmtime::Result<Self> {
56        let engine = Engine::default();
57        let bytes = std::fs::read(path)?;
58        let component = Component::from_binary(&engine, &bytes)?;
59
60        let mut linker = Linker::<HostState>::new(&engine);
61        wasmtime_wasi::p2::add_to_linker_sync(&mut linker)?;
62
63        let mut store = Store::new(&engine, new_host_state());
64        let instance = Analyzer::instantiate(&mut store, &component, &linker)?;
65        let name = instance.call_name(&mut store)?;
66        let version = instance.call_version(&mut store)?;
67        let description = instance.call_description(&mut store)?;
68        let authors = instance.call_authors(&mut store)?;
69
70        Ok(Self {
71            engine,
72            component,
73            plugin_name: name,
74            plugin_version: version,
75            plugin_description: description,
76            plugin_authors: authors,
77            options: vec![],
78        })
79    }
80
81    /// Set plugin options from config.
82    pub fn set_options(&mut self, options: Vec<(String, wit::OptionValue)>) {
83        self.options = options;
84    }
85}
86
87impl Plugin for WasmPlugin {
88    fn name(&self) -> &str {
89        &self.plugin_name
90    }
91
92    fn version(&self) -> &str {
93        &self.plugin_version
94    }
95
96    fn description(&self) -> &str {
97        &self.plugin_description
98    }
99
100    fn authors(&self) -> Vec<String> {
101        self.plugin_authors.clone()
102    }
103
104    fn analyze(&self, ctx: &AnalysisContext) -> Vec<Finding> {
105        let result = (|| -> wasmtime::Result<Vec<Finding>> {
106            let mut linker = Linker::<HostState>::new(&self.engine);
107            wasmtime_wasi::p2::add_to_linker_sync(&mut linker)?;
108
109            let mut store = Store::new(&self.engine, new_host_state());
110            let instance = Analyzer::instantiate(&mut store, &self.component, &linker)?;
111            let input = to_wit_input(ctx, &self.options);
112            let results = instance.call_analyze(&mut store, &input)?;
113            Ok(results.into_iter().map(from_wit_finding).collect())
114        })();
115
116        result.unwrap_or_else(|e| {
117            eprintln!("wasm plugin error: {}", e);
118            vec![]
119        })
120    }
121}
122
123fn to_wit_input(
124    ctx: &AnalysisContext,
125    options: &[(String, wit::OptionValue)],
126) -> wit::AnalysisInput {
127    wit::AnalysisInput {
128        path: ctx.file.path.to_string_lossy().into(),
129        content: ctx.file.content.clone(),
130        language: ctx.model.language.clone(),
131        total_lines: ctx.model.total_lines as u32,
132        functions: convert_functions(&ctx.model.functions),
133        classes: convert_classes(&ctx.model.classes),
134        imports: convert_imports(&ctx.model.imports),
135        options: options.to_vec(),
136    }
137}
138
139/// Generic slice converter to avoid duplicate map-collect patterns.
140fn convert_slice<T, U>(items: &[T], f: impl Fn(&T) -> U) -> Vec<U> {
141    items.iter().map(f).collect()
142}
143
144fn convert_functions(funcs: &[crate::model::FunctionInfo]) -> Vec<wit::FunctionInfo> {
145    convert_slice(funcs, |f| wit::FunctionInfo {
146        name: f.name.clone(),
147        start_line: f.start_line as u32,
148        end_line: f.end_line as u32,
149        name_col: f.name_col as u32,
150        name_end_col: f.name_end_col as u32,
151        line_count: f.line_count as u32,
152        complexity: f.complexity as u32,
153        parameter_count: f.parameter_count as u32,
154        parameter_types: f.parameter_types.clone(),
155        chain_depth: f.chain_depth as u32,
156        switch_arms: f.switch_arms as u32,
157        external_refs: f.external_refs.clone(),
158        is_delegating: f.is_delegating,
159        is_exported: f.is_exported,
160        comment_lines: f.comment_lines as u32,
161        referenced_fields: f.referenced_fields.clone(),
162        null_check_fields: f.null_check_fields.clone(),
163        switch_dispatch_target: f.switch_dispatch_target.clone(),
164        optional_param_count: f.optional_param_count as u32,
165        called_functions: f.called_functions.clone(),
166        cognitive_complexity: f.cognitive_complexity as u32,
167        body_hash: f.body_hash.map(|h| format!("{h:016x}")),
168    })
169}
170
171fn convert_classes(classes: &[crate::model::ClassInfo]) -> Vec<wit::ClassInfo> {
172    convert_slice(classes, |c| wit::ClassInfo {
173        name: c.name.clone(),
174        start_line: c.start_line as u32,
175        end_line: c.end_line as u32,
176        name_col: c.name_col as u32,
177        name_end_col: c.name_end_col as u32,
178        method_count: c.method_count as u32,
179        line_count: c.line_count as u32,
180        delegating_method_count: c.delegating_method_count as u32,
181        field_count: c.field_count as u32,
182        field_names: c.field_names.clone(),
183        field_types: c.field_types.clone(),
184        is_exported: c.is_exported,
185        has_behavior: c.has_behavior,
186        is_interface: c.is_interface,
187        parent_name: c.parent_name.clone(),
188        override_count: c.override_count as u32,
189        self_call_count: c.self_call_count as u32,
190        has_listener_field: c.has_listener_field,
191        has_notify_method: c.has_notify_method,
192    })
193}
194
195fn convert_imports(imports: &[crate::model::ImportInfo]) -> Vec<wit::ImportInfo> {
196    convert_slice(imports, |i| wit::ImportInfo {
197        source: i.source.clone(),
198        line: i.line as u32,
199        col: i.col as u32,
200    })
201}
202
203fn from_wit_finding(f: wit::Finding) -> Finding {
204    Finding {
205        smell_name: f.smell_name,
206        category: convert_category(f.category),
207        severity: convert_severity(f.severity),
208        location: Location {
209            path: PathBuf::from(&f.location.path),
210            start_line: f.location.start_line as usize,
211            start_col: f.location.start_col as usize,
212            end_line: f.location.end_line as usize,
213            end_col: f.location.end_col as usize,
214            name: f.location.name,
215        },
216        message: f.message,
217        suggested_refactorings: f.suggested_refactorings,
218        actual_value: f.actual_value,
219        threshold: f.threshold,
220    }
221}
222
223fn convert_severity(s: wit::Severity) -> Severity {
224    match s {
225        wit::Severity::Hint => Severity::Hint,
226        wit::Severity::Warning => Severity::Warning,
227        wit::Severity::Error => Severity::Error,
228    }
229}
230
231fn convert_category(c: wit::SmellCategory) -> SmellCategory {
232    match c {
233        wit::SmellCategory::Bloaters => SmellCategory::Bloaters,
234        wit::SmellCategory::OoAbusers => SmellCategory::OoAbusers,
235        wit::SmellCategory::ChangePreventers => SmellCategory::ChangePreventers,
236        wit::SmellCategory::Dispensables => SmellCategory::Dispensables,
237        wit::SmellCategory::Couplers => SmellCategory::Couplers,
238        wit::SmellCategory::Security => SmellCategory::Security,
239    }
240}
241
242/// Scan plugin directories and load all .wasm components.
243pub fn load_wasm_plugins(project_dir: &Path) -> Vec<WasmPlugin> {
244    let mut plugins: Vec<WasmPlugin> = Vec::new();
245    let mut seen = HashMap::new();
246
247    let project_plugins = project_dir.join(".cha").join("plugins");
248    let global_plugins = home_dir().join(".cha").join("plugins");
249
250    for dir in [&project_plugins, &global_plugins] {
251        load_plugins_from_dir(dir, &mut seen, &mut plugins);
252    }
253
254    plugins
255}
256
257/// Load .wasm plugins from a single directory, skipping duplicates by filename.
258fn load_plugins_from_dir(
259    dir: &Path,
260    seen: &mut HashMap<String, bool>,
261    plugins: &mut Vec<WasmPlugin>,
262) {
263    let entries = match std::fs::read_dir(dir) {
264        Ok(e) => e,
265        Err(_) => return,
266    };
267    for entry in entries.flatten() {
268        let path = entry.path();
269        if path.extension().is_none_or(|e| e != "wasm") {
270            continue;
271        }
272        let filename = path.file_name().unwrap().to_string_lossy().to_string();
273        if seen.contains_key(&filename) {
274            continue;
275        }
276        match WasmPlugin::load(&path) {
277            Ok(p) => {
278                seen.insert(filename, true);
279                plugins.push(p);
280            }
281            Err(e) => {
282                eprintln!("failed to load wasm plugin {}: {}", path.display(), e);
283            }
284        }
285    }
286}
287
288fn home_dir() -> PathBuf {
289    std::env::var("HOME")
290        .map(PathBuf::from)
291        .unwrap_or_else(|_| PathBuf::from("."))
292}
293
294/// Convert a TOML value to a WIT option-value.
295pub fn toml_to_option_value(v: &toml::Value) -> Option<wit::OptionValue> {
296    match v {
297        toml::Value::String(s) => Some(wit::OptionValue::Str(s.clone())),
298        toml::Value::Integer(i) => Some(wit::OptionValue::Int(*i)),
299        toml::Value::Float(f) => Some(wit::OptionValue::Float(*f)),
300        toml::Value::Boolean(b) => Some(wit::OptionValue::Boolean(*b)),
301        toml::Value::Array(arr) => {
302            let strs: Vec<String> = arr
303                .iter()
304                .filter_map(|v| v.as_str().map(String::from))
305                .collect();
306            Some(wit::OptionValue::ListStr(strs))
307        }
308        _ => None,
309    }
310}