use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::NodeId;
#[derive(Debug, Clone, PartialEq)]
pub struct Suggestion<'a> {
pub candidate: &'a str,
pub score: f64,
}
pub trait Suggester: Send + Sync {
fn suggest<'a>(&self, query: &str, candidates: &'a [&str]) -> Vec<Suggestion<'a>>;
fn enrich_unknown(&self, query: &str, candidates: &[&str]) -> Option<String> {
let sugs = self.suggest(query, candidates);
if sugs.is_empty() {
return None;
}
let joined = sugs
.iter()
.take(3)
.map(|s| s.candidate)
.collect::<Vec<_>>()
.join(", ");
Some(format!("did you mean: {joined}"))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopSuggester;
impl Suggester for NoopSuggester {
fn suggest<'a>(&self, _query: &str, _candidates: &'a [&str]) -> Vec<Suggestion<'a>> {
Vec::new()
}
fn enrich_unknown(&self, _query: &str, _candidates: &[&str]) -> Option<String> {
None
}
}
pub type SuggesterHandle = Arc<dyn Suggester>;
pub fn noop_handle() -> SuggesterHandle {
Arc::new(NoopSuggester)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Applicability {
MachineApplicable,
MaybeIncorrect,
HasPlaceholders,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PatchPart {
pub node: NodeId,
pub path: Option<String>,
pub replacement: String,
}
impl PatchPart {
pub fn node(node: NodeId, replacement: impl Into<String>) -> Self {
Self {
node,
path: None,
replacement: replacement.into(),
}
}
pub fn field(node: NodeId, path: impl Into<String>, replacement: impl Into<String>) -> Self {
Self {
node,
path: Some(path.into()),
replacement: replacement.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FixSuggestion {
pub message: String,
pub patch: Vec<PatchPart>,
pub applicability: Applicability,
}
impl FixSuggestion {
pub fn new(message: impl Into<String>, part: PatchPart, applicability: Applicability) -> Self {
Self {
message: message.into(),
patch: vec![part],
applicability,
}
}
#[must_use]
pub fn with_part(mut self, part: PatchPart) -> Self {
self.patch.push(part);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn noop_returns_empty() {
let s = NoopSuggester;
assert!(s.suggest("foo", &["food", "for"]).is_empty());
assert_eq!(s.enrich_unknown("foo", &["food", "for"]), None);
}
#[test]
fn enrich_default_formats_top_three() {
struct FixedSuggester;
impl Suggester for FixedSuggester {
fn suggest<'a>(&self, _q: &str, cands: &'a [&str]) -> Vec<Suggestion<'a>> {
cands
.iter()
.enumerate()
.map(|(i, c)| Suggestion {
candidate: c,
score: 1.0 - (i as f64 * 0.1),
})
.collect()
}
}
let s = FixedSuggester;
let hint = s.enrich_unknown("q", &["a", "b", "c", "d", "e"]);
assert_eq!(hint.as_deref(), Some("did you mean: a, b, c"));
}
#[test]
fn noop_handle_is_shared() {
let h: SuggesterHandle = noop_handle();
assert!(h.suggest("x", &["y"]).is_empty());
}
#[test]
fn applicability_serde_round_trips() {
for level in [
Applicability::MachineApplicable,
Applicability::MaybeIncorrect,
Applicability::HasPlaceholders,
] {
let json = serde_json::to_string(&level).expect("serialize Applicability");
let back: Applicability =
serde_json::from_str(&json).expect("deserialize Applicability");
assert_eq!(level, back, "round-trip changed {level:?} via {json}");
}
assert_eq!(
serde_json::to_string(&Applicability::MachineApplicable).unwrap(),
"\"MachineApplicable\""
);
}
#[test]
fn fix_suggestion_builds_multipart() {
let s = FixSuggestion::new(
"replace `Alph` with `Alpha`",
PatchPart::node(NodeId(1), "Alpha"),
Applicability::MaybeIncorrect,
)
.with_part(PatchPart::field(NodeId(2), "label", "Beta"));
assert_eq!(s.patch.len(), 2);
assert_eq!(s.applicability, Applicability::MaybeIncorrect);
assert_eq!(s.patch[0].node, NodeId(1));
assert_eq!(s.patch[0].path, None);
assert_eq!(s.patch[1].path.as_deref(), Some("label"));
assert_eq!(s.patch[1].replacement, "Beta");
}
}