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        line_count: f.line_count as u32,
150        complexity: f.complexity as u32,
151        parameter_count: f.parameter_count as u32,
152        parameter_types: f.parameter_types.clone(),
153        chain_depth: f.chain_depth as u32,
154        switch_arms: f.switch_arms as u32,
155        external_refs: f.external_refs.clone(),
156        is_delegating: f.is_delegating,
157        is_exported: f.is_exported,
158        comment_lines: f.comment_lines as u32,
159        referenced_fields: f.referenced_fields.clone(),
160        null_check_fields: f.null_check_fields.clone(),
161        switch_dispatch_target: f.switch_dispatch_target.clone(),
162        optional_param_count: f.optional_param_count as u32,
163        called_functions: f.called_functions.clone(),
164        cognitive_complexity: f.cognitive_complexity as u32,
165        body_hash: f.body_hash.map(|h| format!("{h:016x}")),
166    })
167}
168
169fn convert_classes(classes: &[crate::model::ClassInfo]) -> Vec<wit::ClassInfo> {
170    convert_slice(classes, |c| wit::ClassInfo {
171        name: c.name.clone(),
172        start_line: c.start_line as u32,
173        end_line: c.end_line as u32,
174        method_count: c.method_count as u32,
175        line_count: c.line_count as u32,
176        delegating_method_count: c.delegating_method_count as u32,
177        field_count: c.field_count as u32,
178        field_names: c.field_names.clone(),
179        field_types: c.field_types.clone(),
180        is_exported: c.is_exported,
181        has_behavior: c.has_behavior,
182        is_interface: c.is_interface,
183        parent_name: c.parent_name.clone(),
184        override_count: c.override_count as u32,
185        self_call_count: c.self_call_count as u32,
186        has_listener_field: c.has_listener_field,
187        has_notify_method: c.has_notify_method,
188    })
189}
190
191fn convert_imports(imports: &[crate::model::ImportInfo]) -> Vec<wit::ImportInfo> {
192    convert_slice(imports, |i| wit::ImportInfo {
193        source: i.source.clone(),
194        line: i.line as u32,
195    })
196}
197
198fn from_wit_finding(f: wit::Finding) -> Finding {
199    Finding {
200        smell_name: f.smell_name,
201        category: convert_category(f.category),
202        severity: convert_severity(f.severity),
203        location: Location {
204            path: PathBuf::from(&f.location.path),
205            start_line: f.location.start_line as usize,
206            end_line: f.location.end_line as usize,
207            name: f.location.name,
208        },
209        message: f.message,
210        suggested_refactorings: f.suggested_refactorings,
211        actual_value: f.actual_value,
212        threshold: f.threshold,
213    }
214}
215
216fn convert_severity(s: wit::Severity) -> Severity {
217    match s {
218        wit::Severity::Hint => Severity::Hint,
219        wit::Severity::Warning => Severity::Warning,
220        wit::Severity::Error => Severity::Error,
221    }
222}
223
224fn convert_category(c: wit::SmellCategory) -> SmellCategory {
225    match c {
226        wit::SmellCategory::Bloaters => SmellCategory::Bloaters,
227        wit::SmellCategory::OoAbusers => SmellCategory::OoAbusers,
228        wit::SmellCategory::ChangePreventers => SmellCategory::ChangePreventers,
229        wit::SmellCategory::Dispensables => SmellCategory::Dispensables,
230        wit::SmellCategory::Couplers => SmellCategory::Couplers,
231        wit::SmellCategory::Security => SmellCategory::Security,
232    }
233}
234
235/// Scan plugin directories and load all .wasm components.
236pub fn load_wasm_plugins(project_dir: &Path) -> Vec<WasmPlugin> {
237    let mut plugins: Vec<WasmPlugin> = Vec::new();
238    let mut seen = HashMap::new();
239
240    let project_plugins = project_dir.join(".cha").join("plugins");
241    let global_plugins = home_dir().join(".cha").join("plugins");
242
243    for dir in [&project_plugins, &global_plugins] {
244        load_plugins_from_dir(dir, &mut seen, &mut plugins);
245    }
246
247    plugins
248}
249
250/// Load .wasm plugins from a single directory, skipping duplicates by filename.
251fn load_plugins_from_dir(
252    dir: &Path,
253    seen: &mut HashMap<String, bool>,
254    plugins: &mut Vec<WasmPlugin>,
255) {
256    let entries = match std::fs::read_dir(dir) {
257        Ok(e) => e,
258        Err(_) => return,
259    };
260    for entry in entries.flatten() {
261        let path = entry.path();
262        if path.extension().is_none_or(|e| e != "wasm") {
263            continue;
264        }
265        let filename = path.file_name().unwrap().to_string_lossy().to_string();
266        if seen.contains_key(&filename) {
267            continue;
268        }
269        match WasmPlugin::load(&path) {
270            Ok(p) => {
271                seen.insert(filename, true);
272                plugins.push(p);
273            }
274            Err(e) => {
275                eprintln!("failed to load wasm plugin {}: {}", path.display(), e);
276            }
277        }
278    }
279}
280
281fn home_dir() -> PathBuf {
282    std::env::var("HOME")
283        .map(PathBuf::from)
284        .unwrap_or_else(|_| PathBuf::from("."))
285}
286
287/// Convert a TOML value to a WIT option-value.
288pub fn toml_to_option_value(v: &toml::Value) -> Option<wit::OptionValue> {
289    match v {
290        toml::Value::String(s) => Some(wit::OptionValue::Str(s.clone())),
291        toml::Value::Integer(i) => Some(wit::OptionValue::Int(*i)),
292        toml::Value::Float(f) => Some(wit::OptionValue::Float(*f)),
293        toml::Value::Boolean(b) => Some(wit::OptionValue::Boolean(*b)),
294        toml::Value::Array(arr) => {
295            let strs: Vec<String> = arr
296                .iter()
297                .filter_map(|v| v.as_str().map(String::from))
298                .collect();
299            Some(wit::OptionValue::ListStr(strs))
300        }
301        _ => None,
302    }
303}