Skip to main content

griz_core/
syntax.rs

1//! Parse facts: whether a planned file's before and after text parses
2//! cleanly, and where the first newly introduced error sits.
3//!
4//! Fact only. This never refuses a plan; it only reports what a parse of the
5//! planned text sees, for an enabled language.
6
7use crate::{FileChange, structural};
8use ast_grep_language::{LanguageExt, SupportLang};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use std::{collections::BTreeMap, path::PathBuf};
12
13/// 1-based line and column of a syntax error or missing node.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
15pub struct SyntaxPosition {
16    /// 1-based line.
17    pub line: usize,
18    /// 1-based column in characters.
19    pub column: usize,
20}
21
22/// Parse facts for one file's before and after text, in an enabled language.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
24pub struct FileSyntax {
25    /// Language the file was parsed as.
26    pub language: String,
27    /// Error and missing nodes found parsing the text before the plan.
28    pub before_errors: usize,
29    /// Error and missing nodes found parsing the text after the plan.
30    pub after_errors: usize,
31    /// Position of the first error node introduced by the plan, if any.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub first_new_error: Option<SyntaxPosition>,
34}
35
36/// A plan's overall syntax verdict, derived from every file's [`FileSyntax`].
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
38#[serde(rename_all = "snake_case")]
39pub enum PlanSyntax {
40    /// No changed file was in an enabled language.
41    #[default]
42    Unknown,
43    /// Every assessed file parses with no more errors than before.
44    Clean,
45    /// At least one file has more errors after the plan than before.
46    IntroducedErrors,
47    /// No file gained errors, but at least one already had some.
48    PreexistingErrors,
49}
50
51/// Parse facts for every changed file in an enabled language.
52#[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/// The plan-wide verdict over already-computed per-file facts.
61#[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
97/// Error and missing node count in `text`, and the first such node's
98/// 1-based position, when `language` parses it.
99fn 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}