use std::fmt;
use std::ops::Range;
pub struct Diagnostic {
message: String,
snippet: Option<(String, Range<usize>)>,
help: Option<String>,
notes: Vec<String>,
}
impl Diagnostic {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
snippet: None,
help: None,
notes: vec![],
}
}
pub fn at(mut self, source: &str, part: Range<usize>) -> Self {
self.snippet = Some((source.to_string(), part));
self
}
pub fn help(mut self, help: impl Into<String>) -> Self {
self.help = Some(help.into());
self
}
pub fn maybe_help(mut self, help: Option<String>) -> Self {
self.help = help.or(self.help);
self
}
pub fn note(mut self, note: impl Into<String>) -> Self {
self.notes.push(note.into());
self
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)?;
if let Some((source, part)) = &self.snippet {
let pad = source[..part.start].chars().count();
let width = source[part.clone()].chars().count().max(1);
write!(
f,
"\n --> {source}\n {}{}",
" ".repeat(pad),
"^".repeat(width)
)?;
}
let labelled = self
.help
.iter()
.map(|h| ("ayuda", h))
.chain(self.notes.iter().map(|n| ("nota", n)));
for (label, text) in labelled {
let indent = format!("\n{}", " ".repeat(label.len() + 6));
write!(f, "\n = {label}: {}", text.replace('\n', &indent))?;
}
Ok(())
}
}
impl From<Diagnostic> for String {
fn from(d: Diagnostic) -> Self {
d.to_string()
}
}
pub fn similar<'a>(typed: &str, candidates: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
candidates
.into_iter()
.map(|c| (strsim::normalized_damerau_levenshtein(typed, c), c))
.filter(|(score, _)| *score >= 0.6)
.max_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, c)| c)
}
pub fn did_you_mean<'a>(
typed: &str,
candidates: impl IntoIterator<Item = &'a str>,
) -> Option<String> {
similar(typed, candidates).map(|s| format!("¿querías decir `{s}`?"))
}
pub fn use_color() -> bool {
use std::io::IsTerminal;
std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
}
const RED: &str = "\x1b[1;31m";
const YELLOW: &str = "\x1b[1;33m";
const BLUE: &str = "\x1b[1;34m";
const BOLD: &str = "\x1b[1m";
const RESET: &str = "\x1b[0m";
pub fn paint(label: &str, text: &str, color: bool) -> String {
let text = format!("{label}: {text}");
if !color {
return text;
}
text.lines()
.map(|line| {
for (head, colour) in [("error: ", RED), ("aviso: ", YELLOW)] {
if let Some(rest) = line.strip_prefix(head) {
return format!("{colour}{}{RESET}{BOLD} {rest}{RESET}", head.trim_end());
}
}
if let Some(rest) = line.strip_prefix(" --> ") {
return format!(" {BLUE}-->{RESET} {rest}");
}
if line.trim_start().starts_with('^') && line.trim().chars().all(|c| c == '^') {
return format!("{RED}{line}{RESET}");
}
for head in ["ayuda:", "nota:"] {
if let Some(rest) = line.strip_prefix(&format!(" = {head}")) {
return format!(" {BLUE}={RESET} {BOLD}{head}{RESET}{rest}");
}
}
line.to_string()
})
.collect::<Vec<_>>()
.join("\n")
}