use std::collections::HashSet;
use std::ops::Range;
pub mod diagnostics;
mod error;
mod replace;
use diagnostics::Diagnostic;
use diagnostics::DiagnosticSpan;
pub use error::Error;
#[derive(Debug, Clone, Copy)]
pub enum Filter {
MachineApplicableOnly,
Everything,
}
pub fn get_suggestions_from_json<S: ::std::hash::BuildHasher>(
input: &str,
only: &HashSet<String, S>,
filter: Filter,
) -> serde_json::error::Result<Vec<Suggestion>> {
let mut result = Vec::new();
for cargo_msg in serde_json::Deserializer::from_str(input).into_iter::<Diagnostic>() {
result.extend(collect_suggestions(&cargo_msg?, only, filter));
}
Ok(result)
}
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct LinePosition {
pub line: usize,
pub column: usize,
}
impl std::fmt::Display for LinePosition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.line, self.column)
}
}
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct LineRange {
pub start: LinePosition,
pub end: LinePosition,
}
impl std::fmt::Display for LineRange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}-{}", self.start, self.end)
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Suggestion {
pub message: String,
pub snippets: Vec<Snippet>,
pub solutions: Vec<Solution>,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Solution {
pub message: String,
pub replacements: Vec<Replacement>,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Snippet {
pub file_name: String,
pub line_range: LineRange,
pub range: Range<usize>,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Replacement {
pub snippet: Snippet,
pub replacement: String,
}
fn span_to_snippet(span: &DiagnosticSpan) -> Snippet {
Snippet {
file_name: span.file_name.clone(),
line_range: LineRange {
start: LinePosition {
line: span.line_start,
column: span.column_start,
},
end: LinePosition {
line: span.line_end,
column: span.column_end,
},
},
range: (span.byte_start as usize)..(span.byte_end as usize),
}
}
fn collect_span(span: &DiagnosticSpan) -> Option<Replacement> {
let snippet = span_to_snippet(span);
let replacement = span.suggested_replacement.clone()?;
Some(Replacement {
snippet,
replacement,
})
}
pub fn collect_suggestions<S: ::std::hash::BuildHasher>(
diagnostic: &Diagnostic,
only: &HashSet<String, S>,
filter: Filter,
) -> Option<Suggestion> {
if !only.is_empty() {
if let Some(ref code) = diagnostic.code {
if !only.contains(&code.code) {
return None;
}
} else {
return None;
}
}
let snippets = diagnostic.spans.iter().map(span_to_snippet).collect();
let solutions: Vec<_> = diagnostic
.children
.iter()
.filter_map(|child| {
let replacements: Vec<_> = child
.spans
.iter()
.filter(|span| {
use crate::diagnostics::Applicability::*;
use crate::Filter::*;
match (filter, &span.suggestion_applicability) {
(MachineApplicableOnly, Some(MachineApplicable)) => true,
(MachineApplicableOnly, _) => false,
(Everything, _) => true,
}
})
.filter_map(collect_span)
.collect();
if !replacements.is_empty() {
Some(Solution {
message: child.message.clone(),
replacements,
})
} else {
None
}
})
.collect();
if solutions.is_empty() {
None
} else {
Some(Suggestion {
message: diagnostic.message.clone(),
snippets,
solutions,
})
}
}
pub struct CodeFix {
data: replace::Data,
modified: bool,
}
impl CodeFix {
pub fn new(s: &str) -> CodeFix {
CodeFix {
data: replace::Data::new(s.as_bytes()),
modified: false,
}
}
pub fn apply(&mut self, suggestion: &Suggestion) -> Result<(), Error> {
for sol in &suggestion.solutions {
for r in &sol.replacements {
self.data
.replace_range(r.snippet.range.clone(), r.replacement.as_bytes())?;
self.modified = true;
}
}
Ok(())
}
pub fn finish(&self) -> Result<String, Error> {
Ok(String::from_utf8(self.data.to_vec())?)
}
pub fn modified(&self) -> bool {
self.modified
}
}
pub fn apply_suggestions(code: &str, suggestions: &[Suggestion]) -> Result<String, Error> {
let mut fix = CodeFix::new(code);
for suggestion in suggestions.iter().rev() {
fix.apply(suggestion)?;
}
fix.finish()
}