diff --git a/crates/cli/src/check/tests.rs b/crates/cli/src/check/tests.rs index 82ccf77..55eec1e 100644 --- a/crates/cli/src/check/tests.rs +++ b/crates/cli/src/check/tests.rs @@ -5,8 +5,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use codeint_config::{FindingsShown, ReportFormat}; use codeint_model::language::{ - FileModel, FlaggedLine, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, - SourceSet, WorkspaceError, + DeclaredDep, FileModel, FlaggedLine, Guest, ImportRequest, LowerError, Manifest, + ReferenceRange, Resolution, SourceSet, WorkspaceError, }; use codeint_model::{InvalidReferenceRange, LanguagePlugin, ReferenceRanges, RepoPath}; use serde_json::Value; @@ -89,7 +89,18 @@ macro_rules! every_import_is_external { _manifests: Vec, requests: Vec, ) -> Vec { - requests.iter().map(|_| Resolution::External).collect() + requests + .iter() + .map(|_| Resolution::External(String::new())) + .collect() + } + + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() } }; } @@ -766,7 +777,25 @@ impl LanguagePlugin for ParallelProofPlugin { _manifests: Vec, requests: Vec, ) -> Vec { - requests.iter().map(|_| Resolution::External).collect() + requests + .iter() + .map(|_| Resolution::External(String::new())) + .collect() + } + + fn declared_dependencies( + &self, + _manifests: Vec, + ) -> Result, codeint_model::LanguagePluginError> { + Ok(Vec::new()) + } + + fn entry_points( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + ) -> Result, codeint_model::LanguagePluginError> { + Ok(Vec::new()) } fn reference_ranges(&self) -> Result { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index cc5e5bf..e8f0a46 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -302,7 +302,11 @@ fn plugin_config_remedy(error: &ConfigurationFileError) -> Option<&'static str> } fn plugin_host_remedy(error: &PluginHostError) -> &'static str { - match error { + plugin_load_remedy(error).unwrap_or_else(|| plugin_runtime_remedy(error)) +} + +fn plugin_load_remedy(error: &PluginHostError) -> Option<&'static str> { + Some(match error { PluginHostError::Read { .. } => { "Check that the plugin path in codeint.json points to an existing readable WebAssembly component file." } @@ -310,11 +314,32 @@ fn plugin_host_remedy(error: &PluginHostError) -> &'static str { "Verify the plugin file has not been modified, then update sha256 in codeint.json to match the trusted file." } PluginHostError::Compile { .. } => { - "Build the plugin as a WebAssembly component targeting codeint:plugin@0.1.0." + "Build the plugin as a WebAssembly component targeting codeint:plugin@0.2.0." } PluginHostError::Instantiate { .. } => { - "Ensure the plugin exports codeint:plugin/language@0.1.0 or codeint:plugin/metric@0.1.0 and imports no host capabilities." + "Ensure the plugin exports codeint:plugin/language@0.2.0 or codeint:plugin/metric@0.2.0 and imports no host capabilities." + } + PluginHostError::IncompatibleContractVersion { .. } => { + "Rebuild the plugin against codeint:plugin@0.2.0 and update its sha256 in codeint.json." + } + PluginHostError::NonHttpsUrl { .. } => { + "Use an https:// URL for the plugin in codeint.json; plain HTTP and other schemes are refused." + } + PluginHostError::MissingCacheDir { .. } => { + "Set CODEINT_CACHE_DIR, XDG_CACHE_HOME, HOME, or LOCALAPPDATA so codeint can cache downloaded plugins." + } + PluginHostError::CacheWrite { .. } => { + "Check that you have permission to write to the codeint plugin cache directory, or set CODEINT_CACHE_DIR to a writable folder." + } + PluginHostError::Download { .. } => { + "Check that curl is installed, the HTTPS URL is reachable, and its TLS certificate is valid." } + _ => return None, + }) +} + +fn plugin_runtime_remedy(error: &PluginHostError) -> &'static str { + match error { PluginHostError::Call { .. } => { "Fix the defect in the external Plugin, or report it to the plugin's author." } @@ -330,18 +355,7 @@ fn plugin_host_remedy(error: &PluginHostError) -> &'static str { PluginHostError::DuplicateMetricKey { .. } => { "Remove one of the Metric plugins that declare the same Metric key." } - PluginHostError::NonHttpsUrl { .. } => { - "Use an https:// URL for the plugin in codeint.json; plain HTTP and other schemes are refused." - } - PluginHostError::MissingCacheDir { .. } => { - "Set CODEINT_CACHE_DIR, XDG_CACHE_HOME, HOME, or LOCALAPPDATA so codeint can cache downloaded plugins." - } - PluginHostError::CacheWrite { .. } => { - "Check that you have permission to write to the codeint plugin cache directory, or set CODEINT_CACHE_DIR to a writable folder." - } - PluginHostError::Download { .. } => { - "Check that curl is installed, the HTTPS URL is reachable, and its TLS certificate is valid." - } + _ => "Check the plugin configuration in codeint.json.", } } diff --git a/crates/metrics/src/import_cycles.rs b/crates/metrics/src/import_cycles.rs index d8f30bb..e3b04d6 100644 --- a/crates/metrics/src/import_cycles.rs +++ b/crates/metrics/src/import_cycles.rs @@ -162,7 +162,9 @@ fn unresolved_imports(model: &CodeModel) -> Vec { specifier: runtime_import.specifier.clone(), reason: reason.clone(), }), - ImportResolution::Resolved(_) | ImportResolution::External => None, + ImportResolution::Resolved(_) + | ImportResolution::External(_) + | ImportResolution::Builtin => None, }) .collect(); unresolved.sort_by(|left, right| left.importer.cmp(&right.importer)); diff --git a/crates/metrics/src/import_cycles/tests.rs b/crates/metrics/src/import_cycles/tests.rs index 3eeaf6e..9074fd2 100644 --- a/crates/metrics/src/import_cycles/tests.rs +++ b/crates/metrics/src/import_cycles/tests.rs @@ -107,7 +107,7 @@ fn imports_of_files_that_are_not_modules_and_unresolved_imports_add_no_edge() { model.runtime_imports.push(RuntimeImport { importer: path("b.ts"), specifier: "a".to_owned(), - resolution: ImportResolution::External, + resolution: ImportResolution::External("a".to_owned()), }); let cycles = ImportCycles::measure(&model); @@ -161,7 +161,7 @@ fn unresolved_imports_are_listed_by_importer_in_source_order_and_others_are_not( RuntimeImport { importer: path("a.ts"), specifier: "lodash".to_owned(), - resolution: ImportResolution::External, + resolution: ImportResolution::External("lodash".to_owned()), }, unresolved("b.ts", "./first"), ]); diff --git a/crates/model/HOW-TO.md b/crates/model/HOW-TO.md index c85c19e..fabc417 100644 --- a/crates/model/HOW-TO.md +++ b/crates/model/HOW-TO.md @@ -4,8 +4,8 @@ ```rust use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - Token, TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + SourceSet, Token, TokenKind, WorkspaceError, }; use codeint_model::token_text_hash; @@ -60,7 +60,18 @@ impl Guest for Plain { _manifests: Vec, requests: Vec, ) -> Vec { - requests.iter().map(|_| Resolution::External).collect() + requests + .iter() + .map(|request| Resolution::External(request.specifier.clone())) + .collect() + } + + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() } fn reference_ranges() -> Vec { @@ -74,7 +85,7 @@ impl Guest for Plain { } ``` -- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.1.0`. +- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.2.0`. - `codeint_model::language` holds the Rust types that wit-bindgen generates from that file. Never write a second Rust copy of a WIT type. - A built-in Language plugin implements the generated `Guest` trait, so it compiles against the same interface as an external WebAssembly Plugin. @@ -121,7 +132,9 @@ impl Guest for Plain { Name only paths from `repository_paths`; which files matter is a rule of the Language plugin, never of the core. It is the one way a Language plugin asks the host for files, so the host reads each file once. - `resolve_imports` receives every file path of the repository snapshot and each file that `manifest_paths` chose as a `Manifest` with its text, because a Plugin cannot read the file system. - Return one `Resolution` per request, in request order: `Resolved` with a path from `repository_paths`, `External` for a package or built-in module, or `Unresolved` with the reason. + Return one `Resolution` per request, in request order: `Resolved` with a path from `repository_paths`, `External` with the canonical third-party package name, `Builtin` for a standard-library or runtime built-in module, or `Unresolved` with the reason. +- `declared_dependencies` extracts external dependencies declared in `manifests`, each with its `package-root`, normalized `name`, and `kind` (`Runtime`, `Dev`, or `Optional`). +- `entry_points` discovers standard entry-point source files from `repository_paths` and `manifests`, naming only paths from `repository_paths`. ## Lower files in the core diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index f4f1735..f014e1a 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -1,8 +1,8 @@ #![forbid(unsafe_code)] use std::borrow::Borrow; -use std::collections::BTreeMap; use std::collections::btree_map::Entry; +use std::collections::{BTreeMap, HashSet}; use std::fmt; mod metric; @@ -23,7 +23,9 @@ mod bindings { } pub use bindings::exports::codeint::plugin::language; -pub use language::{FileModel, Manifest, ReferenceRange, SourceSet, Token, TokenKind}; +pub use language::{ + DeclaredDep, DepKind, FileModel, Manifest, ReferenceRange, SourceSet, Token, TokenKind, +}; pub use metric::{ ExternalFinding, ExternalMetricMeasurement, Metric, MetricPlugin, MetricPluginError, }; @@ -301,6 +303,70 @@ impl ReferenceRanges { } } +#[derive(Debug, thiserror::Error)] +pub enum LanguagePluginError { + #[error("the Language plugin returned an invalid entry point path {path:?}")] + InvalidEntryPointPath { path: String }, + #[error( + "the Language plugin returned entry point {path:?}, which is not a file of the repository" + )] + UnknownEntryPoint { path: String }, + #[error( + "the Language plugin declared a dependency with an invalid package root {package_root:?}" + )] + InvalidDependencyPackageRoot { package_root: String }, + #[error( + "the Language plugin declared a dependency with an empty name in package root {package_root:?}" + )] + EmptyDependencyName { package_root: String }, + #[error("Plugin {plugin:?} exceeded its time limit of {timeout_ms} ms")] + TimeLimitExceeded { plugin: String, timeout_ms: u64 }, + #[error("Plugin {plugin:?} exceeded its memory cap of {memory_mb} MiB")] + MemoryLimitExceeded { plugin: String, memory_mb: u64 }, + #[error("Language plugin {plugin:?} failed during {call}: {reason}")] + Call { + plugin: String, + call: &'static str, + reason: String, + }, +} + +pub fn validate_declared_dependencies( + deps: Vec, +) -> Result, LanguagePluginError> { + for dep in &deps { + if !dep.package_root.is_empty() && RepoPath::new(dep.package_root.as_str()).is_err() { + return Err(LanguagePluginError::InvalidDependencyPackageRoot { + package_root: dep.package_root.clone(), + }); + } + if dep.name.trim().is_empty() { + return Err(LanguagePluginError::EmptyDependencyName { + package_root: dep.package_root.clone(), + }); + } + } + Ok(deps) +} + +pub fn validate_entry_points( + repository_paths: &[RepoPath], + entries: Vec, +) -> Result, LanguagePluginError> { + let known: HashSet<&str> = repository_paths.iter().map(RepoPath::as_str).collect(); + entries + .into_iter() + .map(|path| { + let repo_path = RepoPath::new(path.clone()) + .map_err(|_| LanguagePluginError::InvalidEntryPointPath { path: path.clone() })?; + if !known.contains(repo_path.as_str()) { + return Err(LanguagePluginError::UnknownEntryPoint { path }); + } + Ok(repo_path) + }) + .collect() +} + pub trait LanguagePlugin: Sync { fn extensions(&self) -> Vec; @@ -318,6 +384,17 @@ pub trait LanguagePlugin: Sync { requests: Vec, ) -> Vec; + fn declared_dependencies( + &self, + manifests: Vec, + ) -> Result, LanguagePluginError>; + + fn entry_points( + &self, + repository_paths: &[RepoPath], + manifests: Vec, + ) -> Result, LanguagePluginError>; + fn reference_ranges(&self) -> Result; } @@ -353,6 +430,24 @@ impl LanguagePlugin for Plugin { Plugin::resolve_imports(owned_paths(repository_paths), manifests, requests) } + fn declared_dependencies( + &self, + manifests: Vec, + ) -> Result, LanguagePluginError> { + validate_declared_dependencies(Plugin::declared_dependencies(manifests)) + } + + fn entry_points( + &self, + repository_paths: &[RepoPath], + manifests: Vec, + ) -> Result, LanguagePluginError> { + validate_entry_points( + repository_paths, + Plugin::entry_points(owned_paths(repository_paths), manifests), + ) + } + fn reference_ranges(&self) -> Result { ReferenceRanges::new(Plugin::reference_ranges()) } diff --git a/crates/model/src/runtime_imports.rs b/crates/model/src/runtime_imports.rs index f4ad77b..ea4b640 100644 --- a/crates/model/src/runtime_imports.rs +++ b/crates/model/src/runtime_imports.rs @@ -8,7 +8,8 @@ mod tests; #[derive(Clone, Debug, PartialEq, Eq)] pub enum ImportResolution { Resolved(RepoPath), - External, + External(String), + Builtin, Unresolved { reason: String }, } @@ -101,7 +102,8 @@ pub fn resolve_runtime_imports( target, }); } - language::Resolution::External => ImportResolution::External, + language::Resolution::External(package) => ImportResolution::External(package), + language::Resolution::Builtin => ImportResolution::Builtin, language::Resolution::Unresolved(reason) => ImportResolution::Unresolved { reason }, }; Ok(RuntimeImport { diff --git a/crates/model/src/runtime_imports/tests.rs b/crates/model/src/runtime_imports/tests.rs index 1d901f5..c8fcb3f 100644 --- a/crates/model/src/runtime_imports/tests.rs +++ b/crates/model/src/runtime_imports/tests.rs @@ -1,7 +1,7 @@ -use crate::language::{ImportRequest, Resolution, SourceSet}; +use crate::language::{DeclaredDep, ImportRequest, Resolution, SourceSet}; use crate::{ - FileModel, InvalidReferenceRange, LanguagePlugin, LowerError, Manifest, ReferenceRanges, - RepoPath, SourceFile, WorkspaceError, + FileModel, InvalidReferenceRange, LanguagePlugin, LanguagePluginError, LowerError, Manifest, + ReferenceRanges, RepoPath, SourceFile, WorkspaceError, }; use super::{ @@ -11,6 +11,21 @@ use super::{ struct Answering(Vec); impl LanguagePlugin for Answering { + fn declared_dependencies( + &self, + _manifests: Vec, + ) -> Result, LanguagePluginError> { + Ok(Vec::new()) + } + + fn entry_points( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + ) -> Result, LanguagePluginError> { + Ok(Vec::new()) + } + fn extensions(&self) -> Vec { vec!["ts".to_owned()] } @@ -66,10 +81,11 @@ fn importer(name: &str, specifiers: &[&str]) -> SourceFile { fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { let plugin = Answering(vec![ Resolution::Resolved("b.ts".to_owned()), - Resolution::External, + Resolution::External("react".to_owned()), + Resolution::Builtin, Resolution::Unresolved("gone".to_owned()), ]); - let a = importer("a.ts", &["./b", "react"]); + let a = importer("a.ts", &["./b", "react", "node:fs"]); let b = importer("b.ts", &["./gone"]); let imports = resolve_runtime_imports( @@ -91,7 +107,12 @@ fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { RuntimeImport { importer: path("a.ts"), specifier: "react".to_owned(), - resolution: ImportResolution::External, + resolution: ImportResolution::External("react".to_owned()), + }, + RuntimeImport { + importer: path("a.ts"), + specifier: "node:fs".to_owned(), + resolution: ImportResolution::Builtin, }, RuntimeImport { importer: path("b.ts"), @@ -106,7 +127,7 @@ fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { #[test] fn a_plugin_that_answers_the_wrong_number_of_requests_is_an_error() { - let plugin = Answering(vec![Resolution::External]); + let plugin = Answering(vec![Resolution::External("react".to_owned())]); let a = importer("a.ts", &["react", "vue"]); let result = resolve_runtime_imports(&plugin, &[path("a.ts")], Vec::new(), &[&a]); diff --git a/crates/model/src/scan.rs b/crates/model/src/scan.rs index d36451f..c35ac27 100644 --- a/crates/model/src/scan.rs +++ b/crates/model/src/scan.rs @@ -201,6 +201,8 @@ pub fn score_function_spans( end_line, decision_points: decisions, source_lines: code_lines.range(start_line..=end_line).count() as u32, + name: None, + cognitive_complexity: 0, } }) .collect(); @@ -295,11 +297,11 @@ pub fn resolve_relative_file( return Resolution::Unresolved(format!("{rel_uri:?} leads outside the repository")); }; if ignore_vendor && joined.split('/').any(|seg| seg == "vendor") { - return Resolution::External; + return Resolution::External(String::new()); } if files.contains(&joined) { if joined == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(joined) } diff --git a/crates/model/src/tests.rs b/crates/model/src/tests.rs index 8478ccd..406f3b2 100644 --- a/crates/model/src/tests.rs +++ b/crates/model/src/tests.rs @@ -1,10 +1,11 @@ use super::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, DepKind, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, + Resolution, SourceSet, WorkspaceError, }; use super::{ - CodeModel, ImportResolution, InvalidReferenceRange, LanguagePlugin, Package, ReferenceRanges, - RepoPath, RuntimeImport, SourceFile, Workspace, token_text_hash, + CodeModel, ImportResolution, InvalidReferenceRange, LanguagePlugin, LanguagePluginError, + Package, ReferenceRanges, RepoPath, RuntimeImport, SourceFile, Workspace, token_text_hash, + validate_declared_dependencies, validate_entry_points, }; fn path(text: &str) -> RepoPath { @@ -84,6 +85,14 @@ impl Guest for MeasuredLanguage { .collect() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { vec![range("erosion", 0.12, 0.56, "Measured panel, Table 1")] } @@ -247,3 +256,71 @@ fn the_token_text_hash_is_64_bit_fnv_1a() { assert_eq!(token_text_hash("a"), 0xaf63_dc4c_8601_ec8c); assert_eq!(token_text_hash("foobar"), 0x8594_4171_f739_67e8); } + +#[test] +fn validate_entry_points_rejects_traversal_absolute_and_unknown_paths() { + let repo_paths = vec![RepoPath::new("src/main.ts").expect("valid path")]; + assert_eq!( + validate_entry_points(&repo_paths, vec!["src/main.ts".to_owned()]) + .expect("known repo path succeeds"), + repo_paths + ); + assert!(matches!( + validate_entry_points(&repo_paths, vec!["../../../etc/passwd".to_owned()]), + Err(LanguagePluginError::InvalidEntryPointPath { ref path }) if path == "../../../etc/passwd" + )); + assert!(matches!( + validate_entry_points(&repo_paths, vec!["/etc/shadow".to_owned()]), + Err(LanguagePluginError::InvalidEntryPointPath { ref path }) if path == "/etc/shadow" + )); + assert!(matches!( + validate_entry_points(&repo_paths, vec!["src/missing.ts".to_owned()]), + Err(LanguagePluginError::UnknownEntryPoint { ref path }) if path == "src/missing.ts" + )); +} + +#[test] +fn validate_declared_dependencies_rejects_invalid_package_roots_and_empty_names() { + let valid = vec![ + DeclaredDep { + package_root: String::new(), + name: "serde".to_owned(), + kind: DepKind::Runtime, + }, + DeclaredDep { + package_root: "packages/app".to_owned(), + name: "@scope/pkg".to_owned(), + kind: DepKind::Dev, + }, + ]; + assert_eq!( + validate_declared_dependencies(valid.clone()).expect("valid deps succeed"), + valid + ); + for bad_root in ["../escape", "/etc", "packages\\app", "packages/app/"] { + let result = validate_declared_dependencies(vec![DeclaredDep { + package_root: bad_root.to_owned(), + name: "serde".to_owned(), + kind: DepKind::Runtime, + }]); + assert!( + matches!( + result, + Err(LanguagePluginError::InvalidDependencyPackageRoot { ref package_root }) + if package_root == bad_root + ), + "expected invalid package root error for {bad_root:?}, got {result:?}" + ); + } + for bad_name in ["", " "] { + let result = validate_declared_dependencies(vec![DeclaredDep { + package_root: String::new(), + name: bad_name.to_owned(), + kind: DepKind::Runtime, + }]); + assert!( + matches!(result, Err(LanguagePluginError::EmptyDependencyName { .. })), + "expected empty dependency name error for {bad_name:?}, got {result:?}" + ); + } +} diff --git a/crates/plugin-host/HOW-TO.md b/crates/plugin-host/HOW-TO.md index 3cf7836..7f89ea9 100644 --- a/crates/plugin-host/HOW-TO.md +++ b/crates/plugin-host/HOW-TO.md @@ -15,6 +15,7 @@ let external = load_language_plugins(repository.root(), &configuration.plugins, - Relative paths in `PluginSource::Path` resolve against `repository_root`; absolute paths are used as given. - `PluginSource::HttpsUrl` downloads through `curl` with `--proto =https --tlsv1.2 --proto-redir =https`, verifies the SHA-256 digest of the downloaded bytes before atomically renaming into `/.wasm`, and reuses a valid cached entry without network I/O. - Every `WasmLanguagePlugin` is instantiated with an empty `wasmtime::component::Linker` with zero host capabilities (no WASI, no filesystem, no network, no environment variables, no clocks). A component that imports any host interface fails to instantiate with `PluginHostError::Instantiate`. +- Every `WasmLanguagePlugin` and `WasmMetricPlugin` validates its exported WIT interface version against `codeint:plugin@0.2.0` before instantiation; an incompatible version (such as `codeint:plugin@0.1.0`) fails with `PluginHostError::IncompatibleContractVersion`. - Every `WasmLanguagePlugin` and `WasmMetricPlugin` enforces `codeint_config::PluginLimits` (linear memory cap via `wasmtime::ResourceLimiter` and wall-clock time limit via `wasmtime` epoch interruption). Use `load_language_plugins_with_limits` and `load_metric_plugins_with_limits` to pass configured limits from `codeint.json`. - `WasmLanguagePlugin` implements `codeint_model::LanguagePlugin: Sync` using an internal pool of pre-instantiated component instances, so callers can invoke `lower` concurrently across threads. diff --git a/crates/plugin-host/src/lib.rs b/crates/plugin-host/src/lib.rs index e403d53..3d9895a 100644 --- a/crates/plugin-host/src/lib.rs +++ b/crates/plugin-host/src/lib.rs @@ -5,9 +5,9 @@ use std::path::{Path, PathBuf}; use codeint_config::{PluginDeclaration, PluginHostConfig, PluginKind, PluginLimits, PluginSource}; use codeint_model::{ - CodeModel, ExternalMetricMeasurement, FileModel, InvalidReferenceRange, LanguagePlugin, - LowerError, Manifest, MetricPlugin, MetricPluginError, ReferenceRanges, RepoPath, - WorkspaceError, language, + CodeModel, DeclaredDep, ExternalMetricMeasurement, FileModel, InvalidReferenceRange, + LanguagePlugin, LanguagePluginError, LowerError, Manifest, MetricPlugin, MetricPluginError, + ReferenceRanges, RepoPath, WorkspaceError, language, }; mod fetch; @@ -51,6 +51,16 @@ pub enum PluginHostError { path: PathBuf, reason: String, }, + #[error( + "Plugin {name:?} at {} targets incompatible WIT contract {found}, but this version of codeint requires {expected}; rebuild the Plugin against {expected} and update its sha256 in codeint.json", + path.display() + )] + IncompatibleContractVersion { + name: String, + path: PathBuf, + expected: &'static str, + found: String, + }, #[error("Plugin {name:?} failed during {call}: {reason}")] Call { name: String, @@ -268,6 +278,21 @@ impl LanguagePlugin for WasmLanguagePlugin { self.resolve_imports_impl(repository_paths, manifests, requests) } + fn declared_dependencies( + &self, + manifests: Vec, + ) -> Result, LanguagePluginError> { + self.declared_dependencies_impl(manifests) + } + + fn entry_points( + &self, + repository_paths: &[RepoPath], + manifests: Vec, + ) -> Result, LanguagePluginError> { + self.entry_points_impl(repository_paths, manifests) + } + fn reference_ranges(&self) -> Result { self.reference_ranges_impl() } diff --git a/crates/plugin-host/src/limits.rs b/crates/plugin-host/src/limits.rs index a238cad..6bdbee2 100644 --- a/crates/plugin-host/src/limits.rs +++ b/crates/plugin-host/src/limits.rs @@ -2,10 +2,16 @@ use std::sync::{Arc, Condvar, Mutex}; use std::thread::{self, JoinHandle}; use std::time::Duration; +#[cfg(test)] +mod tests; + use codeint_config::PluginLimits; use wasmtime::{Engine, ResourceLimiter, Store, StoreLimits, StoreLimitsBuilder, Trap}; +use crate::PluginHostError; + const EPOCH_TICK_MS: u64 = 10; +const LIFTED_BYTES_PER_ELEMENT: usize = 32; pub(crate) struct EpochTicker { stop: Arc<(Mutex, Condvar)>, @@ -140,6 +146,7 @@ pub(crate) enum LimitTrap { pub(crate) fn new_limited_store(engine: &Engine, limits: PluginLimits) -> Store { let mut store = Store::new(engine, PluginStoreState::new(limits)); store.limiter(|state| state); + store.set_hostcall_fuel(limits.memory_bytes()); store.epoch_deadline_trap(); arm_call_deadline(&mut store, limits); store @@ -152,7 +159,9 @@ pub(crate) fn arm_call_deadline(store: &mut Store, limits: Plu } pub(crate) fn classify_trap(store: &Store, error: &wasmtime::Error) -> LimitTrap { - if store.data().memory_limit_hit() { + if store.data().memory_limit_hit() + || error.downcast_ref::() == Some(&Trap::HostcallFuelExhausted) + { LimitTrap::Memory } else if error.downcast_ref::() == Some(&Trap::Interrupt) { LimitTrap::Time @@ -160,3 +169,20 @@ pub(crate) fn classify_trap(store: &Store, error: &wasmtime::E LimitTrap::Other } } + +pub(crate) fn enforce_lifted_budget( + name: &str, + limits: PluginLimits, + elements: usize, + bytes: usize, +) -> Result<(), PluginHostError> { + let max_bytes = limits.memory_bytes(); + let max_elements = (max_bytes / LIFTED_BYTES_PER_ELEMENT).max(1); + if elements > max_elements || bytes > max_bytes { + return Err(PluginHostError::MemoryLimitExceeded { + name: name.to_owned(), + memory_mb: limits.memory_mb, + }); + } + Ok(()) +} diff --git a/crates/plugin-host/src/limits/tests.rs b/crates/plugin-host/src/limits/tests.rs new file mode 100644 index 0000000..3801419 --- /dev/null +++ b/crates/plugin-host/src/limits/tests.rs @@ -0,0 +1,24 @@ +use codeint_config::PluginLimits; + +use super::enforce_lifted_budget; +use crate::PluginHostError; + +#[test] +fn enforce_lifted_budget_rejects_excessive_bytes_and_elements() { + let limits = PluginLimits { + memory_mb: 1, + timeout_ms: 1_000, + }; + let max_bytes = limits.memory_bytes(); + let max_elements = max_bytes / 32; + + assert!(enforce_lifted_budget("probe", limits, max_elements, max_bytes).is_ok()); + assert!(matches!( + enforce_lifted_budget("probe", limits, 1, max_bytes + 1), + Err(PluginHostError::MemoryLimitExceeded { ref name, memory_mb: 1 }) if name == "probe" + )); + assert!(matches!( + enforce_lifted_budget("probe", limits, max_elements + 1, 0), + Err(PluginHostError::MemoryLimitExceeded { ref name, memory_mb: 1 }) if name == "probe" + )); +} diff --git a/crates/plugin-host/src/wasm.rs b/crates/plugin-host/src/wasm.rs index 8275c58..0e75a6d 100644 --- a/crates/plugin-host/src/wasm.rs +++ b/crates/plugin-host/src/wasm.rs @@ -4,15 +4,17 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use codeint_config::PluginLimits; use codeint_model::{ - FileModel, InvalidReferenceRange, LowerError, Manifest, ReferenceRange, ReferenceRanges, - RepoPath, SourceSet, Token, TokenKind, WorkspaceError, language, + DeclaredDep, DepKind, FileModel, InvalidReferenceRange, LanguagePluginError, LowerError, + Manifest, ReferenceRange, ReferenceRanges, RepoPath, SourceSet, Token, TokenKind, + WorkspaceError, language, validate_declared_dependencies, validate_entry_points, }; use wasmtime::component::{Component, Linker}; use wasmtime::{Config, Engine, Store}; use crate::PluginHostError; use crate::limits::{ - EpochTicker, LimitTrap, PluginStoreState, arm_call_deadline, classify_trap, new_limited_store, + EpochTicker, LimitTrap, PluginStoreState, arm_call_deadline, classify_trap, + enforce_lifted_budget, new_limited_store, }; mod bindings { @@ -24,22 +26,125 @@ mod bindings { use bindings::exports::codeint::plugin::language as guest; -struct PluginInstance { - store: Store, - bindings: bindings::LanguagePlugin, +pub(crate) struct ContractSpec { + pub(crate) interface_prefix: &'static str, + pub(crate) expected_interface: &'static str, } -pub struct WasmLanguagePlugin { - name: String, +const LANGUAGE_CONTRACT: ContractSpec = ContractSpec { + interface_prefix: "codeint:plugin/language@", + expected_interface: "codeint:plugin/language@0.2.0", +}; + +pub(crate) fn check_contract_version( + name: &str, + path: &Path, + engine: &Engine, + instance_pre: &wasmtime::component::InstancePre, + spec: ContractSpec, +) -> Result<(), PluginHostError> { + let component_type = instance_pre.component().component_type(); + let mut incompatible: Option = None; + for (export_name, _) in component_type.exports(engine) { + if export_name == spec.expected_interface { + return Ok(()); + } + if export_name.starts_with(spec.interface_prefix) && incompatible.is_none() { + incompatible = Some(export_name.to_owned()); + } + } + if let Some(found) = incompatible { + return Err(PluginHostError::IncompatibleContractVersion { + name: name.to_owned(), + path: path.to_path_buf(), + expected: spec.expected_interface, + found, + }); + } + Ok(()) +} + +pub(crate) struct PooledInstance { + pub(crate) store: Store, + pub(crate) bindings: Bindings, +} + +pub(crate) struct InstancePool { limits: PluginLimits, engine: Engine, _ticker: EpochTicker, - pre: bindings::LanguagePluginPre, - extensions: Vec, - pool: Mutex>, + pre: Pre, + pool: Mutex>>, peak_memory_bytes: AtomicUsize, } +impl InstancePool { + pub(crate) fn from_component( + component: InstantiatedComponent, + limits: PluginLimits, + ) -> InstancePool { + let peak_memory_bytes = AtomicUsize::new(component.store.data().peak_memory_bytes()); + InstancePool { + limits, + engine: component.engine, + _ticker: component.ticker, + pre: component.pre, + pool: Mutex::new(vec![PooledInstance { + store: component.store, + bindings: component.bindings, + }]), + peak_memory_bytes, + } + } + + pub(crate) fn limits(&self) -> PluginLimits { + self.limits + } + + pub(crate) fn peak_memory_bytes(&self) -> usize { + self.peak_memory_bytes.load(Ordering::Relaxed) + } + + pub(crate) fn record_peak_memory(&self, store: &Store) { + self.peak_memory_bytes + .fetch_max(store.data().peak_memory_bytes(), Ordering::Relaxed); + } + + pub(crate) fn checkout( + &self, + instantiate: impl FnOnce( + &Pre, + &mut Store, + ) -> Result, + map_error: impl FnOnce(&Store, wasmtime::Error) -> E, + ) -> Result, E> { + if let Ok(mut guard) = self.pool.lock() + && let Some(instance) = guard.pop() + { + return Ok(instance); + } + let mut store = new_limited_store(&self.engine, self.limits); + let bindings = + instantiate(&self.pre, &mut store).map_err(|error| map_error(&store, error))?; + self.record_peak_memory(&store); + Ok(PooledInstance { store, bindings }) + } + + pub(crate) fn checkin(&self, instance: PooledInstance) { + self.record_peak_memory(&instance.store); + if let Ok(mut guard) = self.pool.lock() { + guard.push(instance); + } + } +} + +pub struct WasmLanguagePlugin { + name: String, + extensions: Vec, + instances: + InstancePool, bindings::LanguagePlugin>, +} + pub(crate) fn compile_sandboxed_component( name: &str, path: &Path, @@ -71,6 +176,45 @@ pub(crate) fn compile_sandboxed_component( Ok((engine, instance_pre)) } +pub(crate) struct InstantiatedComponent { + pub(crate) engine: Engine, + pub(crate) ticker: EpochTicker, + pub(crate) pre: Pre, + pub(crate) store: Store, + pub(crate) bindings: Bindings, +} + +pub(crate) fn instantiate_sandboxed_component( + name: &str, + path: &Path, + bytes: &[u8], + limits: PluginLimits, + spec: ContractSpec, + bind: impl FnOnce( + wasmtime::component::InstancePre, + ) -> Result, + instantiate: impl FnOnce(&Pre, &mut Store) -> Result, +) -> Result, PluginHostError> { + let (engine, instance_pre) = compile_sandboxed_component(name, path, bytes)?; + check_contract_version(name, path, &engine, &instance_pre, spec)?; + let ticker = EpochTicker::start(engine.clone()); + let pre = bind(instance_pre).map_err(|error| PluginHostError::Instantiate { + name: name.to_owned(), + path: path.to_path_buf(), + reason: error.to_string(), + })?; + let mut store = new_limited_store(&engine, limits); + let bindings = instantiate(&pre, &mut store) + .map_err(|error| map_host_trap(name, path, None, limits, &store, error))?; + Ok(InstantiatedComponent { + engine, + ticker, + pre, + store, + bindings, + }) +} + impl WasmLanguagePlugin { pub(crate) fn from_verified_bytes( name: String, @@ -78,70 +222,44 @@ impl WasmLanguagePlugin { bytes: &[u8], limits: PluginLimits, ) -> Result { - let (engine, instance_pre) = compile_sandboxed_component(&name, path, bytes)?; - let ticker = EpochTicker::start(engine.clone()); - let pre = bindings::LanguagePluginPre::new(instance_pre).map_err(|error| { - PluginHostError::Instantiate { - name: name.clone(), - path: path.to_path_buf(), - reason: error.to_string(), - } - })?; - let mut store = new_limited_store(&engine, limits); - let bindings = pre - .instantiate(&mut store) - .map_err(|error| map_host_trap(&name, path, None, limits, &store, error))?; - arm_call_deadline(&mut store, limits); - let extensions = bindings + let mut component = instantiate_sandboxed_component( + &name, + path, + bytes, + limits, + LANGUAGE_CONTRACT, + bindings::LanguagePluginPre::new, + |pre, store| pre.instantiate(store), + )?; + arm_call_deadline(&mut component.store, limits); + let extensions = component + .bindings .codeint_plugin_language() - .call_extensions(&mut store) + .call_extensions(&mut component.store) .map_err(|error| { - map_host_trap(&name, path, Some("extensions"), limits, &store, error) + map_host_trap( + &name, + path, + Some("extensions"), + limits, + &component.store, + error, + ) })?; - let peak_memory_bytes = AtomicUsize::new(store.data().peak_memory_bytes()); + let (ext_count, ext_bytes) = extensions.lifted_budget(); + enforce_lifted_budget(&name, limits, ext_count, ext_bytes)?; Ok(WasmLanguagePlugin { name, - limits, - engine, - _ticker: ticker, - pre, extensions, - pool: Mutex::new(vec![PluginInstance { store, bindings }]), - peak_memory_bytes, + instances: InstancePool::from_component(component, limits), }) } pub fn peak_memory_bytes(&self) -> usize { - self.peak_memory_bytes.load(Ordering::Relaxed) - } - - fn record_peak_memory(&self, store: &Store) { - self.peak_memory_bytes - .fetch_max(store.data().peak_memory_bytes(), Ordering::Relaxed); - } - - fn checkout(&self) -> Result { - if let Ok(mut guard) = self.pool.lock() - && let Some(instance) = guard.pop() - { - return Ok(instance); - } - let mut store = new_limited_store(&self.engine, self.limits); - let bindings = self.pre.instantiate(&mut store).map_err(|error| { - map_call_trap(&self.name, "instantiate", self.limits, &store, error) - })?; - self.record_peak_memory(&store); - Ok(PluginInstance { store, bindings }) + self.instances.peak_memory_bytes() } - fn checkin(&self, instance: PluginInstance) { - self.record_peak_memory(&instance.store); - if let Ok(mut guard) = self.pool.lock() { - guard.push(instance); - } - } - - fn with_instance( + fn with_checked_instance( &self, call: &'static str, operation: impl FnOnce( @@ -149,22 +267,28 @@ impl WasmLanguagePlugin { &mut Store, ) -> Result, ) -> Result { - let mut instance = self.checkout()?; - arm_call_deadline(&mut instance.store, self.limits); + let limits = self.instances.limits(); + let mut instance = self.instances.checkout( + |pre, store| pre.instantiate(store), + |store, error| map_call_trap(&self.name, "instantiate", limits, store, error), + )?; + arm_call_deadline(&mut instance.store, limits); let result = operation( instance.bindings.codeint_plugin_language(), &mut instance.store, ); - self.record_peak_memory(&instance.store); + self.instances.record_peak_memory(&instance.store); match result { Ok(value) => { - self.checkin(instance); + let (elements, bytes) = value.lifted_budget(); + enforce_lifted_budget(&self.name, limits, elements, bytes)?; + self.instances.checkin(instance); Ok(value) } Err(error) => Err(map_call_trap( &self.name, call, - self.limits, + limits, &instance.store, error, )), @@ -177,7 +301,7 @@ impl WasmLanguagePlugin { pub(crate) fn lower_impl(&self, path: &RepoPath, text: &str) -> Result { let lowered = self - .with_instance("lower", |api, store| { + .with_checked_instance("lower", |api, store| { api.call_lower(store, path.as_str(), text) }) .map_err(|error| match error { @@ -202,7 +326,7 @@ impl WasmLanguagePlugin { pub(crate) fn manifest_paths_impl(&self, repository_paths: &[RepoPath]) -> Vec { let paths = owned_paths(repository_paths); - self.with_instance("manifest-paths", |api, store| { + self.with_checked_instance("manifest-paths", |api, store| { api.call_manifest_paths(store, &paths) }) .unwrap_or_default() @@ -212,15 +336,9 @@ impl WasmLanguagePlugin { &self, manifests: Vec, ) -> Result, WorkspaceError> { - let host_manifests: Vec = manifests - .into_iter() - .map(|manifest| guest::Manifest { - path: manifest.path, - text: manifest.text, - }) - .collect(); + let host_manifests = to_guest_manifests(manifests); let packages = self - .with_instance("workspace-packages", |api, store| { + .with_checked_instance("workspace-packages", |api, store| { api.call_workspace_packages(store, &host_manifests) }) .map_err(|error| WorkspaceError::Manifest { @@ -244,13 +362,7 @@ impl WasmLanguagePlugin { requests: Vec, ) -> Vec { let paths = owned_paths(repository_paths); - let host_manifests: Vec = manifests - .into_iter() - .map(|manifest| guest::Manifest { - path: manifest.path, - text: manifest.text, - }) - .collect(); + let host_manifests = to_guest_manifests(manifests); let host_requests: Vec = requests .into_iter() .map(|request| guest::ImportRequest { @@ -258,16 +370,44 @@ impl WasmLanguagePlugin { specifier: request.specifier, }) .collect(); - self.with_instance("resolve-imports", |api, store| { + self.with_checked_instance("resolve-imports", |api, store| { api.call_resolve_imports(store, &paths, &host_manifests, &host_requests) }) .map(|resolutions| resolutions.into_iter().map(convert_resolution).collect()) .unwrap_or_default() } + pub(crate) fn declared_dependencies_impl( + &self, + manifests: Vec, + ) -> Result, LanguagePluginError> { + let host_manifests = to_guest_manifests(manifests); + let deps = self + .with_checked_instance("declared-dependencies", |api, store| { + api.call_declared_dependencies(store, &host_manifests) + }) + .map_err(map_language_plugin_error)?; + validate_declared_dependencies(deps.into_iter().map(convert_declared_dep).collect()) + } + + pub(crate) fn entry_points_impl( + &self, + repository_paths: &[RepoPath], + manifests: Vec, + ) -> Result, LanguagePluginError> { + let paths = owned_paths(repository_paths); + let host_manifests = to_guest_manifests(manifests); + let entries = self + .with_checked_instance("entry-points", |api, store| { + api.call_entry_points(store, &paths, &host_manifests) + }) + .map_err(map_language_plugin_error)?; + validate_entry_points(repository_paths, entries) + } + pub(crate) fn reference_ranges_impl(&self) -> Result { let ranges = self - .with_instance("reference-ranges", |api, store| { + .with_checked_instance("reference-ranges", |api, store| { api.call_reference_ranges(store) }) .unwrap_or_default() @@ -283,6 +423,128 @@ impl WasmLanguagePlugin { } } +trait LiftedSize { + fn lifted_budget(&self) -> (usize, usize); +} + +fn slice_budget(items: &[T], extra_bytes: fn(&T) -> usize) -> (usize, usize) { + let base = items.len().saturating_mul(size_of::()); + let bytes = items + .iter() + .fold(base, |acc, item| acc.saturating_add(extra_bytes(item))); + (items.len(), bytes) +} + +impl LiftedSize for Vec { + fn lifted_budget(&self) -> (usize, usize) { + slice_budget(self, String::len) + } +} + +impl LiftedSize for Vec { + fn lifted_budget(&self) -> (usize, usize) { + slice_budget(self, |dep| { + dep.package_root.len().saturating_add(dep.name.len()) + }) + } +} + +impl LiftedSize for Vec { + fn lifted_budget(&self) -> (usize, usize) { + slice_budget(self, |resolution| match resolution { + guest::Resolution::Resolved(text) + | guest::Resolution::External(text) + | guest::Resolution::Unresolved(text) => text.len(), + guest::Resolution::Builtin => 0, + }) + } +} + +impl LiftedSize for Vec { + fn lifted_budget(&self) -> (usize, usize) { + slice_budget(self, |range| { + range.metric.len().saturating_add(range.source.len()) + }) + } +} + +impl LiftedSize for Result, guest::WorkspaceError> { + fn lifted_budget(&self) -> (usize, usize) { + match self { + Ok(packages) => packages.lifted_budget(), + Err(error) => (1, error.path.len().saturating_add(error.message.len())), + } + } +} + +impl LiftedSize for Result { + fn lifted_budget(&self) -> (usize, usize) { + match self { + Ok(model) => { + let (fn_count, fn_bytes) = slice_budget(&model.functions, |function| { + function.name.as_ref().map_or(0, String::len) + }); + let (token_count, token_bytes) = slice_budget(&model.tokens, |_| 0); + let (flag_count, flag_bytes) = + slice_budget(&model.flagged_lines, |flagged| flagged.rule.len()); + let (import_count, import_bytes) = model.runtime_imports.lifted_budget(); + ( + fn_count + .saturating_add(token_count) + .saturating_add(flag_count) + .saturating_add(import_count), + fn_bytes + .saturating_add(token_bytes) + .saturating_add(flag_bytes) + .saturating_add(import_bytes), + ) + } + Err( + guest::LowerError::Unparsable(message) + | guest::LowerError::UnsupportedFile(message), + ) => (1, message.len()), + Err(guest::LowerError::TooLarge | guest::LowerError::DeclarationOnly) => (0, 0), + } + } +} + +fn to_guest_manifests(manifests: Vec) -> Vec { + manifests + .into_iter() + .map(|manifest| guest::Manifest { + path: manifest.path, + text: manifest.text, + }) + .collect() +} + +fn map_language_plugin_error(error: PluginHostError) -> LanguagePluginError { + match error { + PluginHostError::MemoryLimitExceeded { name, memory_mb } => { + LanguagePluginError::MemoryLimitExceeded { + plugin: name, + memory_mb, + } + } + PluginHostError::TimeLimitExceeded { name, timeout_ms } => { + LanguagePluginError::TimeLimitExceeded { + plugin: name, + timeout_ms, + } + } + PluginHostError::Call { name, call, reason } => LanguagePluginError::Call { + plugin: name, + call, + reason, + }, + other => LanguagePluginError::Call { + plugin: String::new(), + call: "plugin", + reason: other.to_string(), + }, + } +} + fn owned_paths(repository_paths: &[RepoPath]) -> Vec { repository_paths .iter() @@ -302,6 +564,8 @@ fn convert_file_model(model: guest::FileModel) -> FileModel { end_line: function.end_line, decision_points: function.decision_points, source_lines: function.source_lines, + name: function.name, + cognitive_complexity: function.cognitive_complexity, }) .collect(), tokens: model @@ -355,11 +619,24 @@ fn convert_lower_error(error: guest::LowerError) -> LowerError { fn convert_resolution(resolution: guest::Resolution) -> language::Resolution { match resolution { guest::Resolution::Resolved(path) => language::Resolution::Resolved(path), - guest::Resolution::External => language::Resolution::External, + guest::Resolution::External(package) => language::Resolution::External(package), + guest::Resolution::Builtin => language::Resolution::Builtin, guest::Resolution::Unresolved(reason) => language::Resolution::Unresolved(reason), } } +fn convert_declared_dep(dep: guest::DeclaredDep) -> DeclaredDep { + DeclaredDep { + package_root: dep.package_root, + name: dep.name, + kind: match dep.kind { + guest::DepKind::Runtime => DepKind::Runtime, + guest::DepKind::Dev => DepKind::Dev, + guest::DepKind::Optional => DepKind::Optional, + }, + } +} + pub(crate) fn map_host_trap( name: &str, path: &Path, diff --git a/crates/plugin-host/src/wasm_metric.rs b/crates/plugin-host/src/wasm_metric.rs index 888c19c..78e346d 100644 --- a/crates/plugin-host/src/wasm_metric.rs +++ b/crates/plugin-host/src/wasm_metric.rs @@ -1,19 +1,20 @@ use std::path::Path; -use std::sync::Mutex; -use std::sync::atomic::{AtomicUsize, Ordering}; use codeint_config::PluginLimits; use codeint_model::{ CodeModel, ExternalFinding, ExternalMetricMeasurement, FileModel, ImportResolution, Metric, MetricPluginError, RepoPath, SourceSet, TokenKind, }; -use wasmtime::{Engine, Store}; +use wasmtime::Store; use crate::PluginHostError; -use crate::limits::{ - EpochTicker, LimitTrap, PluginStoreState, arm_call_deadline, classify_trap, new_limited_store, +use crate::limits::{LimitTrap, PluginStoreState, arm_call_deadline, classify_trap}; +use crate::wasm::{ContractSpec, InstancePool, instantiate_sandboxed_component, map_host_trap}; + +const METRIC_CONTRACT: ContractSpec = ContractSpec { + interface_prefix: "codeint:plugin/metric@", + expected_interface: "codeint:plugin/metric@0.2.0", }; -use crate::wasm::{compile_sandboxed_component, map_host_trap}; mod bindings { wasmtime::component::bindgen!({ @@ -27,22 +28,12 @@ use bindings::exports::codeint::plugin::metric as guest_metric; const RESERVED_KEYS: [&str; 3] = ["files", "source_lines", "packages"]; -struct MetricPluginInstance { - store: Store, - bindings: bindings::MetricPlugin, -} - pub struct WasmMetricPlugin { plugin_name: String, - limits: PluginLimits, key: String, display_name: String, description: String, - engine: Engine, - _ticker: EpochTicker, - pre: bindings::MetricPluginPre, - pool: Mutex>, - peak_memory_bytes: AtomicUsize, + instances: InstancePool, bindings::MetricPlugin>, } impl WasmMetricPlugin { @@ -52,89 +43,68 @@ impl WasmMetricPlugin { bytes: &[u8], limits: PluginLimits, ) -> Result { - let (engine, instance_pre) = compile_sandboxed_component(&plugin_name, path, bytes)?; - let ticker = EpochTicker::start(engine.clone()); - let pre = bindings::MetricPluginPre::new(instance_pre).map_err(|error| { - PluginHostError::Instantiate { - name: plugin_name.clone(), - path: path.to_path_buf(), - reason: error.to_string(), - } - })?; - let mut store = new_limited_store(&engine, limits); - let bindings = pre - .instantiate(&mut store) - .map_err(|error| map_host_trap(&plugin_name, path, None, limits, &store, error))?; - let api = bindings.codeint_plugin_metric(); - arm_call_deadline(&mut store, limits); - let key = api.call_key(&mut store).map_err(|error| { - map_host_trap(&plugin_name, path, Some("key"), limits, &store, error) + let mut component = instantiate_sandboxed_component( + &plugin_name, + path, + bytes, + limits, + METRIC_CONTRACT, + bindings::MetricPluginPre::new, + |pre, store| pre.instantiate(store), + )?; + let api = component.bindings.codeint_plugin_metric(); + arm_call_deadline(&mut component.store, limits); + let key = api.call_key(&mut component.store).map_err(|error| { + map_host_trap( + &plugin_name, + path, + Some("key"), + limits, + &component.store, + error, + ) })?; validate_metric_key(&plugin_name, &key)?; - arm_call_deadline(&mut store, limits); - let display_name = api.call_name(&mut store).map_err(|error| { - map_host_trap(&plugin_name, path, Some("name"), limits, &store, error) - })?; - arm_call_deadline(&mut store, limits); - let description = api.call_description(&mut store).map_err(|error| { + arm_call_deadline(&mut component.store, limits); + let display_name = api.call_name(&mut component.store).map_err(|error| { map_host_trap( &plugin_name, path, - Some("description"), + Some("name"), limits, - &store, + &component.store, error, ) })?; + arm_call_deadline(&mut component.store, limits); + let description = api + .call_description(&mut component.store) + .map_err(|error| { + map_host_trap( + &plugin_name, + path, + Some("description"), + limits, + &component.store, + error, + ) + })?; let display_name = if display_name.trim().is_empty() { key.clone() } else { display_name }; - let peak_memory_bytes = AtomicUsize::new(store.data().peak_memory_bytes()); Ok(WasmMetricPlugin { plugin_name, - limits, key, display_name, description, - engine, - _ticker: ticker, - pre, - pool: Mutex::new(vec![MetricPluginInstance { store, bindings }]), - peak_memory_bytes, + instances: InstancePool::from_component(component, limits), }) } pub fn peak_memory_bytes(&self) -> usize { - self.peak_memory_bytes.load(Ordering::Relaxed) - } - - fn record_peak_memory(&self, store: &Store) { - self.peak_memory_bytes - .fetch_max(store.data().peak_memory_bytes(), Ordering::Relaxed); - } - - fn checkout(&self) -> Result { - if let Ok(mut guard) = self.pool.lock() - && let Some(instance) = guard.pop() - { - return Ok(instance); - } - let mut store = new_limited_store(&self.engine, self.limits); - let bindings = self - .pre - .instantiate(&mut store) - .map_err(|error| map_metric_trap(&self.plugin_name, self.limits, &store, error))?; - self.record_peak_memory(&store); - Ok(MetricPluginInstance { store, bindings }) - } - - fn checkin(&self, instance: MetricPluginInstance) { - self.record_peak_memory(&instance.store); - if let Ok(mut guard) = self.pool.lock() { - guard.push(instance); - } + self.instances.peak_memory_bytes() } pub(crate) fn key_impl(&self) -> &str { @@ -154,21 +124,25 @@ impl WasmMetricPlugin { model: &CodeModel, ) -> Result { let guest_model = to_guest_code_model(model); - let mut instance = self.checkout()?; - arm_call_deadline(&mut instance.store, self.limits); + let limits = self.instances.limits(); + let mut instance = self.instances.checkout( + |pre, store| pre.instantiate(store), + |store, error| map_metric_trap(&self.plugin_name, limits, store, error), + )?; + arm_call_deadline(&mut instance.store, limits); let result = instance .bindings .codeint_plugin_metric() .call_measure(&mut instance.store, &guest_model); - self.record_peak_memory(&instance.store); + self.instances.record_peak_memory(&instance.store); match result { Ok(measurement) => { - self.checkin(instance); + self.instances.checkin(instance); convert_measurement(&self.plugin_name, measurement) } Err(error) => Err(map_metric_trap( &self.plugin_name, - self.limits, + limits, &instance.store, error, )), @@ -244,7 +218,10 @@ fn to_guest_code_model(model: &CodeModel) -> guest_metric::CodeModel { ImportResolution::Resolved(path) => { guest_language::Resolution::Resolved(path.as_str().to_owned()) } - ImportResolution::External => guest_language::Resolution::External, + ImportResolution::External(package) => { + guest_language::Resolution::External(package.clone()) + } + ImportResolution::Builtin => guest_language::Resolution::Builtin, ImportResolution::Unresolved { reason } => { guest_language::Resolution::Unresolved(reason.clone()) } @@ -276,6 +253,8 @@ fn to_guest_file_model(model: &FileModel) -> guest_language::FileModel { end_line: function.end_line, decision_points: function.decision_points, source_lines: function.source_lines, + name: function.name.clone(), + cognitive_complexity: function.cognitive_complexity, }) .collect(), tokens: model diff --git a/crates/plugin-host/tests/conformance.rs b/crates/plugin-host/tests/conformance.rs index 2c0b11e..8ed5a11 100644 --- a/crates/plugin-host/tests/conformance.rs +++ b/crates/plugin-host/tests/conformance.rs @@ -203,7 +203,7 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF specifier: (*specifier).to_owned(), }) .collect(); - let resolutions = plugin.resolve_imports(&repo_paths, valid_manifest, requests); + let resolutions = plugin.resolve_imports(&repo_paths, valid_manifest.clone(), requests); assert_eq!( resolutions.len(), fixture.import_requests.len(), @@ -214,10 +214,13 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF Resolution::Resolved(fixture.expected_resolved_target.to_owned()), "{label}: first import resolves" ); - assert_eq!( - resolutions[1], - Resolution::External, - "{label}: second import is external" + assert!( + matches!( + resolutions[1], + Resolution::External(_) | Resolution::Builtin + ), + "{label}: second import is external or builtin, got {:?}", + resolutions[1] ); assert!( matches!(resolutions[2], Resolution::Unresolved(_)), @@ -225,6 +228,19 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF resolutions[2] ); + let _deps = plugin + .declared_dependencies(valid_manifest.clone()) + .unwrap_or_else(|error| panic!("{label}: declared_dependencies failed: {error}")); + let entry_points = plugin + .entry_points(&repo_paths, valid_manifest) + .unwrap_or_else(|error| panic!("{label}: entry_points failed: {error}")); + for entry in &entry_points { + assert!( + fixture.repository_paths.contains(&entry.as_str()), + "{label}: entry_points returned {entry:?} outside repository_paths" + ); + } + let ranges = plugin .reference_ranges() .unwrap_or_else(|error| panic!("{label}: reference_ranges failed: {error}")); diff --git a/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs b/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs index c12f58d..aedf9bd 100644 --- a/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs @@ -156,8 +156,8 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, - Resolution, SourceSet, Token, TokenKind, WorkspaceError, + DeclaredDep, DepKind, FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, + Manifest, ReferenceRange, Resolution, SourceSet, Token, TokenKind, WorkspaceError, }; struct SampleMiniPlugin; @@ -186,9 +186,7 @@ fn strip_comment(line: &str) -> &str { fn source_set_of(path: &str) -> SourceSet { let file_name = path.rsplit('/').next().unwrap_or(path); - if file_name.ends_with(".test.mini") - || path.split('/').any(|segment| segment == "tests") - { + if file_name.ends_with(".test.mini") || path.split('/').any(|segment| segment == "tests") { SourceSet::Test } else { SourceSet::Production @@ -252,7 +250,10 @@ fn tokenize_line(code: &str, line_number: u32, is_import: bool, tokens: &mut Vec let text = &code[start..index]; let kind = if is_import { TokenKind::ImportOrExport - } else if matches!(text, "fn" | "if" | "else" | "while" | "return" | "let" | "pass") { + } else if matches!( + text, + "fn" | "if" | "else" | "while" | "return" | "let" | "pass" + ) { TokenKind::Other } else { TokenKind::Identifier @@ -284,14 +285,116 @@ fn extract_import_specifier(trimmed: &str) -> Option { Some(inner.to_string()) } +fn extract_function_name(trimmed: &str) -> Option { + let rest = trimmed.strip_prefix("fn")?.trim_start(); + let end = rest + .find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_') + .unwrap_or(rest.len()); + let name = &rest[..end]; + if name.is_empty() { + None + } else { + Some(name.to_string()) + } +} + struct OpenFunction { slot: usize, + name: Option, line: u32, brace_depth: u32, decision_points: u32, + cognitive_complexity: u32, source_lines: u32, } +fn is_workspace_directive(trimmed: &str) -> bool { + ["dep:", "dev-dep:", "opt-dep:", "entry:"] + .iter() + .any(|prefix| trimmed.starts_with(prefix)) +} + +fn push_function_header( + trimmed: &str, + line_number: u32, + functions: &mut Vec, + stack: &mut Vec, +) { + let opens_fn = + (trimmed.starts_with("fn ") || trimmed.starts_with("fn(")) && trimmed.contains('{'); + if !opens_fn { + return; + } + let slot = functions.len(); + let name = extract_function_name(trimmed); + functions.push(Function { + line: line_number, + end_line: line_number, + decision_points: 0, + source_lines: 0, + name: name.clone(), + cognitive_complexity: 0, + }); + stack.push(OpenFunction { + slot, + name, + line: line_number, + brace_depth: 0, + decision_points: 0, + cognitive_complexity: 0, + source_lines: 0, + }); +} + +fn update_function_stack( + code: &str, + trimmed: &str, + line_number: u32, + functions: &mut [Function], + stack: &mut Vec, +) -> Result<(), LowerError> { + let Some(current) = stack.last_mut() else { + if code.contains('}') { + return Err(LowerError::Unparsable(format!( + "unmatched closing brace at line {line_number}" + ))); + } + return Ok(()); + }; + current.source_lines += 1; + let nesting = current.brace_depth.saturating_sub(1); + for word in trimmed.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_') { + if matches!(word, "if" | "while") { + current.decision_points += 1; + current.cognitive_complexity += 1 + nesting; + } + } + for byte in code.bytes() { + if byte == b'{' { + current.brace_depth += 1; + } else if byte == b'}' { + if current.brace_depth == 0 { + return Err(LowerError::Unparsable(format!( + "unmatched closing brace at line {line_number}" + ))); + } + current.brace_depth -= 1; + } + } + if current.brace_depth == 0 { + let finished = stack.pop().unwrap(); + functions[finished.slot] = Function { + line: finished.line, + end_line: line_number, + decision_points: finished.decision_points, + source_lines: finished.source_lines, + name: finished.name, + cognitive_complexity: finished.cognitive_complexity, + }; + } + Ok(()) +} + impl Guest for SampleMiniPlugin { fn extensions() -> Vec { vec!["mini".to_string()] @@ -344,62 +447,14 @@ impl Guest for SampleMiniPlugin { } tokenize_line(code, line_number, is_import, &mut tokens); - - let opens_fn = trimmed.starts_with("fn ") && trimmed.contains('{'); - if opens_fn { - let slot = functions.len(); - functions.push(Function { - line: line_number, - end_line: line_number, - decision_points: 0, - source_lines: 0, - }); - stack.push(OpenFunction { - slot, - line: line_number, - brace_depth: 0, - decision_points: 0, - source_lines: 0, - }); - } - - if let Some(current) = stack.last_mut() { - current.source_lines += 1; - for word in trimmed.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_') { - if matches!(word, "if" | "while") { - current.decision_points += 1; - } - } - for byte in code.bytes() { - if byte == b'{' { - current.brace_depth += 1; - } else if byte == b'}' { - if current.brace_depth == 0 { - return Err(LowerError::Unparsable(format!( - "unmatched closing brace at line {line_number}" - ))); - } - current.brace_depth -= 1; - } - } - if current.brace_depth == 0 { - let finished = stack.pop().unwrap(); - functions[finished.slot] = Function { - line: finished.line, - end_line: line_number, - decision_points: finished.decision_points, - source_lines: finished.source_lines, - }; - } - } else if code.contains('}') { - return Err(LowerError::Unparsable(format!( - "unmatched closing brace at line {line_number}" - ))); - } + push_function_header(trimmed, line_number, &mut functions, &mut stack); + update_function_stack(code, trimmed, line_number, &mut functions, &mut stack)?; } if !stack.is_empty() { - return Err(LowerError::Unparsable("unclosed function block".to_string())); + return Err(LowerError::Unparsable( + "unclosed function block".to_string(), + )); } Ok(FileModel { @@ -427,7 +482,8 @@ impl Guest for SampleMiniPlugin { } for line in manifest.text.lines() { let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') { + if trimmed.is_empty() || trimmed.starts_with('#') || is_workspace_directive(trimmed) + { continue; } if let Some(message) = trimmed.strip_prefix("INVALID:") { @@ -450,8 +506,11 @@ impl Guest for SampleMiniPlugin { requests .into_iter() .map(|request| { + if request.specifier.starts_with("std:") { + return Resolution::Builtin; + } if !request.specifier.starts_with("./") { - return Resolution::External; + return Resolution::External(request.specifier); } let relative = request.specifier.trim_start_matches("./"); let folder = match request.importer.rsplit_once('/') { @@ -479,6 +538,55 @@ impl Guest for SampleMiniPlugin { .collect() } + fn declared_dependencies(manifests: Vec) -> Vec { + let mut deps = Vec::new(); + for manifest in manifests { + if manifest.path != "mini.workspace" { + continue; + } + for line in manifest.text.lines() { + let trimmed = line.trim(); + let entry = if let Some(name) = trimmed.strip_prefix("dep:") { + Some((name.trim(), DepKind::Runtime)) + } else if let Some(name) = trimmed.strip_prefix("dev-dep:") { + Some((name.trim(), DepKind::Dev)) + } else { + trimmed + .strip_prefix("opt-dep:") + .map(|name| (name.trim(), DepKind::Optional)) + }; + if let Some((name, kind)) = entry + && !name.is_empty() + { + deps.push(DeclaredDep { + package_root: String::new(), + name: name.to_string(), + kind, + }); + } + } + } + deps + } + + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + let mut entries = Vec::new(); + for manifest in manifests { + if manifest.path != "mini.workspace" { + continue; + } + for line in manifest.text.lines() { + if let Some(entry) = line.trim().strip_prefix("entry:") { + let candidate = entry.trim(); + if repository_paths.iter().any(|path| path == candidate) { + entries.push(candidate.to_string()); + } + } + } + } + entries + } + fn reference_ranges() -> Vec { vec![ReferenceRange { metric: "erosion".to_string(), diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock index 71ec695..cbdc564 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock @@ -22,6 +22,14 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "dual-version-language-plugin" +version = "0.1.0" +dependencies = [ + "probe-runtime", + "wit-bindgen", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -87,6 +95,22 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +[[package]] +name = "legacy-v0-1-0-language-plugin" +version = "0.1.0" +dependencies = [ + "probe-runtime", + "wit-bindgen", +] + +[[package]] +name = "legacy-v0-1-0-metric-plugin" +version = "0.1.0" +dependencies = [ + "probe-runtime", + "wit-bindgen", +] + [[package]] name = "log" version = "0.4.35" diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml index 62122b3..663993a 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml @@ -8,6 +8,9 @@ members = [ "loop-language", "memory-hog-language", "loop-metric", + "legacy-v0-1-0-language", + "legacy-v0-1-0-metric", + "dual-version-language", ] [workspace.package] diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs index f7b9f05..d8d1c1b 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs @@ -31,7 +31,7 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; @@ -65,6 +65,14 @@ impl Guest for ClockReaderPlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/Cargo.toml new file mode 100644 index 0000000..0f29b2d --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "dual-version-language-plugin" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +probe-runtime.workspace = true +wit-bindgen.workspace = true diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/src/lib.rs new file mode 100644 index 0000000..bfcf5cf --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/src/lib.rs @@ -0,0 +1,287 @@ +#![no_std] + +extern crate alloc; +extern crate probe_runtime; + +use alloc::string::{String, ToString}; +use alloc::vec; +use alloc::vec::Vec; + +wit_bindgen::generate!({ + world: "dual-language-plugin", + inline: " + package codeint:dual@0.2.0; + + world dual-language-plugin { + export codeint:plugin/language@0.1.0; + export codeint:plugin/language@0.2.0; + } + + package codeint:plugin@0.1.0 { + interface language { + record function { + line: u32, + end-line: u32, + decision-points: u32, + source-lines: u32, + } + + enum token-kind { + identifier, + literal, + other, + import-or-export, + } + + enum source-set { + production, + test, + generated, + vendored, + } + + record token { + kind: token-kind, + text-hash: u64, + line: u32, + } + + record flagged-line { + line: u32, + rule: string, + } + + record file-model { + source-set: source-set, + source-lines: u32, + functions: list, + tokens: list, + flagged-lines: list, + runtime-imports: list, + } + + record import-request { + importer: string, + specifier: string, + } + + variant resolution { + resolved(string), + external, + unresolved(string), + } + + variant lower-error { + unparsable(string), + unsupported-file(string), + too-large, + declaration-only, + } + + record manifest { + path: string, + text: string, + } + + record workspace-error { + path: string, + message: string, + } + + record reference-range { + metric: string, + low: f64, + high: f64, + source: string, + } + + extensions: func() -> list; + lower: func(path: string, text: string) -> result; + manifest-paths: func(repository-paths: list) -> list; + workspace-packages: func(manifests: list) -> result, workspace-error>; + resolve-imports: func(repository-paths: list, manifests: list, requests: list) -> list; + reference-ranges: func() -> list; + } + } + + package codeint:plugin@0.2.0 { + interface language { + record function { + line: u32, + end-line: u32, + decision-points: u32, + source-lines: u32, + name: option, + cognitive-complexity: u32, + } + + enum token-kind { + identifier, + literal, + other, + import-or-export, + } + + enum source-set { + production, + test, + generated, + vendored, + } + + record token { + kind: token-kind, + text-hash: u64, + line: u32, + } + + record flagged-line { + line: u32, + rule: string, + } + + record file-model { + source-set: source-set, + source-lines: u32, + functions: list, + tokens: list, + flagged-lines: list, + runtime-imports: list, + } + + record import-request { + importer: string, + specifier: string, + } + + variant resolution { + resolved(string), + external(string), + builtin, + unresolved(string), + } + + enum dep-kind { + runtime, + dev, + optional, + } + + record declared-dep { + package-root: string, + name: string, + kind: dep-kind, + } + + variant lower-error { + unparsable(string), + unsupported-file(string), + too-large, + declaration-only, + } + + record manifest { + path: string, + text: string, + } + + record workspace-error { + path: string, + message: string, + } + + record reference-range { + metric: string, + low: f64, + high: f64, + source: string, + } + + extensions: func() -> list; + lower: func(path: string, text: string) -> result; + manifest-paths: func(repository-paths: list) -> list; + workspace-packages: func(manifests: list) -> result, workspace-error>; + resolve-imports: func(repository-paths: list, manifests: list, requests: list) -> list; + declared-dependencies: func(manifests: list) -> list; + entry-points: func(repository-paths: list, manifests: list) -> list; + reference-ranges: func() -> list; + } + } + ", +}); + +struct DualVersionLanguagePlugin; + +export!(DualVersionLanguagePlugin); + +macro_rules! impl_common_guest { + ($pkg:ident) => { + fn extensions() -> Vec { + vec!["dual".to_string()] + } + + fn lower( + _path: String, + text: String, + ) -> Result< + exports::codeint::$pkg::language::FileModel, + exports::codeint::$pkg::language::LowerError, + > { + Ok(exports::codeint::$pkg::language::FileModel { + source_set: exports::codeint::$pkg::language::SourceSet::Production, + source_lines: text.lines().count() as u32, + functions: vec![], + tokens: vec![], + flagged_lines: vec![], + runtime_imports: vec![], + }) + } + + fn manifest_paths(_paths: Vec) -> Vec { + vec![] + } + + fn workspace_packages( + _manifests: Vec, + ) -> Result, exports::codeint::$pkg::language::WorkspaceError> { + Ok(vec![]) + } + + fn resolve_imports( + _paths: Vec, + _manifests: Vec, + _requests: Vec, + ) -> Vec { + vec![] + } + + fn reference_ranges() -> Vec { + vec![] + } + }; +} + +impl exports::codeint::plugin0_1_0::language::Guest for DualVersionLanguagePlugin { + impl_common_guest!(plugin0_1_0); +} + +impl exports::codeint::plugin0_2_0::language::Guest for DualVersionLanguagePlugin { + impl_common_guest!(plugin0_2_0); + + fn declared_dependencies( + _manifests: Vec, + ) -> Vec { + vec![exports::codeint::plugin0_2_0::language::DeclaredDep { + package_root: String::new(), + name: "dual-dep".to_string(), + kind: exports::codeint::plugin0_2_0::language::DepKind::Runtime, + }] + } + + fn entry_points( + repository_paths: Vec, + _manifests: Vec, + ) -> Vec { + repository_paths.into_iter().take(1).collect() + } +} diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs index 85486a2..ab20732 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs @@ -26,7 +26,7 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; @@ -59,6 +59,14 @@ impl Guest for FileReaderPlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/Cargo.toml new file mode 100644 index 0000000..4cd7a46 --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "legacy-v0-1-0-language-plugin" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +probe-runtime.workspace = true +wit-bindgen.workspace = true diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/src/lib.rs new file mode 100644 index 0000000..3b68e81 --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/src/lib.rs @@ -0,0 +1,150 @@ +#![no_std] + +extern crate alloc; +extern crate probe_runtime; + +use alloc::string::{String, ToString}; +use alloc::vec; +use alloc::vec::Vec; + +wit_bindgen::generate!({ + world: "language-plugin", + inline: " + package codeint:plugin@0.1.0; + + interface language { + record function { + line: u32, + end-line: u32, + decision-points: u32, + source-lines: u32, + } + + enum token-kind { + identifier, + literal, + other, + import-or-export, + } + + enum source-set { + production, + test, + generated, + vendored, + } + + record token { + kind: token-kind, + text-hash: u64, + line: u32, + } + + record flagged-line { + line: u32, + rule: string, + } + + record file-model { + source-set: source-set, + source-lines: u32, + functions: list, + tokens: list, + flagged-lines: list, + runtime-imports: list, + } + + record import-request { + importer: string, + specifier: string, + } + + variant resolution { + resolved(string), + external, + unresolved(string), + } + + variant lower-error { + unparsable(string), + unsupported-file(string), + too-large, + declaration-only, + } + + record manifest { + path: string, + text: string, + } + + record workspace-error { + path: string, + message: string, + } + + record reference-range { + metric: string, + low: f64, + high: f64, + source: string, + } + + extensions: func() -> list; + lower: func(path: string, text: string) -> result; + manifest-paths: func(repository-paths: list) -> list; + workspace-packages: func(manifests: list) -> result, workspace-error>; + resolve-imports: func(repository-paths: list, manifests: list, requests: list) -> list; + reference-ranges: func() -> list; + } + + world language-plugin { + export language; + } + ", +}); + +use exports::codeint::plugin::language::{ + FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, + WorkspaceError, +}; + +struct LegacyLanguagePlugin; + +export!(LegacyLanguagePlugin); + +impl Guest for LegacyLanguagePlugin { + fn extensions() -> Vec { + vec!["legacy".to_string()] + } + + fn lower(_path: String, _text: String) -> Result { + Ok(FileModel { + source_set: SourceSet::Production, + source_lines: 0, + functions: Vec::new(), + tokens: Vec::new(), + flagged_lines: Vec::new(), + runtime_imports: Vec::new(), + }) + } + + fn manifest_paths(_repository_paths: Vec) -> Vec { + Vec::new() + } + + fn workspace_packages(_manifests: Vec) -> Result, WorkspaceError> { + Ok(Vec::new()) + } + + fn resolve_imports( + _repository_paths: Vec, + _manifests: Vec, + _requests: Vec, + ) -> Vec { + Vec::new() + } + + fn reference_ranges() -> Vec { + Vec::new() + } +} diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/Cargo.toml new file mode 100644 index 0000000..835c4c9 --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "legacy-v0-1-0-metric-plugin" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +probe-runtime.workspace = true +wit-bindgen.workspace = true diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/src/lib.rs new file mode 100644 index 0000000..949b65d --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/src/lib.rs @@ -0,0 +1,137 @@ +#![no_std] + +extern crate alloc; +extern crate probe_runtime; + +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +wit_bindgen::generate!({ + world: "metric-plugin", + inline: " + package codeint:plugin@0.1.0; + + interface language { + record function { + line: u32, + end-line: u32, + decision-points: u32, + source-lines: u32, + } + + enum token-kind { + identifier, + literal, + other, + import-or-export, + } + + enum source-set { + production, + test, + generated, + vendored, + } + + record token { + kind: token-kind, + text-hash: u64, + line: u32, + } + + record flagged-line { + line: u32, + rule: string, + } + + record file-model { + source-set: source-set, + source-lines: u32, + functions: list, + tokens: list, + flagged-lines: list, + runtime-imports: list, + } + + variant resolution { + resolved(string), + external, + unresolved(string), + } + } + + interface metric { + use language.{file-model, resolution}; + + record source-file { + path: string, + model: file-model, + } + + record runtime-import { + importer: string, + specifier: string, + resolution: resolution, + } + + record code-model { + files: list, + runtime-imports: list, + workspace-packages: list, + } + + record finding { + id: string, + path: string, + line: u32, + end-line: option, + message: string, + } + + record measurement { + ratio: f64, + numerator: f64, + denominator: f64, + findings: list, + } + + key: func() -> string; + name: func() -> string; + description: func() -> string; + measure: func(model: code-model) -> measurement; + } + + world metric-plugin { + export metric; + } + ", +}); + +use exports::codeint::plugin::metric::{CodeModel, Guest, Measurement}; + +struct LegacyMetricPlugin; + +export!(LegacyMetricPlugin); + +impl Guest for LegacyMetricPlugin { + fn key() -> String { + "legacy_metric".to_string() + } + + fn name() -> String { + "Legacy metric".to_string() + } + + fn description() -> String { + "Test Metric plugin targeting codeint:plugin@0.1.0".to_string() + } + + fn measure(_model: CodeModel) -> Measurement { + Measurement { + ratio: 0.0, + numerator: 0.0, + denominator: 0.0, + findings: Vec::new(), + } + } +} diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs index 01ccb0a..389b473 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs @@ -13,14 +13,27 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, DepKind, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, + Resolution, SourceSet, WorkspaceError, }; struct LoopLanguagePlugin; export!(LoopLanguagePlugin); +fn trigger_loop_or_trap(manifests: &[Manifest]) { + for manifest in manifests { + if manifest.text.contains("LOOP_FOREVER") { + loop { + core::hint::spin_loop(); + } + } + if manifest.text.contains("PANIC_TRAP") { + panic!("probe trap"); + } + } +} + impl Guest for LoopLanguagePlugin { fn extensions() -> Vec { vec!["loop".to_string()] @@ -58,6 +71,20 @@ impl Guest for LoopLanguagePlugin { Vec::new() } + fn declared_dependencies(manifests: Vec) -> Vec { + trigger_loop_or_trap(&manifests); + vec![DeclaredDep { + package_root: String::new(), + name: "healthy-dep".to_string(), + kind: DepKind::Runtime, + }] + } + + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + trigger_loop_or_trap(&manifests); + repository_paths.into_iter().take(1).collect() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs index 2c4edac..43ab264 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs @@ -13,14 +13,50 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, DepKind, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, + Resolution, SourceSet, WorkspaceError, }; +fn aliased_strings(count: usize, chunk_bytes: usize) -> Vec { + let mut shared = String::with_capacity(chunk_bytes); + for _ in 0..chunk_bytes { + shared.push('a'); + } + let ptr = shared.as_mut_ptr(); + let len = shared.len(); + let cap = shared.capacity(); + core::mem::forget(shared); + let mut out = Vec::with_capacity(count); + for _ in 0..count { + out.push(unsafe { String::from_raw_parts(ptr, len, cap) }); + } + out +} + struct MemoryHogLanguagePlugin; export!(MemoryHogLanguagePlugin); +fn has_directive(manifests: &[Manifest], tag: &str) -> bool { + manifests.iter().any(|m| m.text.contains(tag)) +} + +fn alloc_2mb_if_requested(manifests: &[Manifest]) { + if has_directive(manifests, "ALLOC_2MB") { + let mut buf = Vec::new(); + buf.resize(2 * 1024 * 1024, 1u8); + core::hint::black_box(&buf); + } +} + +fn dep(package_root: &str, name: &str) -> DeclaredDep { + DeclaredDep { + package_root: package_root.to_string(), + name: name.to_string(), + kind: DepKind::Runtime, + } +} + impl Guest for MemoryHogLanguagePlugin { fn extensions() -> Vec { vec!["hog".to_string()] @@ -51,23 +87,70 @@ impl Guest for MemoryHogLanguagePlugin { }) } - fn manifest_paths(_repository_paths: Vec) -> Vec { - Vec::new() + fn manifest_paths(_paths: Vec) -> Vec { + vec![] } fn workspace_packages(_manifests: Vec) -> Result, WorkspaceError> { - Ok(Vec::new()) + Ok(vec![]) } fn resolve_imports( - _repository_paths: Vec, + _paths: Vec, _manifests: Vec, _requests: Vec, ) -> Vec { - Vec::new() + vec![] + } + + fn declared_dependencies(manifests: Vec) -> Vec { + alloc_2mb_if_requested(&manifests); + if has_directive(&manifests, "ALIASED_BOMB") { + return aliased_strings(256, 32 * 1024) + .into_iter() + .map(|name| DeclaredDep { + package_root: String::new(), + name, + kind: DepKind::Runtime, + }) + .collect(); + } + if has_directive(&manifests, "INVALID_EMPTY_NAME") { + return vec![dep("", "")]; + } + if has_directive(&manifests, "INVALID_WHITESPACE_NAME") { + return vec![dep("", " ")]; + } + if has_directive(&manifests, "INVALID_TRAVERSAL_ROOT") { + return vec![dep("../escape", "serde")]; + } + if has_directive(&manifests, "INVALID_ABSOLUTE_ROOT") { + return vec![dep("/etc/shadow", "serde")]; + } + if has_directive(&manifests, "INVALID_BACKSLASH_ROOT") { + return vec![dep("packages\\app", "serde")]; + } + vec![dep("", "healthy-dep")] + } + + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + alloc_2mb_if_requested(&manifests); + if has_directive(&manifests, "ALIASED_BOMB") { + return aliased_strings(256, 32 * 1024); + } + for (tag, bad) in [ + ("INVALID_TRAVERSAL", "../../../etc/passwd"), + ("INVALID_ABSOLUTE", "/etc/shadow"), + ("INVALID_UNKNOWN", "src/missing.hog"), + ] { + if has_directive(&manifests, tag) { + return vec![bad.to_string()]; + } + } + repository_paths.into_iter().take(1).collect() } fn reference_ranges() -> Vec { - Vec::new() + vec![] } } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs index e0ec236..e783d68 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs @@ -65,7 +65,7 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; @@ -101,6 +101,14 @@ impl Guest for SocketOpenerPlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/load.rs b/crates/plugin-host/tests/load.rs index 0e4e38b..1636158 100644 --- a/crates/plugin-host/tests/load.rs +++ b/crates/plugin-host/tests/load.rs @@ -6,14 +6,14 @@ use std::sync::OnceLock; use codeint_config::{ PluginDeclaration, PluginHostConfig, PluginKind, PluginLimits, PluginSource, Sha256Digest, }; -use codeint_model::language::{Function, ImportRequest, Resolution}; +use codeint_model::language::{DeclaredDep, DepKind, Function, ImportRequest, Resolution}; use codeint_model::{ - CodeModel, FileModel, LanguagePlugin, LowerError, Manifest, MetricPlugin, MetricPluginError, - RepoPath, SourceFile, SourceSet, Token, TokenKind, token_text_hash, + CodeModel, FileModel, LanguagePlugin, LanguagePluginError, LowerError, Manifest, MetricPlugin, + MetricPluginError, RepoPath, SourceFile, SourceSet, Token, TokenKind, token_text_hash, }; use codeint_plugin_host::{ - PluginHostError, load_language_plugin, load_language_plugin_with_limits, load_language_plugins, - load_metric_plugin, load_metric_plugin_with_limits, load_metric_plugins, + PluginHostError, WasmLanguagePlugin, load_language_plugin, load_language_plugin_with_limits, + load_language_plugins, load_metric_plugin, load_metric_plugin_with_limits, load_metric_plugins, }; use common::{build_fixture_workspace, declaration_for, declaration_with_kind, sample_plugin_wasm}; @@ -90,7 +90,9 @@ fn loads_sample_external_plugin_with_zero_capabilities_and_valid_hash() { assert_eq!(model.source_set, SourceSet::Production); assert_eq!(model.source_lines, 6); assert_eq!(model.functions.len(), 1); + assert_eq!(model.functions[0].name.as_deref(), Some("main")); assert_eq!(model.functions[0].decision_points, 1); + assert_eq!(model.functions[0].cognitive_complexity, 1); assert_eq!(model.runtime_imports, vec!["./util"]); assert_eq!(model.flagged_lines.len(), 1); assert_eq!(model.flagged_lines[0].rule, "redundant-pass"); @@ -126,13 +128,18 @@ fn loads_sample_external_plugin_with_zero_capabilities_and_valid_hash() { importer: "src/app.mini".to_owned(), specifier: "external-pkg".to_owned(), }, + ImportRequest { + importer: "src/app.mini".to_owned(), + specifier: "std:io".to_owned(), + }, ], ); assert_eq!( resolutions, vec![ Resolution::Resolved("src/util.mini".to_owned()), - Resolution::External, + Resolution::External("external-pkg".to_owned()), + Resolution::Builtin, ] ); } @@ -205,12 +212,16 @@ fn loads_sample_external_metric_plugin_with_zero_capabilities_and_measures_code_ end_line: 3, decision_points: 0, source_lines: 3, + name: Some("brief".to_owned()), + cognitive_complexity: 0, }, Function { line: 5, end_line: 18, decision_points: 1, source_lines: 14, + name: Some("verbose".to_owned()), + cognitive_complexity: 1, }, ], tokens: vec![Token { @@ -559,3 +570,376 @@ fn built_in_and_sample_plugins_fit_comfortably_within_default_limits() { assert!(metric_peak < defaults.memory_bytes()); assert!(metric_elapsed.as_millis() < u128::from(defaults.timeout_ms)); } + +#[test] +fn verifies_0_2_0_contract_fields_and_methods_across_wasm_boundary() { + let wasm_path = sample_plugin_wasm(); + let declaration = declaration_for("sample-mini", wasm_path); + let plugin = load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default()) + .expect("0.2.0 sample plugin loads"); + + let lowered = plugin + .lower( + &RepoPath::new("src/main.mini").expect("valid repo path"), + "fn outer(x) {\n if x {\n while x {\n return x\n }\n }\n}\nfn() {\n return 1\n}\n", + ) + .expect("lowers named and anonymous functions"); + assert_eq!(lowered.functions.len(), 2); + assert_eq!(lowered.functions[0].name.as_deref(), Some("outer")); + assert_eq!(lowered.functions[0].decision_points, 2); + assert_eq!(lowered.functions[0].cognitive_complexity, 3); + assert_eq!(lowered.functions[1].name, None); + assert_eq!(lowered.functions[1].cognitive_complexity, 0); + + let repo_paths = vec![ + RepoPath::new("mini.workspace").expect("valid repo path"), + RepoPath::new("src/main.mini").expect("valid repo path"), + RepoPath::new("src/util.mini").expect("valid repo path"), + ]; + let manifests = vec![Manifest { + path: "mini.workspace".to_owned(), + text: "packages/core\ndep:serde\ndev-dep:testkit\nopt-dep:extras\nentry:src/main.mini\nentry:src/missing.mini\n".to_owned(), + }]; + + assert_eq!( + plugin + .declared_dependencies(manifests.clone()) + .expect("valid declared dependencies"), + vec![ + DeclaredDep { + package_root: String::new(), + name: "serde".to_owned(), + kind: DepKind::Runtime, + }, + DeclaredDep { + package_root: String::new(), + name: "testkit".to_owned(), + kind: DepKind::Dev, + }, + DeclaredDep { + package_root: String::new(), + name: "extras".to_owned(), + kind: DepKind::Optional, + }, + ] + ); + assert_eq!( + plugin + .entry_points(&repo_paths, manifests.clone()) + .expect("valid entry points"), + vec![RepoPath::new("src/main.mini").expect("valid repo path")] + ); + assert_eq!( + plugin.resolve_imports( + &repo_paths, + manifests, + vec![ + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "./util".to_owned(), + }, + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "serde".to_owned(), + }, + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "std:fs".to_owned(), + }, + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "./missing".to_owned(), + }, + ], + ), + vec![ + Resolution::Resolved("src/util.mini".to_owned()), + Resolution::External("serde".to_owned()), + Resolution::Builtin, + Resolution::Unresolved("cannot find src/missing.mini".to_owned()), + ] + ); +} + +fn assert_incompatible_contract_error( + error: PluginHostError, + plugin_name: &str, + expected_interface: &str, + found_interface: &str, +) { + assert!( + matches!( + &error, + PluginHostError::IncompatibleContractVersion { + name, + expected, + found, + .. + } if name == plugin_name + && *expected == expected_interface + && found == found_interface + ), + "expected IncompatibleContractVersion, got: {error}" + ); + let rendered = error.to_string(); + assert!( + rendered.contains(plugin_name) + && rendered.contains(found_interface) + && rendered.contains(expected_interface) + && rendered.contains("rebuild"), + "expected actionable version-mismatch error, got: {rendered}" + ); +} + +#[test] +fn rejects_v0_1_0_language_plugin_with_actionable_version_mismatch_error() { + let wasm_path = sandbox_probe_wasm("legacy_v0_1_0_language_plugin.wasm"); + let declaration = declaration_for("legacy-lang", &wasm_path); + + let error = load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default()) + .err() + .expect("0.1.0 Language plugin must be rejected by 0.2.0 host"); + + assert_incompatible_contract_error( + error, + "legacy-lang", + "codeint:plugin/language@0.2.0", + "codeint:plugin/language@0.1.0", + ); +} + +#[test] +fn rejects_v0_1_0_metric_plugin_with_actionable_version_mismatch_error() { + let wasm_path = sandbox_probe_wasm("legacy_v0_1_0_metric_plugin.wasm"); + let declaration = declaration_with_kind("legacy-metric", PluginKind::Metric, &wasm_path); + + let error = load_metric_plugin(Path::new("."), &declaration, &PluginHostConfig::default()) + .err() + .expect("0.1.0 Metric plugin must be rejected by 0.2.0 host"); + + assert_incompatible_contract_error( + error, + "legacy-metric", + "codeint:plugin/metric@0.2.0", + "codeint:plugin/metric@0.1.0", + ); +} + +fn trigger_manifest(directive: &str) -> Vec { + vec![Manifest { + path: "trigger.manifest".to_owned(), + text: directive.to_owned(), + }] +} + +fn load_probe(name: &str, wasm_file: &str, limits: PluginLimits) -> WasmLanguagePlugin { + let wasm_path = sandbox_probe_wasm(wasm_file); + load_language_plugin_with_limits( + Path::new("."), + &declaration_for(name, &wasm_path), + &PluginHostConfig::default(), + limits, + ) + .expect("probe plugin loads") +} + +fn assert_memory_err( + result: Result, + expected_plugin: &str, + expected_mb: u64, +) { + assert!( + matches!( + result, + Err(LanguagePluginError::MemoryLimitExceeded { + ref plugin, + memory_mb, + }) if plugin == expected_plugin && memory_mb == expected_mb + ), + "expected MemoryLimitExceeded({expected_plugin}, {expected_mb}), got: {result:?}" + ); +} + +#[test] +fn declared_dependencies_and_entry_points_propagate_timeout_trap_and_oom_and_recover() { + let loop_plugin = load_probe( + "loop-lang", + "loop_language_plugin.wasm", + PluginLimits { + memory_mb: 4, + timeout_ms: 150, + }, + ); + let repo_paths = vec![RepoPath::new("src/main.loop").expect("valid repo path")]; + + assert!(matches!( + loop_plugin.declared_dependencies(trigger_manifest("LOOP_FOREVER")), + Err(LanguagePluginError::TimeLimitExceeded { + ref plugin, + timeout_ms: 150, + }) if plugin == "loop-lang" + )); + assert!(matches!( + loop_plugin.declared_dependencies(trigger_manifest("PANIC_TRAP")), + Err(LanguagePluginError::Call { + ref plugin, + call: "declared-dependencies", + .. + }) if plugin == "loop-lang" + )); + assert_eq!( + loop_plugin + .declared_dependencies(Vec::new()) + .expect("healthy declared_dependencies succeeds after trap") + .len(), + 1 + ); + + assert!(matches!( + loop_plugin.entry_points(&repo_paths, trigger_manifest("LOOP_FOREVER")), + Err(LanguagePluginError::TimeLimitExceeded { + ref plugin, + timeout_ms: 150, + }) if plugin == "loop-lang" + )); + assert!(matches!( + loop_plugin.entry_points(&repo_paths, trigger_manifest("PANIC_TRAP")), + Err(LanguagePluginError::Call { + ref plugin, + call: "entry-points", + .. + }) if plugin == "loop-lang" + )); + assert_eq!( + loop_plugin + .entry_points(&repo_paths, Vec::new()) + .expect("healthy entry_points succeeds after trap"), + repo_paths + ); + + let hog_plugin = load_probe( + "hog-lang", + "memory_hog_language_plugin.wasm", + PluginLimits { + memory_mb: 2, + timeout_ms: 1_000, + }, + ); + let hog_paths = vec![RepoPath::new("src/main.hog").expect("valid repo path")]; + + assert_memory_err( + hog_plugin.declared_dependencies(trigger_manifest("ALLOC_2MB")), + "hog-lang", + 2, + ); + assert_memory_err( + hog_plugin.entry_points(&hog_paths, trigger_manifest("ALLOC_2MB")), + "hog-lang", + 2, + ); + assert_eq!( + hog_plugin + .entry_points(&hog_paths, Vec::new()) + .expect("healthy entry_points recovers after OOM trap"), + hog_paths + ); +} + +#[test] +fn rejects_canonical_abi_aliased_string_amplification_bomb() { + let plugin = load_probe( + "hog-lang", + "memory_hog_language_plugin.wasm", + PluginLimits { + memory_mb: 2, + timeout_ms: 1_000, + }, + ); + let repo_paths = vec![RepoPath::new("src/main.hog").expect("valid repo path")]; + + assert_memory_err( + plugin.entry_points(&repo_paths, trigger_manifest("ALIASED_BOMB")), + "hog-lang", + 2, + ); + assert_memory_err( + plugin.declared_dependencies(trigger_manifest("ALIASED_BOMB")), + "hog-lang", + 2, + ); + assert_eq!( + plugin + .entry_points(&repo_paths, Vec::new()) + .expect("plugin recovers after aliased-string bomb is rejected"), + repo_paths + ); +} + +#[test] +fn rejects_invalid_entry_points_and_declared_dependencies_from_wasm_plugin() { + let plugin = load_probe( + "hog-lang", + "memory_hog_language_plugin.wasm", + PluginLimits::default(), + ); + let repo_paths = vec![RepoPath::new("src/main.hog").expect("valid repo path")]; + + assert!(matches!( + plugin.entry_points(&repo_paths, trigger_manifest("INVALID_TRAVERSAL")), + Err(LanguagePluginError::InvalidEntryPointPath { ref path }) + if path == "../../../etc/passwd" + )); + assert!(matches!( + plugin.entry_points(&repo_paths, trigger_manifest("INVALID_ABSOLUTE")), + Err(LanguagePluginError::InvalidEntryPointPath { ref path }) if path == "/etc/shadow" + )); + assert!(matches!( + plugin.entry_points(&repo_paths, trigger_manifest("INVALID_UNKNOWN")), + Err(LanguagePluginError::UnknownEntryPoint { ref path }) if path == "src/missing.hog" + )); + + for directive in ["INVALID_EMPTY_NAME", "INVALID_WHITESPACE_NAME"] { + assert!(matches!( + plugin.declared_dependencies(trigger_manifest(directive)), + Err(LanguagePluginError::EmptyDependencyName { .. }) + )); + } + for (directive, expected) in [ + ("INVALID_TRAVERSAL_ROOT", "../escape"), + ("INVALID_ABSOLUTE_ROOT", "/etc/shadow"), + ("INVALID_BACKSLASH_ROOT", "packages\\app"), + ] { + assert!(matches!( + plugin.declared_dependencies(trigger_manifest(directive)), + Err(LanguagePluginError::InvalidDependencyPackageRoot { ref package_root }) + if package_root == expected + )); + } +} + +#[test] +fn loads_dual_version_language_plugin_exporting_0_1_0_and_0_2_0() { + let plugin = load_probe( + "dual-lang", + "dual_version_language_plugin.wasm", + PluginLimits::default(), + ); + assert_eq!(plugin.extensions(), vec!["dual"]); + let repo_paths = vec![RepoPath::new("src/app.dual").expect("valid repo path")]; + assert_eq!( + plugin + .entry_points(&repo_paths, Vec::new()) + .expect("dual plugin entry_points"), + repo_paths + ); + assert_eq!( + plugin + .declared_dependencies(Vec::new()) + .expect("dual plugin declared_dependencies"), + vec![DeclaredDep { + package_root: String::new(), + name: "dual-dep".to_owned(), + kind: DepKind::Runtime, + }] + ); +} diff --git a/docs/plugins.md b/docs/plugins.md index 075f9b7..24cb702 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -6,11 +6,11 @@ This guide explains how to build, hash, declare, and test a Language plugin and ## Versioned WIT contract -codeint defines its Plugin contract in `package codeint:plugin@0.1.0`. +codeint defines its Plugin contract in `package codeint:plugin@0.2.0`. Two WIT files hold the contract: -- [wit/language.wit](../wit/language.wit) defines `codeint:plugin/language@0.1.0` and the `language-plugin` world. -- [wit/metric.wit](../wit/metric.wit) defines `codeint:plugin/metric@0.1.0` and the `metric-plugin` world. +- [wit/language.wit](../wit/language.wit) defines `codeint:plugin/language@0.2.0` and the `language-plugin` world. +- [wit/metric.wit](../wit/metric.wit) defines `codeint:plugin/metric@0.2.0` and the `metric-plugin` world. The `metric` interface reuses `file-model` and `resolution` from `language`. A Language plugin exports `language` and lowers source files into the Code model. @@ -70,8 +70,8 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, - Resolution, SourceSet, Token, TokenKind, WorkspaceError, + DeclaredDep, DepKind, FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, + Manifest, ReferenceRange, Resolution, SourceSet, Token, TokenKind, WorkspaceError, }; struct SampleMiniPlugin; @@ -81,23 +81,25 @@ export!(SampleMiniPlugin); ### Required functions -Implement all six functions on `Guest`: +Implement all eight functions on `Guest`: | Function | Responsibility | | -------- | -------------- | | `extensions() -> list` | Return file extensions without a leading dot, such as `["mini"]`. | -| `lower(path, text) -> result` | Lower one file into its `source-set`, `source-lines`, `functions`, `tokens`, `flagged-lines`, and `runtime-imports`. Return `declaration-only`, `unparsable`, `unsupported-file`, or `too-large` on error. | +| `lower(path, text) -> result` | Lower one file into its `source-set`, `source-lines`, `functions` (each with optional `name` and nesting-weighted `cognitive-complexity`), `tokens`, `flagged-lines`, and `runtime-imports`. Return `declaration-only`, `unparsable`, `unsupported-file`, or `too-large` on error. | | `manifest-paths(repository-paths) -> list` | Select manifest paths from `repository-paths` that the host reads once on the Plugin's behalf. | | `workspace-packages(manifests) -> result, workspace-error>` | Return relative Workspace package roots from the manifest contents, or an empty list for a single-package repository. | -| `resolve-imports(repository-paths, manifests, requests) -> list` | Return one `resolved`, `external`, or `unresolved` entry per request, in request order. | +| `resolve-imports(repository-paths, manifests, requests) -> list` | Return one `resolved(string)`, `external(string)` (carrying the canonical package name), `builtin` (for standard-library or runtime built-ins), or `unresolved(string)` entry per request, in request order. | +| `declared-dependencies(manifests) -> list` | Extract manifest-declared external dependencies (`package-root`, normalized `name`, and `kind` of `runtime`, `dev`, or `optional`). | +| `entry-points(repository-paths, manifests) -> list` | Discover standard entry-point source files from `repository-paths` and `manifests`, returning only paths from `repository-paths`. | | `reference-ranges() -> list` | Return published Reference ranges for this language, at most one per Metric. | Follow these invariants in `lower`: -- Keep `functions` sorted by start `line` (`line >= 1` and `line <= end-line`). +- Keep `functions` sorted by start `line` (`line >= 1` and `line <= end-line`), with `name` set to `none` for anonymous lambdas or closures. - Keep `tokens` sorted by 1-based `line`, with 64-bit FNV-1a `text-hash` values of each token's UTF-8 text. - Produce identical `source-lines` and `functions` for LF and CRLF line endings. -- Do not count nested functions' decision points or source lines in their enclosing function. +- Do not count nested functions' decision points, cognitive complexity, or source lines in their enclosing function. ### Compile the sample Language plugin @@ -261,7 +263,8 @@ The suite verifies: - Ordered `functions` and `tokens`, valid 1-based line spans, and non-empty Flagged line rules. - `manifest-paths` returning only paths from `repository-paths`. - `workspace-packages` parsing valid manifests and returning `WorkspaceError::Manifest` on invalid manifests. -- `resolve-imports` returning one `Resolved`, `External`, or `Unresolved` result per request in request order. +- `resolve-imports` returning one `Resolved`, `External`, `Builtin`, or `Unresolved` result per request in request order. +- `declared-dependencies` returning manifest-declared dependencies and `entry-points` returning only paths from `repository-paths`. - `reference-ranges` returning valid ranges. - Safe concurrent `lower` calls across threads. @@ -301,10 +304,10 @@ cargo test --locked -p codeint-cli --test plugins The WIT package declaration carries a Semantic Versioning number: ```wit -package codeint:plugin@0.1.0; +package codeint:plugin@0.2.0; ``` -This version identifies the exported interfaces `codeint:plugin/language@0.1.0` and `codeint:plugin/metric@0.1.0` in the compiled WebAssembly component. +This version identifies the exported interfaces `codeint:plugin/language@0.2.0` and `codeint:plugin/metric@0.2.0` in the compiled WebAssembly component. ### Compatibility rules @@ -319,6 +322,6 @@ This version identifies the exported interfaces `codeint:plugin/language@0.1.0` `wasmtime::component::bindgen!` binds the codeint host to the exact WIT interface version compiled into the binary. At load time, wasmtime checks that the component's exported interface name and version match what the host expects. -- A Plugin built against an incompatible WIT version fails to instantiate with exit code 2, and the error names the mismatched interface version. +- A Plugin built against an incompatible WIT version (such as `codeint:plugin@0.1.0`) fails at load time with exit code 2, naming the plugin, its found interface version, the required `0.2.0` interface version, and how to rebuild it. - Rebuild the Plugin against the updated `wit/` files and update its `sha256` in `codeint.json` when upgrading to a breaking WIT version. - Never silently mutate an existing released WIT version in place; every breaking change gets a new version number. diff --git a/plugins/languages/dart/src/lib.rs b/plugins/languages/dart/src/lib.rs index e75d065..9179e00 100644 --- a/plugins/languages/dart/src/lib.rs +++ b/plugins/languages/dart/src/lib.rs @@ -11,8 +11,8 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, Token, - TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + Token, TokenKind, WorkspaceError, }; use codeint_model::token_text_hash; @@ -71,6 +71,10 @@ fn lower_dart(path: &str, text: &str) -> Result { } impl Guest for Dart { + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + fn workspace_packages(manifests: Vec) -> Result, WorkspaceError> { workspaces::discover(&manifests) } @@ -91,6 +95,10 @@ impl Guest for Dart { lower_dart(&path, &text) } + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn extensions() -> Vec { vec!["dart".to_owned()] } diff --git a/plugins/languages/dart/src/resolution.rs b/plugins/languages/dart/src/resolution.rs index decdd34..3477ce9 100644 --- a/plugins/languages/dart/src/resolution.rs +++ b/plugins/languages/dart/src/resolution.rs @@ -55,7 +55,7 @@ fn resolve_one( ) -> Resolution { let spec = request.specifier.as_str(); if spec.starts_with("dart:") { - return Resolution::External; + return Resolution::Builtin; } if let Some(pkg_rest) = spec.strip_prefix("package:") { return resolve_package_uri(files, packages, &request.importer, pkg_rest); @@ -70,10 +70,10 @@ fn resolve_package_uri( pkg_rest: &str, ) -> Resolution { let Some((pkg_name, rel_path)) = pkg_rest.split_once('/') else { - return Resolution::External; + return Resolution::External(String::new()); }; let Some(pkg_dir) = packages.get(pkg_name) else { - return Resolution::External; + return Resolution::External(String::new()); }; let candidate = if pkg_dir.is_empty() { format!("lib/{rel_path}") @@ -82,7 +82,7 @@ fn resolve_package_uri( }; if files.contains(&candidate) { if candidate == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(candidate) } diff --git a/plugins/languages/dart/tests/conformance.rs b/plugins/languages/dart/tests/conformance.rs index 145de3b..7f5f719 100644 --- a/plugins/languages/dart/tests/conformance.rs +++ b/plugins/languages/dart/tests/conformance.rs @@ -30,6 +30,17 @@ fn dart_contract_basics() { ); } +fn func(line: u32, end_line: u32, decision_points: u32, source_lines: u32) -> Function { + Function { + line, + end_line, + decision_points, + source_lines, + name: None, + cognitive_complexity: 0, + } +} + #[test] fn dart_functions_and_decisions() { let model = lower( @@ -43,23 +54,7 @@ fn dart_functions_and_decisions() { }\n", ) .unwrap(); - assert_eq!( - model.functions, - [ - Function { - line: 1, - end_line: 7, - decision_points: 6, - source_lines: 7 - }, - Function { - line: 5, - end_line: 5, - decision_points: 1, - source_lines: 1 - }, - ] - ); + assert_eq!(model.functions, [func(1, 7, 6, 7), func(5, 5, 1, 1)]); } #[test] @@ -106,8 +101,8 @@ fn dart_directives_and_resolution() { ); assert_eq!(res[0], Resolution::Resolved("lib/u.dart".into())); assert_eq!(res[1], Resolution::Resolved("lib/h.dart".into())); - assert_eq!(res[2], Resolution::External); - assert_eq!(res[3], Resolution::External); + assert_eq!(res[2], Resolution::Builtin); + assert_eq!(res[3], Resolution::External(String::new())); assert!(matches!(res[4], Resolution::Unresolved(_))); } diff --git a/plugins/languages/php/src/lib.rs b/plugins/languages/php/src/lib.rs index f2433f6..f95671e 100644 --- a/plugins/languages/php/src/lib.rs +++ b/plugins/languages/php/src/lib.rs @@ -11,8 +11,8 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, Token, - TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + Token, TokenKind, WorkspaceError, }; use codeint_model::token_text_hash; @@ -97,4 +97,12 @@ impl Guest for Php { ) -> Vec { resolution::resolve_batch(&repository_paths, &manifests, &requests) } + + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } } diff --git a/plugins/languages/php/src/resolution.rs b/plugins/languages/php/src/resolution.rs index e50e821..27bdb6b 100644 --- a/plugins/languages/php/src/resolution.rs +++ b/plugins/languages/php/src/resolution.rs @@ -47,7 +47,7 @@ impl PhpResolver { match request.specifier.split_once(':') { Some(("use", ns_path)) => self.resolve_psr4(&request.importer, ns_path), Some(("req", req_path)) => self.resolve_require(&request.importer, req_path), - _ => Resolution::External, + _ => Resolution::External(String::new()), } } @@ -63,13 +63,13 @@ impl PhpResolver { let rel = rest.replace('\\', "/"); if let Some(hit) = self.first_matching_file(&rule.dirs, &rel) { return if hit == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(hit) }; } } - Resolution::External + Resolution::External(String::new()) } fn first_matching_file(&self, dirs: &[String], rel: &str) -> Option { diff --git a/plugins/languages/php/tests/conformance.rs b/plugins/languages/php/tests/conformance.rs index 382b1ef..5c0d791 100644 --- a/plugins/languages/php/tests/conformance.rs +++ b/plugins/languages/php/tests/conformance.rs @@ -75,12 +75,16 @@ fn php_decision_points_cover_control_flow_match_and_arrow_functions() { end_line: 16, decision_points: 8, source_lines: 15, + name: None, + cognitive_complexity: 0, }, Function { line: 10, end_line: 10, decision_points: 1, source_lines: 1, + name: None, + cognitive_complexity: 0, }, ] ); @@ -197,6 +201,6 @@ fn php_resolver_handles_psr4_and_static_require() { Resolution::Resolved("app/Models/Order.php".to_owned()) ); assert_eq!(out[1], Resolution::Resolved("app/helpers.php".to_owned())); - assert_eq!(out[2], Resolution::External); + assert_eq!(out[2], Resolution::External(String::new())); assert!(matches!(out[3], Resolution::Unresolved(_))); } diff --git a/plugins/languages/python/src/lib.rs b/plugins/languages/python/src/lib.rs index b061293..5916f89 100644 --- a/plugins/languages/python/src/lib.rs +++ b/plugins/languages/python/src/lib.rs @@ -9,8 +9,8 @@ mod source_set; mod workspaces; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, Token, - TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + Token, TokenKind, WorkspaceError, }; use codeint_model::scan::build_reference_ranges; use codeint_model::token_text_hash; @@ -52,6 +52,14 @@ impl Guest for Python { resolution::resolve_all(&repository_paths, &manifests, &requests) } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn lower(path: String, text: String) -> Result { if !path.ends_with(".py") { return Err(LowerError::UnsupportedFile(format!( diff --git a/plugins/languages/python/src/resolution.rs b/plugins/languages/python/src/resolution.rs index 62a3d46..3551769 100644 --- a/plugins/languages/python/src/resolution.rs +++ b/plugins/languages/python/src/resolution.rs @@ -74,11 +74,11 @@ fn resolve_one( } if let Some(target) = module_map.get(specifier) { if target == importer { - return Resolution::External; + return Resolution::External(String::new()); } return Resolution::Resolved(target.clone()); } - Resolution::External + Resolution::External(String::new()) } fn resolve_relative(py_files: &HashSet, importer: &str, specifier: &str) -> Resolution { @@ -107,7 +107,7 @@ fn resolve_relative(py_files: &HashSet, importer: &str, specifier: &str) for candidate in candidates { if py_files.contains(&candidate) { if candidate == importer { - return Resolution::External; + return Resolution::External(String::new()); } return Resolution::Resolved(candidate); } diff --git a/plugins/languages/python/tests/conformance.rs b/plugins/languages/python/tests/conformance.rs index 5ccd9ed..9e6bfed 100644 --- a/plugins/languages/python/tests/conformance.rs +++ b/plugins/languages/python/tests/conformance.rs @@ -56,6 +56,8 @@ fn python_functions_decisions_and_source_sets() { end_line: 10, decision_points: 4, source_lines: 10, + name: None, + cognitive_complexity: 0, } ); assert_eq!(model.functions[1].decision_points, 1); @@ -143,7 +145,7 @@ fn python_imports_type_checking_resolution_and_workspaces() { resolutions[1], Resolution::Resolved("src/demo/utils.py".into()) ); - assert_eq!(resolutions[2], Resolution::External); + assert_eq!(resolutions[2], Resolution::External(String::new())); assert!(matches!(resolutions[3], Resolution::Unresolved(_))); let packages = Python diff --git a/plugins/languages/rust/src/functions.rs b/plugins/languages/rust/src/functions.rs index 1aa23fe..1c85547 100644 --- a/plugins/languages/rust/src/functions.rs +++ b/plugins/languages/rust/src/functions.rs @@ -227,6 +227,8 @@ impl FunctionCollector<'_> { end_line, decision_points, source_lines, + name: None, + cognitive_complexity: 0, }); } } diff --git a/plugins/languages/rust/src/lib.rs b/plugins/languages/rust/src/lib.rs index 790e5f9..10f2c5e 100644 --- a/plugins/languages/rust/src/lib.rs +++ b/plugins/languages/rust/src/lib.rs @@ -12,8 +12,8 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + SourceSet, WorkspaceError, }; use crate::cfg_test::excluded_cfg_test_lines; @@ -65,6 +65,14 @@ impl Guest for Rust { }) } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn manifest_paths(repository_paths: Vec) -> Vec { manifest_paths(&repository_paths) } diff --git a/plugins/languages/rust/src/resolution.rs b/plugins/languages/rust/src/resolution.rs index fd0d4d9..db655ab 100644 --- a/plugins/languages/rust/src/resolution.rs +++ b/plugins/languages/rust/src/resolution.rs @@ -47,14 +47,14 @@ impl RustResolver { if let Some(use_path) = request.specifier.strip_prefix(USE_PREFIX) { return self.resolve_use(&request.importer, use_path); } - Resolution::External + Resolution::External(String::new()) } fn resolve_mod(&self, importer: &str, mod_name: &str) -> Resolution { let base_dir = module_child_dir(importer); match self.find_module_file(&base_dir, &[mod_name]) { Some(target) if target != importer => Resolution::Resolved(target), - Some(_) => Resolution::External, + Some(_) => Resolution::External(String::new()), None => Resolution::Unresolved(format!( "no module file found for `mod {mod_name}` from {importer}" )), @@ -64,15 +64,15 @@ impl RustResolver { fn resolve_use(&self, importer: &str, use_path: &str) -> Resolution { let segments: Vec<&str> = use_path.split("::").filter(|s| !s.is_empty()).collect(); let Some(&first) = segments.first() else { - return Resolution::External; + return Resolution::External(String::new()); }; if STD_CRATES.contains(&first) { - return Resolution::External; + return Resolution::Builtin; } match first { "crate" => { let Some(src_dir) = self.crate_src_dir(importer) else { - return Resolution::External; + return Resolution::External(String::new()); }; self.resolve_longest_module(importer, &src_dir, &segments[1..]) } @@ -91,11 +91,11 @@ impl RustResolver { return self .resolve_dir_to_file(¤t) .filter(|target| target != importer) - .map_or(Resolution::External, Resolution::Resolved); + .map_or_else(|| Resolution::External(String::new()), Resolution::Resolved); } self.resolve_longest_module(importer, ¤t, &segments[idx..]) } - _ => Resolution::External, + _ => Resolution::External(String::new()), } } @@ -108,7 +108,7 @@ impl RustResolver { for len in (1..=segments.len()).rev() { if let Some(target) = self.find_module_file(base_dir, &segments[..len]) { return if target == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(target) }; @@ -119,7 +119,7 @@ impl RustResolver { { return Resolution::Resolved(root_file); } - Resolution::External + Resolution::External(String::new()) } fn find_module_file(&self, base_dir: &str, segments: &[&str]) -> Option { diff --git a/plugins/languages/rust/tests/conformance.rs b/plugins/languages/rust/tests/conformance.rs index f78540f..5483038 100644 --- a/plugins/languages/rust/tests/conformance.rs +++ b/plugins/languages/rust/tests/conformance.rs @@ -73,12 +73,16 @@ fn counts_decision_points_and_nested_functions_separately() { end_line: 16, decision_points: 7, source_lines: 16, + name: None, + cognitive_complexity: 0, }, Function { line: 7, end_line: 9, decision_points: 2, source_lines: 3, + name: None, + cognitive_complexity: 0, }, ] ); @@ -251,8 +255,8 @@ fn resolves_intra_crate_mod_and_use_imports_and_marks_external_crates() { Resolution::Resolved("src/beta/mod.rs".to_owned()), Resolution::Resolved("src/beta/child.rs".to_owned()), Resolution::Resolved("src/alpha.rs".to_owned()), - Resolution::External, - Resolution::External, + Resolution::Builtin, + Resolution::External(String::new()), ] ); } diff --git a/plugins/languages/ts/src/functions.rs b/plugins/languages/ts/src/functions.rs index 0291722..3d02b5b 100644 --- a/plugins/languages/ts/src/functions.rs +++ b/plugins/languages/ts/src/functions.rs @@ -117,6 +117,8 @@ impl FunctionCollector<'_> { self.code_lines .count_between(first_line_index, last_line_index), ), + name: None, + cognitive_complexity: 0, }); } diff --git a/plugins/languages/ts/src/lib.rs b/plugins/languages/ts/src/lib.rs index 81da2d3..c40cc53 100644 --- a/plugins/languages/ts/src/lib.rs +++ b/plugins/languages/ts/src/lib.rs @@ -13,7 +13,7 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; use oxc_allocator::Allocator; @@ -74,6 +74,14 @@ impl Guest for TypeScriptAndJavaScript { .collect() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { [ ("erosion", 0.352, 0.600), diff --git a/plugins/languages/ts/src/resolution.rs b/plugins/languages/ts/src/resolution.rs index 0ae812d..50cea26 100644 --- a/plugins/languages/ts/src/resolution.rs +++ b/plugins/languages/ts/src/resolution.rs @@ -1,5 +1,7 @@ mod packages; mod snapshot; +#[cfg(test)] +mod tests; use std::collections::HashSet; @@ -76,26 +78,35 @@ impl ProjectResolver { pub(crate) fn resolve(&self, request: &ImportRequest) -> Resolution { let specifier = request.specifier.as_str(); - if specifier.starts_with('/') { - return Resolution::Unresolved(format!( - "{specifier:?} is an absolute path, which depends on the machine" - )); - } - if is_relative(specifier) && leaves_the_repository(&request.importer, specifier) { - return Resolution::Unresolved(format!("{specifier:?} leads outside the repository")); - } - if is_bun_builtin(specifier) { - return Resolution::External; + if let Some(early) = precheck_specifier(&request.importer, specifier) { + return early; } let importer = snapshot::absolute(&request.importer); - let resolved = match self.resolver.resolve_file(&importer, specifier) { + let resolved = self.resolve_with_fallback(&importer, specifier); + self.classify_resolution(&importer, specifier, resolved) + } + + fn resolve_with_fallback( + &self, + importer: &std::path::Path, + specifier: &str, + ) -> Result { + match self.resolver.resolve_file(importer, specifier) { Err(error) if is_project_configuration_error(&error) => { importer.parent().map_or(Err(error), |folder| { self.resolver.resolve(folder, specifier) }) } result => result, - }; + } + } + + fn classify_resolution( + &self, + importer: &std::path::Path, + specifier: &str, + resolved: Result, + ) -> Resolution { match resolved { Ok(resolution) => snapshot::repository_path(resolution.path()).map_or_else( || { @@ -106,8 +117,10 @@ impl ProjectResolver { }, Resolution::Resolved, ), - Err(ResolveError::Builtin { .. }) => Resolution::External, - Err(_) if self.names_an_outside_module(&importer, specifier) => Resolution::External, + Err(ResolveError::Builtin { .. }) => Resolution::Builtin, + Err(_) if self.names_an_outside_module(importer, specifier) => { + Resolution::External(package_name(specifier).to_owned()) + } Err(ResolveError::NotFound(_)) => { Resolution::Unresolved(format!("no file of the repository matches {specifier:?}")) } @@ -119,7 +132,8 @@ impl ProjectResolver { if is_relative(specifier) || specifier.starts_with('#') { return false; } - if self.package_names.contains(package_name(specifier)) { + let name = package_name(specifier); + if name.is_empty() || self.package_names.contains(name) { return false; } let matches_path_alias = self @@ -133,6 +147,25 @@ impl ProjectResolver { } } +fn precheck_specifier(importer: &str, specifier: &str) -> Option { + if specifier.is_empty() { + return Some(Resolution::Unresolved( + "import specifier is empty".to_owned(), + )); + } + if specifier.starts_with('/') { + return Some(Resolution::Unresolved(format!( + "{specifier:?} is an absolute path, which depends on the machine" + ))); + } + if is_relative(specifier) && leaves_the_repository(importer, specifier) { + return Some(Resolution::Unresolved(format!( + "{specifier:?} leads outside the repository" + ))); + } + is_bun_builtin(specifier).then_some(Resolution::Builtin) +} + fn is_project_configuration_error(error: &ResolveError) -> bool { matches!( error, @@ -165,12 +198,15 @@ fn leaves_the_repository(importer: &str, specifier: &str) -> bool { } fn package_name(specifier: &str) -> &str { - let segments = if specifier.starts_with('@') { 2 } else { 1 }; - let end = specifier + let clean = specifier + .split_once(['?', '#']) + .map_or(specifier, |(head, _)| head); + let segments = if clean.starts_with('@') { 2 } else { 1 }; + let end = clean .match_indices('/') .nth(segments - 1) - .map_or(specifier.len(), |(index, _)| index); - &specifier[..end] + .map_or(clean.len(), |(index, _)| index); + &clean[..end] } fn alias_matches(key: &str, specifier: &str) -> bool { diff --git a/plugins/languages/ts/src/resolution/tests.rs b/plugins/languages/ts/src/resolution/tests.rs new file mode 100644 index 0000000..269a451 --- /dev/null +++ b/plugins/languages/ts/src/resolution/tests.rs @@ -0,0 +1,50 @@ +use codeint_model::language::{ImportRequest, Resolution}; + +use super::{ProjectResolver, package_name}; + +fn resolve_specifier(specifier: &str) -> Resolution { + let paths = vec!["src/main.ts".to_owned()]; + let resolver = ProjectResolver::new(&paths, Vec::new()); + resolver.resolve(&ImportRequest { + importer: "src/main.ts".to_owned(), + specifier: specifier.to_owned(), + }) +} + +#[test] +fn package_name_strips_query_and_fragment_suffixes() { + assert_eq!(package_name("lodash?raw"), "lodash"); + assert_eq!(package_name("@scope/pkg?v=1"), "@scope/pkg"); + assert_eq!(package_name("@scope/pkg/sub?v=1#top"), "@scope/pkg"); + assert_eq!(package_name("react#hash"), "react"); + assert_eq!(package_name("?raw"), ""); + assert_eq!(package_name(""), ""); +} + +#[test] +fn external_resolutions_strip_query_and_fragment_suffixes() { + assert_eq!( + resolve_specifier("lodash?raw"), + Resolution::External("lodash".to_owned()) + ); + assert_eq!( + resolve_specifier("@scope/pkg?v=1"), + Resolution::External("@scope/pkg".to_owned()) + ); + assert_eq!( + resolve_specifier("react#hash"), + Resolution::External("react".to_owned()) + ); +} + +#[test] +fn empty_and_query_only_specifiers_are_unresolved() { + assert!( + matches!(resolve_specifier(""), Resolution::Unresolved(_)), + "empty specifier must be unresolved" + ); + assert!( + matches!(resolve_specifier("?raw"), Resolution::Unresolved(_)), + "query-only specifier must be unresolved" + ); +} diff --git a/plugins/languages/ts/tests/conformance.rs b/plugins/languages/ts/tests/conformance.rs index c73c598..181d0fe 100644 --- a/plugins/languages/ts/tests/conformance.rs +++ b/plugins/languages/ts/tests/conformance.rs @@ -324,6 +324,8 @@ fn function(line: u32, end_line: u32, decision_points: u32, source_lines: u32) - end_line, decision_points, source_lines, + name: None, + cognitive_complexity: 0, } } @@ -1166,10 +1168,18 @@ fn a_relative_specifier_resolves_to_the_first_matching_file_in_typescript_order( #[test] fn a_bare_specifier_names_a_module_outside_the_repository() { - for specifier in ["react", "@scope/package/sub", "node:path", "fs"] { + for (specifier, expected) in [ + ("react", Resolution::External("react".to_owned())), + ( + "@scope/package/sub", + Resolution::External("@scope/package".to_owned()), + ), + ("node:path", Resolution::Builtin), + ("fs", Resolution::Builtin), + ] { assert_eq!( resolve(&["src/main.ts"], "src/main.ts", specifier), - Resolution::External, + expected, "{specifier}" ); } @@ -1216,7 +1226,7 @@ fn resolutions_come_back_one_per_request_in_request_order() { resolutions, [ resolved("b.ts"), - Resolution::External, + Resolution::External("react".to_owned()), resolved("a.ts"), Resolution::Unresolved("no file of the repository matches \"./c\"".to_owned()), ] @@ -1314,10 +1324,17 @@ fn a_path_alias_without_a_matching_file_is_unresolved_and_other_bare_specifiers_ matches!(&missing, Resolution::Unresolved(reason) if reason.contains("@/views/missing")), "{missing:?}" ); - for specifier in ["react", "@scope/package", "node:fs"] { + for (specifier, expected) in [ + ("react", Resolution::External("react".to_owned())), + ( + "@scope/package", + Resolution::External("@scope/package".to_owned()), + ), + ("node:fs", Resolution::Builtin), + ] { assert_eq!( resolve_in_project(&ALIASED_PROJECT, "src/main.ts", specifier), - Resolution::External, + expected, "{specifier}" ); } @@ -1336,7 +1353,7 @@ fn a_tsconfig_that_does_not_include_the_importer_does_not_alias_its_imports() { assert_eq!( resolve_in_project(&files, "scripts/build.ts", "@/util"), - Resolution::External + Resolution::External("@/util".to_owned()) ); } @@ -1357,7 +1374,7 @@ fn imports_still_resolve_when_a_tsconfig_extends_a_config_outside_the_repository ); assert_eq!( resolve_in_project(&files, "src/main.ts", "react"), - Resolution::External + Resolution::External("react".to_owned()) ); } @@ -1428,7 +1445,7 @@ fn a_named_package_outside_the_declared_workspaces_is_not_linked() { for specifier in ["scripts", "retired"] { assert_eq!( resolve_in_project(&files, "packages/app/src/main.ts", specifier), - Resolution::External, + Resolution::External(specifier.to_owned()), "{specifier}" ); } @@ -1448,7 +1465,7 @@ fn a_named_package_in_a_repository_without_workspaces_is_not_linked() { assert_eq!( resolve_in_project(&files, "src/main.ts", "demo"), - Resolution::External + Resolution::External("demo".to_owned()) ); } @@ -1911,7 +1928,7 @@ fn bun_builtins_resolve_as_external_even_with_catch_all_tsconfig_paths() { ("src/db.ts", "bun:test"), ], ); - assert_eq!(resolutions, vec![Resolution::External; 3]); + assert_eq!(resolutions, vec![Resolution::Builtin; 3]); } #[test] diff --git a/wit/language.wit b/wit/language.wit index 0fc146c..2ba8096 100644 --- a/wit/language.wit +++ b/wit/language.wit @@ -1,6 +1,6 @@ /// The Plugin interface of codeint. /// A change that breaks a Plugin built against this version needs a new version. -package codeint:plugin@0.1.0; +package codeint:plugin@0.2.0; /// The interface a Language plugin exports: the file extensions it reads, and the Code model of each such file. interface language { @@ -15,6 +15,10 @@ interface language { decision-points: u32, /// The source lines of the function, not counting lines of nested functions. source-lines: u32, + /// The optional name of the function or method; `none` for anonymous lambdas and closures. + name: option, + /// The nesting-weighted cognitive complexity of the function, not counting nested functions. + cognitive-complexity: u32, } /// What a token is to clone detection, by the rules of the Language plugin. @@ -94,12 +98,34 @@ interface language { variant resolution { /// The import names this file of the repository, relative to the root, with forward slashes. resolved(string), - /// The import names a module outside the repository, such as a package or a built-in module. - external, + /// The import names a third-party package outside the repository; the payload is the canonical package name. + external(string), + /// The import names a standard-library or runtime built-in module. + builtin, /// The import should name a file of the repository, but none matches; the payload says why. unresolved(string), } + /// How a package manifest declares an external dependency. + enum dep-kind { + /// A dependency required at runtime in production. + runtime, + /// A dependency used only during development or testing. + dev, + /// An optional or peer dependency. + optional, + } + + /// One external dependency declared in a package manifest. + record declared-dep { + /// The package root folder relative to the repository root, with forward slashes, or empty for the repository root. + package-root: string, + /// The normalized package name as declared by the manifest. + name: string, + /// Whether the dependency is declared as runtime, dev, or optional. + kind: dep-kind, + } + /// Why a Language plugin cannot lower a file. variant lower-error { /// The file does not parse; the payload is the parser's message. @@ -136,7 +162,7 @@ interface language { /// `text` is the whole file. lower: func(path: string, text: string) -> result; - /// Chooses the files of one repository snapshot that the host reads once and passes to `workspace-packages` and `resolve-imports`, because a Plugin cannot read files. + /// Chooses the files of one repository snapshot that the host reads once and passes to `workspace-packages`, `resolve-imports`, `declared-dependencies`, and `entry-points`, because a Plugin cannot read files. /// `repository-paths` lists every file of the snapshot, relative to the root, with forward slashes. /// The result names only paths from `repository-paths`, such as each `package.json` and `tsconfig.json` file. manifest-paths: func(repository-paths: list) -> list; @@ -152,6 +178,17 @@ interface language { /// `manifests` holds each file that `manifest-paths` chose, with its text. /// The result holds one resolution per request, in request order. resolve-imports: func(repository-paths: list, manifests: list, requests: list) -> list; + + /// Extracts external dependencies declared in the selected manifests. + /// `manifests` holds each file that `manifest-paths` chose, with its text. + declared-dependencies: func(manifests: list) -> list; + + /// Discovers standard entry-point source files from the repository paths and selected manifests. + /// `repository-paths` lists every file of the snapshot, relative to the root, with forward slashes. + /// `manifests` holds each file that `manifest-paths` chose, with its text. + /// Every returned path must come from `repository-paths`. + entry-points: func(repository-paths: list, manifests: list) -> list; + /// The published typical value of one Metric for codebases in the language of the Language plugin. record reference-range { /// The Metric, by its key in the report: `erosion`, `verbosity`, `duplication`, or `import_cycles`. diff --git a/wit/metric.wit b/wit/metric.wit index 371ac14..f000874 100644 --- a/wit/metric.wit +++ b/wit/metric.wit @@ -1,4 +1,4 @@ -package codeint:plugin@0.1.0; +package codeint:plugin@0.2.0; /// The interface a Metric plugin exports: metadata for one Metric and a function that measures a Code model. interface metric {