1use crate::{FileChange, structural};
8use ast_grep_language::{LanguageExt, SupportLang};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use std::{collections::BTreeMap, path::PathBuf};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
15pub struct SyntaxPosition {
16 pub line: usize,
18 pub column: usize,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
24pub struct FileSyntax {
25 pub language: String,
27 pub before_errors: usize,
29 pub after_errors: usize,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
33 pub first_new_error: Option<SyntaxPosition>,
34}
35
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
38#[serde(rename_all = "snake_case")]
39pub enum PlanSyntax {
40 #[default]
42 Unknown,
43 Clean,
45 IntroducedErrors,
47 PreexistingErrors,
49}
50
51#[must_use]
53pub fn annotate(files: &[FileChange]) -> BTreeMap<PathBuf, FileSyntax> {
54 files
55 .iter()
56 .filter_map(|file| Some((file.path.clone(), file_syntax(file)?)))
57 .collect()
58}
59
60#[must_use]
62pub fn plan_syntax(facts: &BTreeMap<PathBuf, FileSyntax>) -> PlanSyntax {
63 if facts.is_empty() {
64 return PlanSyntax::Unknown;
65 }
66 if facts
67 .values()
68 .any(|fact| fact.after_errors > fact.before_errors)
69 {
70 return PlanSyntax::IntroducedErrors;
71 }
72 if facts.values().any(|fact| fact.before_errors > 0) {
73 return PlanSyntax::PreexistingErrors;
74 }
75 PlanSyntax::Clean
76}
77
78fn file_syntax(file: &FileChange) -> Option<FileSyntax> {
79 let language = structural::enabled_language(&file.path)?;
80 let before_errors = file
81 .before
82 .as_deref()
83 .map_or(0, |text| errors(language, text).0);
84 let after = file.after.as_deref().map(|text| errors(language, text));
85 let after_errors = after.as_ref().map_or(0, |(count, _)| *count);
86 let first_new_error = (after_errors > before_errors)
87 .then(|| after.and_then(|(_, pos)| pos))
88 .flatten();
89 Some(FileSyntax {
90 language: structural::language_name(language).to_string(),
91 before_errors,
92 after_errors,
93 first_new_error,
94 })
95}
96
97fn errors(language: SupportLang, text: &str) -> (usize, Option<SyntaxPosition>) {
100 let tree = language.ast_grep(text);
101 let mut count = 0;
102 let mut first = None;
103 for node in tree.root().dfs() {
104 if !(node.is_error() || node.is_missing()) {
105 continue;
106 }
107 count += 1;
108 if first.is_none() {
109 let pos = node.start_pos();
110 first = Some(SyntaxPosition {
111 line: pos.line() + 1,
112 column: pos.column(&node) + 1,
113 });
114 }
115 }
116 (count, first)
117}