use std::collections::{BTreeMap, BTreeSet};
use crate::constraint::ConstraintRef;
pub const MAX_CONSTRAINT_WEIGHT_MULTIPLIER: u32 = 1_000_000;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(transparent)
)]
pub struct ConstraintWeights {
multipliers: BTreeMap<String, u32>,
}
impl ConstraintWeights {
pub fn new() -> Self {
Self::default()
}
pub fn set(&mut self, constraint: impl Into<String>, multiplier: u32) -> &mut Self {
self.multipliers.insert(constraint.into(), multiplier);
self
}
pub fn remove(&mut self, constraint: &str) -> Option<u32> {
self.multipliers.remove(constraint)
}
pub fn get(&self, constraint: &str) -> Option<u32> {
self.multipliers.get(constraint).copied()
}
pub fn multiplier_for(&self, constraint: &ConstraintRef) -> u32 {
if self.multipliers.is_empty() {
return 1;
}
self.get(&constraint.full_name()).unwrap_or(1)
}
pub fn is_empty(&self) -> bool {
self.multipliers.is_empty()
}
pub fn len(&self) -> usize {
self.multipliers.len()
}
pub fn iter(&self) -> impl Iterator<Item = (&str, u32)> {
self.multipliers
.iter()
.map(|(name, multiplier)| (name.as_str(), *multiplier))
}
pub fn validate<'a>(
&self,
known: impl IntoIterator<Item = &'a ConstraintRef>,
) -> Result<(), ConstraintWeightError> {
let known: BTreeSet<String> = known.into_iter().map(ConstraintRef::full_name).collect();
for (name, &multiplier) in &self.multipliers {
if !known.contains(name) {
return Err(ConstraintWeightError::UnknownConstraint {
name: name.clone(),
suggestions: close_matches(name, &known),
known: known.iter().cloned().collect(),
});
}
if multiplier > MAX_CONSTRAINT_WEIGHT_MULTIPLIER {
return Err(ConstraintWeightError::MultiplierTooLarge {
name: name.clone(),
multiplier,
max: MAX_CONSTRAINT_WEIGHT_MULTIPLIER,
});
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ConstraintWeightError {
#[error(
"constraint weight names unknown constraint \"{name}\"{}; known constraints: {}",
suggestion_text(suggestions),
known_text(known)
)]
UnknownConstraint {
name: String,
suggestions: Vec<String>,
known: Vec<String>,
},
#[error("constraint weight multiplier {multiplier} for \"{name}\" exceeds the maximum {max}")]
MultiplierTooLarge {
name: String,
multiplier: u32,
max: u32,
},
}
fn suggestion_text(suggestions: &[String]) -> String {
match suggestions {
[] => String::new(),
[only] => format!(" (did you mean \"{only}\"?)"),
many => format!(
" (did you mean one of {}?)",
many.iter()
.map(|name| format!("\"{name}\""))
.collect::<Vec<_>>()
.join(", ")
),
}
}
fn known_text(known: &[String]) -> String {
if known.is_empty() {
return "none".to_string();
}
known
.iter()
.map(|name| format!("\"{name}\""))
.collect::<Vec<_>>()
.join(", ")
}
fn close_matches(name: &str, known: &BTreeSet<String>) -> Vec<String> {
let lowered = name.to_lowercase();
let limit = (name.chars().count() / 3).max(1);
known
.iter()
.filter(|candidate| {
let candidate = candidate.to_lowercase();
candidate == lowered || edit_distance(&candidate, &lowered) <= limit
})
.cloned()
.collect()
}
fn edit_distance(left: &str, right: &str) -> usize {
let right: Vec<char> = right.chars().collect();
let mut previous: Vec<usize> = (0..=right.len()).collect();
let mut current = vec![0; right.len() + 1];
for (i, l) in left.chars().enumerate() {
current[0] = i + 1;
for (j, r) in right.iter().enumerate() {
let substitution = previous[j] + usize::from(l != *r);
current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
}
std::mem::swap(&mut previous, &mut current);
}
previous[right.len()]
}