1use 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
27pub(crate) const MAX_DEPTH: usize = 64;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub struct FormatOutcome {
34 pub formatted: String,
36 pub changed: bool,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
42#[non_exhaustive]
43pub enum FormatError {
44 #[error("YAML syntax error at line {line}, column {column}: {message}")]
46 Yaml {
47 line: usize,
48 column: usize,
49 message: String,
50 },
51 #[error("document {} is not a Sigma rule document: {reason}", .document + 1)]
54 NotSigma { document: usize, reason: String },
55 #[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 #[error("unsupported YAML at line {line}: {construct}")]
63 Unsupported { line: usize, construct: String },
64 #[error("formatting would change the rule: {0}")]
66 Guard(String),
67 #[error("the range cannot be formatted: {0}")]
69 Range(String),
70}
71
72pub 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
108pub(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
130pub(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}