use crate::{FileChange, structural};
use ast_grep_language::{LanguageExt, SupportLang};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SyntaxPosition {
pub line: usize,
pub column: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct FileSyntax {
pub language: String,
pub before_errors: usize,
pub after_errors: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub first_new_error: Option<SyntaxPosition>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PlanSyntax {
#[default]
Unknown,
Clean,
IntroducedErrors,
PreexistingErrors,
}
#[must_use]
pub fn annotate(files: &[FileChange]) -> BTreeMap<PathBuf, FileSyntax> {
files
.iter()
.filter_map(|file| Some((file.path.clone(), file_syntax(file)?)))
.collect()
}
#[must_use]
pub fn plan_syntax(facts: &BTreeMap<PathBuf, FileSyntax>) -> PlanSyntax {
if facts.is_empty() {
return PlanSyntax::Unknown;
}
if facts
.values()
.any(|fact| fact.after_errors > fact.before_errors)
{
return PlanSyntax::IntroducedErrors;
}
if facts.values().any(|fact| fact.before_errors > 0) {
return PlanSyntax::PreexistingErrors;
}
PlanSyntax::Clean
}
fn file_syntax(file: &FileChange) -> Option<FileSyntax> {
let language = structural::enabled_language(&file.path)?;
let before_errors = file
.before
.as_deref()
.map_or(0, |text| errors(language, text).0);
let after = file.after.as_deref().map(|text| errors(language, text));
let after_errors = after.as_ref().map_or(0, |(count, _)| *count);
let first_new_error = (after_errors > before_errors)
.then(|| after.and_then(|(_, pos)| pos))
.flatten();
Some(FileSyntax {
language: structural::language_name(language).to_string(),
before_errors,
after_errors,
first_new_error,
})
}
fn errors(language: SupportLang, text: &str) -> (usize, Option<SyntaxPosition>) {
let tree = language.ast_grep(text);
let mut count = 0;
let mut first = None;
for node in tree.root().dfs() {
if !(node.is_error() || node.is_missing()) {
continue;
}
count += 1;
if first.is_none() {
let pos = node.start_pos();
first = Some(SyntaxPosition {
line: pos.line() + 1,
column: pos.column(&node) + 1,
});
}
}
(count, first)
}