Skip to main content

ailint_core/rules/structural/
malformed_yaml.rs

1//! AIL041 `malformed-yaml` — a `.yaml` / `.yml` file failed to parse.
2//!
3//! See: `docs/rules/structural/AIL041.md`
4
5use crate::file_type::FileType;
6use crate::parser::{DocumentContent, ParsedDocument};
7use crate::rules::structural::AIL041;
8use crate::rules::{Rule, RuleContext, RuleId, Severity, Violation};
9
10/// AIL041 malformed-yaml: YAML file or frontmatter fails to parse.
11#[derive(Debug, Default)]
12pub struct MalformedYamlRule;
13
14impl Rule for MalformedYamlRule {
15    fn id(&self) -> RuleId {
16        AIL041
17    }
18
19    fn default_severity(&self) -> Severity {
20        Severity::Error
21    }
22
23    /// Applies to any file we treat as YAML, guidance or generic.
24    fn applies_to(&self, file_type: FileType) -> bool {
25        matches!(
26            file_type,
27            FileType::GenericYaml
28                | FileType::GenericSystemPrompt
29                | FileType::CursorRules
30                | FileType::WindsurfRules
31                | FileType::ClineRules
32                | FileType::ContinueRules
33        )
34    }
35
36    fn run(&self, doc: &ParsedDocument, _ctx: &RuleContext<'_>) -> Vec<Violation> {
37        let msg = match &doc.content {
38            DocumentContent::ParseError(m) => m,
39            _ => return Vec::new(),
40        };
41        let (line, column) = extract_location(msg).unwrap_or((1, 1));
42        let mut v = Violation::new(
43            AIL041,
44            self.default_severity(),
45            doc.path.clone(),
46            format!("YAML/JSON parse error: {msg}"),
47        )
48        .at(line, column);
49        v.fix_hint = Some("fix the YAML/JSON syntax error at the reported location".to_string());
50        vec![v]
51    }
52}
53
54/// Best-effort extraction of `line: N column: M` from serde_yaml errors.
55fn extract_location(msg: &str) -> Option<(usize, usize)> {
56    let lower = msg.to_ascii_lowercase();
57    let line = extract_after(&lower, "line ").or_else(|| extract_after(&lower, "line: "))?;
58    let col = extract_after(&lower, "column ")
59        .or_else(|| extract_after(&lower, "column: "))
60        .unwrap_or(1);
61    Some((line, col))
62}
63
64fn extract_after(haystack: &str, needle: &str) -> Option<usize> {
65    let idx = haystack.find(needle)?;
66    let rest = &haystack[idx + needle.len()..];
67    let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
68    digits.parse().ok()
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn extracts_serde_yaml_style_location() {
77        assert_eq!(
78            extract_location("mapping values are not allowed in this context at line 3 column 5"),
79            Some((3, 5))
80        );
81    }
82
83    #[test]
84    fn falls_back_when_no_location() {
85        assert_eq!(extract_location("some other error"), None);
86    }
87}