Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions crates/cli/src/check/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -89,7 +89,18 @@ macro_rules! every_import_is_external {
_manifests: Vec<Manifest>,
requests: Vec<ImportRequest>,
) -> Vec<Resolution> {
requests.iter().map(|_| Resolution::External).collect()
requests
.iter()
.map(|_| Resolution::External(String::new()))
.collect()
}

fn declared_dependencies(_manifests: Vec<Manifest>) -> Vec<DeclaredDep> {
Vec::new()
}

fn entry_points(_repository_paths: Vec<String>, _manifests: Vec<Manifest>) -> Vec<String> {
Vec::new()
}
};
}
Expand Down Expand Up @@ -766,7 +777,25 @@ impl LanguagePlugin for ParallelProofPlugin {
_manifests: Vec<Manifest>,
requests: Vec<ImportRequest>,
) -> Vec<Resolution> {
requests.iter().map(|_| Resolution::External).collect()
requests
.iter()
.map(|_| Resolution::External(String::new()))
.collect()
}

fn declared_dependencies(
&self,
_manifests: Vec<Manifest>,
) -> Result<Vec<DeclaredDep>, codeint_model::LanguagePluginError> {
Ok(Vec::new())
}

fn entry_points(
&self,
_repository_paths: &[RepoPath],
_manifests: Vec<Manifest>,
) -> Result<Vec<RepoPath>, codeint_model::LanguagePluginError> {
Ok(Vec::new())
}

fn reference_ranges(&self) -> Result<ReferenceRanges, InvalidReferenceRange> {
Expand Down
44 changes: 29 additions & 15 deletions crates/cli/src/remedy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,19 +302,44 @@ 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."
}
PluginHostError::HashMismatch { .. } | PluginHostError::DownloadHashMismatch { .. } => {
"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."
}
Expand All @@ -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.",
}
}

Expand Down
4 changes: 3 additions & 1 deletion crates/metrics/src/import_cycles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,9 @@ fn unresolved_imports(model: &CodeModel) -> Vec<UnresolvedImport> {
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));
Expand Down
4 changes: 2 additions & 2 deletions crates/metrics/src/import_cycles/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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"),
]);
Expand Down
23 changes: 18 additions & 5 deletions crates/model/HOW-TO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -60,7 +60,18 @@ impl Guest for Plain {
_manifests: Vec<Manifest>,
requests: Vec<ImportRequest>,
) -> Vec<Resolution> {
requests.iter().map(|_| Resolution::External).collect()
requests
.iter()
.map(|request| Resolution::External(request.specifier.clone()))
.collect()
}

fn declared_dependencies(_manifests: Vec<Manifest>) -> Vec<DeclaredDep> {
Vec::new()
}

fn entry_points(_repository_paths: Vec<String>, _manifests: Vec<Manifest>) -> Vec<String> {
Vec::new()
}

fn reference_ranges() -> Vec<ReferenceRange> {
Expand All @@ -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.
Expand Down Expand Up @@ -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

Expand Down
99 changes: 97 additions & 2 deletions crates/model/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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,
};
Expand Down Expand Up @@ -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<DeclaredDep>,
) -> Result<Vec<DeclaredDep>, 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<String>,
) -> Result<Vec<RepoPath>, 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<String>;

Expand All @@ -318,6 +384,17 @@ pub trait LanguagePlugin: Sync {
requests: Vec<language::ImportRequest>,
) -> Vec<language::Resolution>;

fn declared_dependencies(
&self,
manifests: Vec<Manifest>,
) -> Result<Vec<DeclaredDep>, LanguagePluginError>;

fn entry_points(
&self,
repository_paths: &[RepoPath],
manifests: Vec<Manifest>,
) -> Result<Vec<RepoPath>, LanguagePluginError>;

fn reference_ranges(&self) -> Result<ReferenceRanges, InvalidReferenceRange>;
}

Expand Down Expand Up @@ -353,6 +430,24 @@ impl<Plugin: language::Guest + Sync> LanguagePlugin for Plugin {
Plugin::resolve_imports(owned_paths(repository_paths), manifests, requests)
}

fn declared_dependencies(
&self,
manifests: Vec<Manifest>,
) -> Result<Vec<DeclaredDep>, LanguagePluginError> {
validate_declared_dependencies(Plugin::declared_dependencies(manifests))
}

fn entry_points(
&self,
repository_paths: &[RepoPath],
manifests: Vec<Manifest>,
) -> Result<Vec<RepoPath>, LanguagePluginError> {
validate_entry_points(
repository_paths,
Plugin::entry_points(owned_paths(repository_paths), manifests),
)
}

fn reference_ranges(&self) -> Result<ReferenceRanges, InvalidReferenceRange> {
ReferenceRanges::new(Plugin::reference_ranges())
}
Expand Down
6 changes: 4 additions & 2 deletions crates/model/src/runtime_imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ mod tests;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImportResolution {
Resolved(RepoPath),
External,
External(String),
Builtin,
Unresolved { reason: String },
}

Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading