1use crate::fmt::cst::{Model, NodeId, NodeKind, PathSeg, key_string};
4use crate::fmt::{FormatError, guard, prepare};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
8#[non_exhaustive]
9pub struct RangeEdit {
10 pub start: usize,
12 pub end: usize,
14 pub replacement: String,
16}
17
18pub fn format_yaml_range(
23 source: &str,
24 start: usize,
25 end: usize,
26) -> Result<Option<RangeEdit>, FormatError> {
27 if start > end
28 || end > source.len()
29 || !source.is_char_boundary(start)
30 || !source.is_char_boundary(end)
31 {
32 return Err(FormatError::Range(
33 "the range is outside the document or splits a character".to_string(),
34 ));
35 }
36
37 let prepared = prepare(source)?;
38 let bom = if prepared.had_bom {
39 '\u{FEFF}'.len_utf8()
40 } else {
41 0
42 };
43 let stripped = source.strip_prefix('\u{FEFF}').unwrap_or(source);
44 let start = start.saturating_sub(bom);
45 let end = end.saturating_sub(bom);
46 let (start, end) = trim_range(stripped, start, end);
47
48 let document = select_document(&prepared.model, start, end)?;
49 let mut maps = Vec::new();
50 collect_maps(
51 &prepared.model,
52 stripped,
53 prepared.model.docs[document].root,
54 &[],
55 0,
56 &mut maps,
57 );
58
59 let region = maps
60 .into_iter()
61 .filter(|region| region.start <= start && end <= region.end)
62 .max_by_key(|region| (region.depth, region.start))
63 .ok_or_else(|| FormatError::Range("the range is not inside a mapping".to_string()))?;
64
65 let span = prepared
66 .rendered
67 .spans
68 .get(&(document, region.path.clone()))
69 .ok_or_else(|| FormatError::Range("the range is not inside a mapping".to_string()))?;
70
71 let replacement = build_replacement(&prepared.rendered.text, span, region.child_col);
72 if replacement == stripped[region.start..region.end] {
73 return Ok(None);
74 }
75
76 splice_checked(
77 &prepared.before(),
78 stripped,
79 region.start,
80 region.end,
81 &replacement,
82 )?;
83
84 Ok(Some(RangeEdit {
85 start: region.start + bom,
86 end: region.end + bom,
87 replacement,
88 }))
89}
90
91fn splice_checked(
94 before: &guard::Before<'_>,
95 source: &str,
96 start: usize,
97 end: usize,
98 replacement: &str,
99) -> Result<(), FormatError> {
100 let mut spliced = String::with_capacity(source.len() + replacement.len());
101 spliced.push_str(&source[..start]);
102 spliced.push_str(replacement);
103 spliced.push_str(&source[end..]);
104 guard::check(before, &spliced)
105}
106
107struct MapRegion {
109 path: Vec<PathSeg>,
110 start: usize,
111 end: usize,
112 child_col: usize,
113 depth: usize,
114}
115
116fn trim_range(source: &str, mut start: usize, mut end: usize) -> (usize, usize) {
117 let bytes = source.as_bytes();
118 while start < end && bytes[start].is_ascii_whitespace() {
119 start += 1;
120 }
121 while end > start && bytes[end - 1].is_ascii_whitespace() {
122 end -= 1;
123 }
124 (start, end)
125}
126
127fn select_document(model: &Model, start: usize, end: usize) -> Result<usize, FormatError> {
130 let mut candidates = Vec::new();
131 for (index, doc) in model.docs.iter().enumerate() {
132 if doc.span.start <= end && start <= doc.span.end {
133 candidates.push(index);
134 }
135 }
136 match candidates.as_slice() {
137 [index] => Ok(*index),
138 [] => Err(FormatError::Range(
139 "the range is not inside a mapping".to_string(),
140 )),
141 _ => Err(FormatError::Range(
142 "the range spans more than one document".to_string(),
143 )),
144 }
145}
146
147fn collect_maps(
148 model: &Model,
149 source: &str,
150 node: NodeId,
151 path: &[PathSeg],
152 depth: usize,
153 out: &mut Vec<MapRegion>,
154) {
155 match &model.nodes[node as usize].kind {
156 NodeKind::Map { entries, flow, .. } => {
157 if !flow && !entries.is_empty() {
158 let first = entries
159 .iter()
160 .min_by_key(|entry| entry.source_index)
161 .expect("non-empty mapping");
162 let key = &model.nodes[first.key as usize];
163 let mut start = key.span.start;
164 if let Some(comment) = first.leading.first() {
165 start = start.min(comment.byte);
166 }
167 let mut content_end = structural_end(model, node);
168 for comment in &first.leading {
169 content_end = content_end.max(comment.byte + comment.text.len());
170 }
171 content_end = content_end.max(comment_end(model, node));
172 out.push(MapRegion {
173 path: path.to_vec(),
174 start,
175 end: line_end(source, content_end),
176 child_col: key.start.column,
177 depth,
178 });
179 }
180 for entry in entries {
181 let mut child_path = path.to_vec();
182 child_path.push(PathSeg::Key(key_string(model, entry.key)));
183 collect_maps(model, source, entry.value, &child_path, depth + 1, out);
184 }
185 }
186 NodeKind::Seq { items, .. } => {
187 for (index, item) in items.iter().enumerate() {
188 let mut child_path = path.to_vec();
189 child_path.push(PathSeg::Index(index));
190 collect_maps(model, source, item.value, &child_path, depth + 1, out);
191 }
192 }
193 _ => {}
194 }
195}
196
197fn structural_end(model: &Model, node: NodeId) -> usize {
200 match &model.nodes[node as usize].kind {
201 NodeKind::Map { entries, .. } => entries
202 .iter()
203 .map(|entry| {
204 structural_end(model, entry.value).max(model.nodes[entry.key as usize].span.end)
205 })
206 .max()
207 .unwrap_or(model.nodes[node as usize].span.start),
208 NodeKind::Seq { items, .. } => items
209 .iter()
210 .map(|item| structural_end(model, item.value))
211 .max()
212 .unwrap_or(model.nodes[node as usize].span.start),
213 _ => model.nodes[node as usize].span.end,
214 }
215}
216
217fn comment_end(model: &Model, node: NodeId) -> usize {
219 match &model.nodes[node as usize].kind {
220 NodeKind::Map {
221 entries, dangling, ..
222 } => {
223 let mut end = dangling
224 .iter()
225 .map(|comment| comment.byte + comment.text.len())
226 .max()
227 .unwrap_or(0);
228 for entry in entries {
229 for comment in &entry.leading {
230 end = end.max(comment.byte + comment.text.len());
231 }
232 if let Some(comment) = &entry.trailing {
233 end = end.max(comment.byte + comment.text.len());
234 }
235 for comment in &entry.extra_trailing {
236 end = end.max(comment.byte + comment.text.len());
237 }
238 end = end.max(comment_end(model, entry.value));
239 }
240 end
241 }
242 NodeKind::Seq {
243 items, dangling, ..
244 } => {
245 let mut end = dangling
246 .iter()
247 .map(|comment| comment.byte + comment.text.len())
248 .max()
249 .unwrap_or(0);
250 for item in items {
251 for comment in &item.leading {
252 end = end.max(comment.byte + comment.text.len());
253 }
254 if let Some(comment) = &item.trailing {
255 end = end.max(comment.byte + comment.text.len());
256 }
257 for comment in &item.extra_trailing {
258 end = end.max(comment.byte + comment.text.len());
259 }
260 end = end.max(comment_end(model, item.value));
261 }
262 end
263 }
264 _ => 0,
265 }
266}
267
268fn line_end(source: &str, position: usize) -> usize {
269 match source[position..].find('\n') {
270 Some(offset) => position + offset,
271 None => source.len(),
272 }
273}
274
275fn build_replacement(
279 rendered: &str,
280 span: &crate::fmt::render::SpanInfo,
281 source_col: usize,
282) -> String {
283 let region = &rendered[span.start..span.end];
284 let region = region.strip_suffix('\n').unwrap_or(region);
285 let (first, rest) = match region.split_once('\n') {
286 Some((first, rest)) => (first, rest),
287 None => (region, ""),
288 };
289 let first = &first[span.child_col.min(first.len())..];
290 let delta = source_col as isize - span.child_col as isize;
291
292 let mut replacement = String::from(first);
293 for line in rest.split('\n') {
294 replacement.push('\n');
295 if line.is_empty() {
296 continue;
297 }
298 if delta > 0 {
299 for _ in 0..delta {
300 replacement.push(' ');
301 }
302 replacement.push_str(line);
303 } else if delta < 0 {
304 let mut line = line;
305 let mut remove = (-delta) as usize;
306 while remove > 0 && line.starts_with(' ') {
307 line = &line[1..];
308 remove -= 1;
309 }
310 replacement.push_str(line);
311 } else {
312 replacement.push_str(line);
313 }
314 }
315 replacement
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 fn apply(source: &str, start: usize, end: usize) -> Result<Option<String>, FormatError> {
323 match format_yaml_range(source, start, end)? {
324 Some(edit) => {
325 let mut out = String::new();
326 out.push_str(&source[..edit.start]);
327 out.push_str(&edit.replacement);
328 out.push_str(&source[edit.end..]);
329 Ok(Some(out))
330 }
331 None => Ok(None),
332 }
333 }
334
335 fn range_of(source: &str, needle: &str) -> (usize, usize) {
336 let start = source.find(needle).expect("needle");
337 (start, start + needle.len())
338 }
339
340 const RULE: &str = "logsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
341
342 #[test]
343 fn a_selection_value_selects_the_selection_mapping() {
344 let source = "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: [one, two]\n condition: selection\n";
345 let (start, end) = range_of(source, "one");
346 let output = apply(source, start, end).unwrap().expect("edit");
347 assert_eq!(
348 output,
349 "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field:\n - one\n - two\n condition: selection\n"
350 );
351 }
352
353 #[test]
354 fn a_range_across_two_selections_selects_the_detection_mapping() {
355 let source = "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
356 let start = source.find("selection:").unwrap();
357 let end = source.find("condition: selection").unwrap() + "condition: selection".len();
358 let output = apply(source, start, end).unwrap().expect("edit");
359 assert_eq!(
360 output,
361 "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n"
362 );
363 }
364
365 #[test]
366 fn a_flow_list_selects_the_enclosing_root_mapping() {
367 let source = "title: Test\ntags: [attack.execution, attack.discovery]\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
368 let (start, end) = range_of(source, "attack.execution");
369 let output = apply(source, start, end).unwrap().expect("edit");
370 assert_eq!(
371 output,
372 "title: Test\ntags:\n - attack.execution\n - attack.discovery\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n"
373 );
374 }
375
376 #[test]
377 fn a_cursor_on_a_comment_line_selects_its_mapping() {
378 let source = "title: Test\ncustom:\n nested:\n # note\n Deep: [one, two]\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
379 let start = source.find("# note").unwrap();
380 let output = apply(source, start, start).unwrap().expect("edit");
381 assert_eq!(
382 output,
383 "title: Test\ncustom:\n nested:\n # note\n Deep:\n - one\n - two\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n"
384 );
385 }
386
387 #[test]
388 fn a_cursor_on_the_root_mapping_formats_the_whole_file() {
389 let source = "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
390 let start = source.find("title").unwrap();
391 let output = apply(source, start, start).unwrap().expect("edit");
392 assert_eq!(
393 output,
394 "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n"
395 );
396 }
397
398 #[test]
399 fn a_range_across_documents_is_refused() {
400 let source = format!("title: First\n{RULE}---\ntitle: Second\n{RULE}");
401 let start = source.find("First").unwrap();
402 let end = source.find("Second").unwrap() + "Second".len();
403 let error = apply(&source, start, end).unwrap_err();
404 assert_eq!(
405 error,
406 FormatError::Range("the range spans more than one document".to_string())
407 );
408 }
409
410 #[test]
411 fn a_range_in_a_directive_is_refused() {
412 let source = format!("%YAML 1.2\n---\ntitle: Test\n{RULE}");
413 let error = apply(&source, 0, 0).unwrap_err();
414 assert_eq!(
415 error,
416 FormatError::Range("the range is not inside a mapping".to_string())
417 );
418 }
419
420 #[test]
421 fn an_invalid_range_is_refused() {
422 let source = format!("title: Test\n{RULE}");
423 assert_eq!(
424 format_yaml_range(&source, 5, 2).unwrap_err(),
425 FormatError::Range(
426 "the range is outside the document or splits a character".to_string()
427 )
428 );
429 assert_eq!(
430 format_yaml_range(&source, 0, source.len() + 1).unwrap_err(),
431 FormatError::Range(
432 "the range is outside the document or splits a character".to_string()
433 )
434 );
435 let unicode = "title: Tést\n";
436 let split = unicode.find('é').unwrap() + 1;
437 assert_eq!(
438 format_yaml_range(unicode, split, split).unwrap_err(),
439 FormatError::Range(
440 "the range is outside the document or splits a character".to_string()
441 )
442 );
443 }
444
445 #[test]
446 fn a_bom_shifts_the_returned_offsets() {
447 let body = "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
448 let source = format!("\u{FEFF}{body}");
449 let start = source.find("title").unwrap();
450 let edit = format_yaml_range(&source, start, start)
451 .unwrap()
452 .expect("edit");
453 assert_eq!(edit.start, start);
454 assert!(source[edit.start..].starts_with("title:"));
455 let mut spliced = String::new();
456 spliced.push_str(&source[..edit.start]);
457 spliced.push_str(&edit.replacement);
458 spliced.push_str(&source[edit.end..]);
459 assert_eq!(
460 spliced,
461 format!(
462 "\u{FEFF}title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n"
463 )
464 );
465 }
466
467 #[test]
468 fn the_splice_guard_refuses_a_replacement_that_changes_the_file() {
469 let source = "title: Test\nlogsource:\n # keep\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
470 let prepared = prepare(source).unwrap();
471 let before = prepared.before();
472 let start = source.find(" # keep").unwrap();
473 let end = source.find("detection:").unwrap();
474
475 splice_checked(&before, source, start, end, " # keep\n category: test\n").unwrap();
476
477 let dropped = splice_checked(&before, source, start, end, " category: test\n");
478 assert!(matches!(dropped, Err(FormatError::Guard(_))), "{dropped:?}");
479
480 let changed = splice_checked(&before, source, start, end, " # keep\n category: other\n");
481 assert!(matches!(changed, Err(FormatError::Guard(_))), "{changed:?}");
482 }
483
484 #[test]
485 fn a_canonical_range_returns_none() {
486 let source = "title: Test\nlogsource:\n category: test\ndetection:\n selection:\n Field: value\n condition: selection\n";
487 let (start, end) = range_of(source, "selection:");
488 assert_eq!(apply(source, start, end).unwrap(), None);
489 }
490}