Skip to main content

rsigma_parser/fmt/
mod.rs

1//! Comment-preserving formatter for Sigma YAML.
2//!
3//! [`format_yaml`] rewrites a Sigma file into the canonical layout that
4//! [`emit_rule_yaml`](crate::emit_rule_yaml) produces, keeping comments,
5//! anchors, aliases, tags, and directives. Every result is checked against the
6//! source: the YAML values, the parsed Sigma rules, and the attachment of every
7//! comment must be unchanged, or the call fails with [`FormatError::Guard`].
8
9use serde::Deserialize;
10use tree_sitter::Tree;
11
12use crate::diagnostic::DiagnosticSeverity;
13use crate::fmt::context::DocKind;
14use crate::parser::parse_sigma_yaml;
15
16pub(crate) mod classify;
17pub(crate) mod comments;
18pub(crate) mod context;
19pub(crate) mod cst;
20pub(crate) mod guard;
21pub(crate) mod order;
22pub(crate) mod range;
23pub(crate) mod render;
24
25pub use range::{RangeEdit, format_yaml_range};
26
27/// The deepest collection nesting the formatter accepts.
28pub(crate) const MAX_DEPTH: usize = 64;
29
30/// The result of formatting a whole file.
31#[derive(Debug, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub struct FormatOutcome {
34    /// The canonical text. Always ends with exactly one `\n`.
35    pub formatted: String,
36    /// True when `formatted` differs from the source bytes.
37    pub changed: bool,
38}
39
40/// Why a file could not be formatted.
41#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
42#[non_exhaustive]
43pub enum FormatError {
44    /// The source is not valid YAML. `line` and `column` are 1-based.
45    #[error("YAML syntax error at line {line}, column {column}: {message}")]
46    Yaml {
47        line: usize,
48        column: usize,
49        message: String,
50    },
51    /// A document is not a Sigma document, so the whole file is left alone.
52    /// `document` is zero-based.
53    #[error("document {} is not a Sigma rule document: {reason}", .document + 1)]
54    NotSigma { document: usize, reason: String },
55    /// The file looks like Sigma but the parser reports an error.
56    #[error("invalid Sigma{}: {message}", .document.map(|d| format!(" in document {}", d + 1)).unwrap_or_default())]
57    InvalidSigma {
58        document: Option<usize>,
59        message: String,
60    },
61    /// Valid YAML that the formatter cannot lay out safely. `line` is 1-based.
62    #[error("unsupported YAML at line {line}: {construct}")]
63    Unsupported { line: usize, construct: String },
64    /// The formatted text would change the meaning of the file.
65    #[error("formatting would change the rule: {0}")]
66    Guard(String),
67    /// The requested range cannot be formatted on its own.
68    #[error("the range cannot be formatted: {0}")]
69    Range(String),
70}
71
72/// Format a whole Sigma YAML file.
73///
74/// The output uses the same canonical layout as
75/// [`emit_rule_yaml`](crate::emit_rule_yaml): four-space indentation, canonical
76/// key order, block collections, and canonical scalar quoting. Comments move
77/// with the entries they are attached to.
78///
79/// ```
80/// use rsigma_parser::format_yaml;
81///
82/// let source = "title: Test\n# note\nlogsource:\n  category: test\ndetection:\n  selection:\n    Field: value\n  condition: selection\n";
83/// let outcome = format_yaml(source).unwrap();
84/// assert!(outcome.formatted.contains("\n    category: test\n"));
85/// assert_eq!(
86///     outcome.formatted,
87///     "title: Test\n# note\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\n",
88/// );
89/// ```
90pub fn format_yaml(source: &str) -> Result<FormatOutcome, FormatError> {
91    let prepared = prepare(source)?;
92    let formatted = prepared.rendered.text.clone();
93    let changed = formatted != source;
94    if !changed {
95        return Ok(FormatOutcome {
96            formatted,
97            changed: false,
98        });
99    }
100    let before = prepared.before();
101    guard::check(&before, &formatted)?;
102    Ok(FormatOutcome {
103        formatted,
104        changed: true,
105    })
106}
107
108/// The source-derived state shared by whole-file and range formatting.
109pub(crate) struct Prepared {
110    pub model: cst::Model,
111    pub kinds: Vec<DocKind>,
112    pub collection: crate::SigmaCollection,
113    pub values: Vec<yaml_serde::Value>,
114    pub fingerprint: Vec<String>,
115    pub rendered: render::Render,
116    pub had_bom: bool,
117}
118
119impl Prepared {
120    pub(crate) fn before(&self) -> guard::Before<'_> {
121        guard::Before {
122            values: &self.values,
123            collection: &self.collection,
124            fingerprint: self.fingerprint.clone(),
125            kinds: &self.kinds,
126        }
127    }
128}
129
130/// Run the formatter pipeline up to (and including) rendering.
131pub(crate) fn prepare(source: &str) -> Result<Prepared, FormatError> {
132    let (stripped, had_bom) = match source.strip_prefix('\u{FEFF}') {
133        Some(rest) => (rest, true),
134        None => (source, false),
135    };
136    let tree = parse_tree(stripped)?;
137    if tree.root_node().has_error() {
138        let (line, column, message) = error_position(&tree);
139        return Err(FormatError::Yaml {
140            line,
141            column,
142            message,
143        });
144    }
145    let values = deserialize_values(stripped)?;
146    if values.is_empty() || document_count(&tree) == 0 {
147        return Err(FormatError::NotSigma {
148            document: 0,
149            reason: "the file contains no YAML documents".to_string(),
150        });
151    }
152    let kinds = classify::classify(&values)?;
153    let collection = parse_sigma_yaml(stripped).map_err(|error| FormatError::InvalidSigma {
154        document: None,
155        message: error.to_string(),
156    })?;
157    if let Some(diagnostic) = collection
158        .diagnostics
159        .iter()
160        .find(|diagnostic| diagnostic.severity == DiagnosticSeverity::Error)
161    {
162        return Err(FormatError::InvalidSigma {
163            document: diagnostic.document,
164            message: diagnostic.message.clone(),
165        });
166    }
167    let mut model = cst::build(stripped, &tree, &values)?;
168    comments::attach(&mut model, stripped)?;
169    let plan = order::plan(&model, &kinds);
170    let fingerprint = guard::fingerprint(&model, &kinds, &plan);
171    let rendered = render::render(&model, &kinds, &plan);
172    let cap = stripped.len().saturating_mul(16).saturating_add(4096);
173    if rendered.text.len() > cap {
174        return Err(FormatError::Unsupported {
175            line: 1,
176            construct: "formatted output would be more than 16 times the input size".to_string(),
177        });
178    }
179    Ok(Prepared {
180        model,
181        kinds,
182        collection,
183        values,
184        fingerprint,
185        rendered,
186        had_bom,
187    })
188}
189
190fn document_count(tree: &Tree) -> usize {
191    let root = tree.root_node();
192    root.children(&mut root.walk())
193        .filter(|child| child.kind() == "document")
194        .count()
195}
196
197pub(crate) fn parse_tree(source: &str) -> Result<Tree, FormatError> {
198    let mut parser = tree_sitter::Parser::new();
199    let language: tree_sitter::Language = tree_sitter_yaml::LANGUAGE.into();
200    parser
201        .set_language(&language)
202        .map_err(|_| FormatError::Yaml {
203            line: 1,
204            column: 1,
205            message: "could not load the YAML grammar".to_string(),
206        })?;
207    parser.parse(source, None).ok_or_else(|| FormatError::Yaml {
208        line: 1,
209        column: 1,
210        message: "syntax error".to_string(),
211    })
212}
213
214pub(crate) fn deserialize_values(source: &str) -> Result<Vec<yaml_serde::Value>, FormatError> {
215    let mut values = Vec::new();
216    for document in yaml_serde::Deserializer::from_str(source) {
217        match yaml_serde::Value::deserialize(document) {
218            Ok(value) => values.push(value),
219            Err(error) => {
220                let (line, column) = error
221                    .location()
222                    .map(|location| (location.line(), location.column()))
223                    .unwrap_or((1, 1));
224                return Err(FormatError::Yaml {
225                    line,
226                    column,
227                    message: error.to_string(),
228                });
229            }
230        }
231    }
232    Ok(values)
233}
234
235fn error_position(tree: &Tree) -> (usize, usize, String) {
236    if let Some((node, missing)) = first_error(tree.root_node()) {
237        let position = node.start_position();
238        let message = if missing {
239            format!("missing {}", node.kind())
240        } else {
241            "syntax error".to_string()
242        };
243        return (position.row + 1, position.column + 1, message);
244    }
245    (1, 1, "syntax error".to_string())
246}
247
248fn first_error(node: tree_sitter::Node<'_>) -> Option<(tree_sitter::Node<'_>, bool)> {
249    if node.is_error() {
250        return Some((node, false));
251    }
252    if node.is_missing() {
253        return Some((node, true));
254    }
255    let mut cursor = node.walk();
256    for child in node.children(&mut cursor) {
257        if let Some(found) = first_error(child) {
258            return Some(found);
259        }
260    }
261    None
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn reports_yaml_syntax_position() {
270        let error = format_yaml("title: [unclosed\n").unwrap_err();
271        assert!(matches!(error, FormatError::Yaml { line: 1, .. }));
272    }
273
274    #[test]
275    fn drops_bom() {
276        let source = "\u{FEFF}title: Test\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\n";
277        let outcome = format_yaml(source).unwrap();
278        assert!(outcome.changed);
279        assert!(outcome.formatted.starts_with("title: Test\n"));
280    }
281
282    #[test]
283    fn unchanged_canonical_input_is_not_changed() {
284        let source = "title: Test\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\n";
285        let outcome = format_yaml(source).unwrap();
286        assert!(!outcome.changed);
287        assert_eq!(outcome.formatted, source);
288    }
289}