1use crate::document::{Addressing, DocumentError, DocumentResult, Value};
6use noyalib::{
7 DuplicateKeyPolicy, Mapping as YamlMapping, ParserConfig, Value as YamlValue,
8 cst::{GreenChild, GreenNode, SyntaxKind, parse_document},
9 from_str_with_config, to_string,
10};
11
12pub fn load(content: &str) -> DocumentResult<Value> {
13 let (protected, literals) = protect_exact_numbers(content)?;
14 let parser_config = ParserConfig::new()
15 .duplicate_key_policy(DuplicateKeyPolicy::Error)
16 .lossless_u64_integers(true);
17 from_str_with_config::<YamlValue>(&protected, &parser_config)
18 .map(|value| value_to_our_value(value, &literals))
19 .map_err(|e| DocumentError::ParseError {
20 format: "YAML".to_string(),
21 detail: e.to_string(),
22 })
23}
24
25pub(crate) fn set_preserving(content: &str, path: &str, value: &Value) -> DocumentResult<String> {
35 let segments = crate::document::parse_path(path)?;
36 if is_blank_document(content) {
37 return set_in_blank_document(content, &segments, value);
38 }
39 if let Some((last, parents)) = segments.split_last()
40 && last == "-"
41 && array_at_path(&load(content)?, &crate::document::join_path(parents), "set").is_ok()
42 {
43 guard_cst_segments(content, parents, "set", false)?;
44 return append_array_item_preserving(content, &crate::document::join_path(parents), value)
45 .map_err(|error| match error {
46 DocumentError::UnsupportedOperation { format, detail, .. } => {
47 DocumentError::UnsupportedOperation {
48 format,
49 operation: "set".into(),
50 detail,
51 }
52 }
53 other => other,
54 });
55 }
56 let yaml_path = cst_path(&segments, "set")?;
57 guard_cst_segments(content, &segments, "set", true)?;
58 let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
59 format: "YAML".to_string(),
60 detail: error.to_string(),
61 })?;
62 refuse_shared_nodes(
65 &document,
66 content,
67 &segments,
68 segments.len() - 1,
69 "set",
70 true,
71 )?;
72 let mut expected = load(content)?;
75 let exists = crate::document::get_path_ref(&expected, path, Addressing::INDEX_ONLY).is_ok()
78 && segments.last().is_some_and(|last| {
79 last.parse::<usize>().is_ok() || document.key_span(&yaml_path).is_some()
80 });
81 let canonical = load(&save(value)?)?;
84 crate::document::set_path(&mut expected, path, &canonical, Addressing::INDEX_ONLY)?;
85 if exists && matches!(value, Value::Array(_) | Value::Object(_)) {
86 replace_collection_in_place(&mut document, content, &segments, &yaml_path, value)?;
87 } else if exists {
88 let result = if let Value::Number(text) = value {
89 document.set(&yaml_path, text)
90 } else if let Value::String(text) = value
91 && yaml_needs_legacy_quotes(text)
92 {
93 document.set(&yaml_path, "ed_yaml_string(text))
94 } else {
95 document.set_value(&yaml_path, &to_noyalib_value(value)?)
96 };
97 result.map_err(|error| edit_refused("set", &error))?;
98 } else {
99 let original = load(content)?;
101 for index in 0..segments.len().saturating_sub(1) {
102 let prefix = crate::document::join_path(&segments[..=index]);
103 if crate::document::get_path(&original, &prefix, Addressing::INDEX_ONLY).is_err() {
104 let parent = cst_path(&segments[..index], "set")?;
105 if document.span_at(&parent).is_some_and(|(start, end)| {
108 let text = content[start..end].trim();
109 let empty = text
110 .strip_circumfix('{', '}')
111 .is_some_and(|inner| inner.trim().is_empty());
112 text.starts_with('{') && !empty
113 }) {
114 return Err(DocumentError::UnsupportedOperation {
115 format: "YAML".into(),
116 operation: "set".into(),
117 detail: "creating parents inside a flow mapping is not supported".into(),
118 });
119 }
120 let mut nested = value.clone();
121 for key in segments[index + 1..].iter().rev() {
122 nested = Value::Object([(key.clone(), nested)].into_iter().collect());
123 }
124 return set_preserving(content, &prefix, &nested);
125 }
126 }
127 let (last, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
128 if last.parse::<usize>().is_ok() {
129 return Err(DocumentError::UnsupportedOperation {
130 format: "YAML".to_string(),
131 operation: "set".to_string(),
132 detail: "cannot create a new sequence index; the element must already exist"
133 .to_string(),
134 });
135 }
136 let parent_path = if parents.is_empty() {
137 String::new()
138 } else {
139 cst_path(parents, "set")?
140 };
141 let result = match value {
142 Value::Array(items) if items.is_empty() => {
146 document.insert_entry(&parent_path, last, "[]")
147 }
148 Value::Object(entries) if entries.is_empty() => {
149 document.insert_entry(&parent_path, last, "{}")
150 }
151 Value::Array(_) | Value::Object(_) => {
155 document.insert_entry_value(&parent_path, last, &to_noyalib_value(value)?)
156 }
157 _ => document.insert_entry(&parent_path, last, yaml_fragment(value, "set")?.trim_end()),
158 };
159 if result.is_err() {
160 let retry = if let Value::Number(text) = value {
165 document
166 .insert_entry_value(&parent_path, last, &YamlValue::Null)
167 .and_then(|()| document.set(&yaml_path, text))
168 } else {
169 document.insert_entry_value(&parent_path, last, &to_noyalib_value(value)?)
170 };
171 if let Err(error) = retry {
172 if !insert_beside_merge_key(&mut document, content, &parent_path, last, value)?
179 && !append_to_sequence_item_mapping(
180 &mut document,
181 content,
182 &parent_path,
183 last,
184 value,
185 )?
186 {
187 return Err(edit_refused("set", &error));
188 }
189 }
190 }
191 }
192 document
193 .validate()
194 .map_err(|error| DocumentError::ParseError {
195 format: "YAML".to_string(),
196 detail: error.to_string(),
197 })?;
198 let output = if exists {
199 document.to_string()
200 } else {
201 quote_inserted_scalars(&document, &yaml_path)
202 };
203 if load(&output)? != expected {
204 return Err(DocumentError::UnsupportedOperation {
205 format: "YAML".to_string(),
206 operation: "set".to_string(),
207 detail: "YAML edit did not preserve the requested document value".to_string(),
208 });
209 }
210 Ok(output)
211}
212
213pub(crate) fn is_blank_document(content: &str) -> bool {
217 let mut markers = 0;
218 content.lines().all(|line| {
219 let line = line.trim();
220 if line == "---" {
221 markers += 1;
222 return markers == 1;
223 }
224 line.is_empty() || line.starts_with('#')
225 })
226}
227
228fn set_in_blank_document(
230 content: &str,
231 segments: &[String],
232 value: &Value,
233) -> DocumentResult<String> {
234 if segments
235 .iter()
236 .any(|segment| segment == "-" || segment.parse::<usize>().is_ok())
237 {
238 return Err(DocumentError::UnsupportedOperation {
239 format: "YAML".to_string(),
240 operation: "set".to_string(),
241 detail: "an empty document has no sequence to index into".to_string(),
242 });
243 }
244 let mut nested = value.clone();
245 for segment in segments.iter().rev() {
246 nested = Value::Object([(segment.clone(), nested)].into_iter().collect());
247 }
248 let rendered = save(&nested)?;
249 let body = rendered.trim_prefix("---\n");
250 let newline = if content.contains("\r\n") {
251 "\r\n"
252 } else {
253 "\n"
254 };
255 let mut output = content.to_string();
256 if !output.is_empty() && !output.ends_with('\n') {
257 output.push_str(newline);
258 }
259 for line in body.trim_end_matches('\n').split('\n') {
260 output.push_str(line);
261 output.push_str(newline);
262 }
263 if load(&output)? != load(&save(&nested)?)? {
264 return Err(DocumentError::UnsupportedOperation {
265 format: "YAML".to_string(),
266 operation: "set".to_string(),
267 detail: "YAML edit did not preserve the requested document value".to_string(),
268 });
269 }
270 Ok(output)
271}
272
273fn replace_collection_in_place(
297 document: &mut noyalib::cst::Document,
298 content: &str,
299 segments: &[String],
300 yaml_path: &str,
301 value: &Value,
302) -> DocumentResult<()> {
303 let unsupported = |detail: String| DocumentError::UnsupportedOperation {
304 format: "YAML".to_string(),
305 operation: "set".to_string(),
306 detail,
307 };
308 let (value_start, value_end) = document
309 .span_at(yaml_path)
310 .ok_or_else(|| unsupported(format!("could not locate the value at `{yaml_path}`")))?;
311 let newline = if content.contains("\r\n") {
312 "\r\n"
313 } else {
314 "\n"
315 };
316 let Some((key_start, key_end)) = document.key_span(yaml_path) else {
317 let dash_column = preceding_sequence_dash_column(content, value_start).ok_or_else(|| {
320 unsupported(format!(
321 "a collection can replace only a block sequence element, and `{yaml_path}` is not one"
322 ))
323 })?;
324 let indent = dash_column + 2;
325 let fragment = block_fragment(value, document.indent_unit(), indent, newline)?;
326 let inline = fragment
327 .strip_prefix(newline)
328 .and_then(|rest| rest.strip_prefix(" ".repeat(indent).as_str()))
329 .unwrap_or_else(|| fragment.trim_start());
330 let end = end_of_trailing_inline_comment(content, value_end);
331 return document
332 .replace_span(value_start, end, inline)
333 .map_err(|error| edit_refused("set", &error));
334 };
335 if value_start < key_end {
336 return Err(through_alias_refused(
337 segments,
338 segments,
339 anchor_before(document, value_start).as_deref(),
340 "set",
341 ));
342 }
343
344 let bytes = content.as_bytes();
345 let key_column = line_column_of(content, key_start);
346 let indent = key_column + document.indent_unit();
347
348 let mut start = value_start;
349 while start > 0 && matches!(bytes[start - 1], b' ' | b'\t' | b'\n' | b'\r') {
350 start -= 1;
351 }
352 let end = end_of_trailing_inline_comment(content, value_end);
353
354 let fragment = block_fragment(value, document.indent_unit(), indent, newline)?;
355 document
356 .replace_span(start, end, &fragment)
357 .map_err(|error| edit_refused("set", &error))
358}
359
360fn append_to_sequence_item_mapping(
364 document: &mut noyalib::cst::Document,
365 content: &str,
366 parent_path: &str,
367 key: &str,
368 value: &Value,
369) -> DocumentResult<bool> {
370 let Some((start, end)) = document.span_at(parent_path) else {
371 return Ok(false);
372 };
373 let Some(dash_column) = preceding_sequence_dash_column(content, start) else {
374 return Ok(false);
375 };
376 if content[start..end].trim_start().starts_with('{') {
377 return Ok(false);
378 }
379 let newline = if content.contains("\r\n") {
380 "\r\n"
381 } else {
382 "\n"
383 };
384 let entry = Value::Object([(key.to_string(), value.clone())].into_iter().collect());
385 let fragment = block_fragment(&entry, document.indent_unit(), dash_column + 2, newline)?;
386 let at = end_of_trailing_inline_comment(content, end);
387 document
388 .replace_span(at, at, &fragment)
389 .map_err(|error| edit_refused("set", &error))?;
390 Ok(true)
391}
392
393fn insert_beside_merge_key(
401 document: &mut noyalib::cst::Document,
402 content: &str,
403 parent_path: &str,
404 key: &str,
405 value: &Value,
406) -> DocumentResult<bool> {
407 let Some(key_start) = document.span_at(parent_path).and_then(|(start, end)| {
411 let text = &content[start..end];
412 let key_start = start + (text.len() - text.trim_start_matches(' ').len());
413 content[key_start..].starts_with("<<").then_some(key_start)
414 }) else {
415 return Ok(false);
416 };
417 let line_start = content[..key_start]
418 .rfind('\n')
419 .map_or(0, |index| index + 1);
420 if !content[line_start..key_start]
421 .bytes()
422 .all(|byte| byte == b' ')
423 {
424 return Ok(false);
425 }
426 let column = key_start - line_start;
427 let mut at = content[key_start..]
428 .find('\n')
429 .map_or(content.len(), |offset| key_start + offset);
430 let next_line = content[at..].trim_start_matches(['\r', '\n']);
432 let continues = next_line.lines().next().is_some_and(|line| {
433 !line.trim().is_empty() && line.len() - line.trim_start().len() > column
434 });
435 if continues {
436 return Ok(false);
437 }
438 if at > key_start && content.as_bytes()[at - 1] == b'\r' {
439 at -= 1;
440 }
441 let newline = if content.contains("\r\n") {
442 "\r\n"
443 } else {
444 "\n"
445 };
446 let entry = Value::Object([(key.to_string(), value.clone())].into_iter().collect());
447 let fragment = block_fragment(&entry, document.indent_unit(), column, newline)?;
448 document
449 .replace_span(at, at, &fragment)
450 .map_err(|error| edit_refused("set", &error))?;
451 Ok(true)
452}
453
454fn block_fragment(
460 value: &Value,
461 indent_unit: usize,
462 indent: usize,
463 newline: &str,
464) -> DocumentResult<String> {
465 match value {
466 Value::Array(items) if items.is_empty() => return Ok(" []".to_string()),
467 Value::Object(entries) if entries.is_empty() => return Ok(" {}".to_string()),
468 _ => {}
469 }
470 let config = noyalib::SerializerConfig::new()
471 .indent(indent_unit)
472 .flow_style(noyalib::FlowStyle::Block);
473 let rendered = render(value, Some(&config))?;
477 let pad = " ".repeat(indent);
478 let mut fragment = String::new();
479 for line in rendered.trim_end_matches(['\r', '\n']).lines() {
480 fragment.push_str(newline);
481 if line.is_empty() {
482 continue;
483 }
484 fragment.push_str(&pad);
485 fragment.push_str(line);
486 }
487 Ok(fragment)
488}
489
490fn line_column_of(content: &str, offset: usize) -> usize {
492 let line_start = content[..offset].rfind('\n').map_or(0, |index| index + 1);
493 offset - line_start
494}
495
496fn end_of_trailing_inline_comment(content: &str, value_end: usize) -> usize {
499 let bytes = content.as_bytes();
500 let mut index = value_end;
501 while index < bytes.len() && matches!(bytes[index], b' ' | b'\t') {
502 index += 1;
503 }
504 if index >= bytes.len() || bytes[index] != b'#' {
505 return value_end;
506 }
507 while index < bytes.len() && bytes[index] != b'\n' {
508 index += 1;
509 }
510 if index > 0 && bytes[index - 1] == b'\r' {
511 index -= 1;
512 }
513 index
514}
515
516pub(crate) fn unset_preserving(content: &str, path: &str) -> DocumentResult<String> {
518 let segments = crate::document::parse_path(path)?;
519 let (leaf, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
520 let parent_path = crate::document::join_path(parents);
521 let root = load(content)?;
522 let parent = if parents.is_empty() {
523 &root
524 } else {
525 crate::document::get_path_ref(&root, &parent_path, Addressing::INDEX_ONLY)?
526 };
527 if let (Value::Array(_), Ok(index)) = (parent, leaf.parse::<usize>()) {
528 return remove_array_item(content, &parent_path, index, "unset");
529 }
530 let yaml_path = cst_path(&segments, "unset")?;
531 guard_cst_segments(content, &segments, "unset", false)?;
532 let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
533 format: "YAML".to_string(),
534 detail: error.to_string(),
535 })?;
536 refuse_shared_nodes(
537 &document,
538 content,
539 &segments,
540 segments.len() - 1,
541 "unset",
542 false,
543 )?;
544 document
545 .remove(&yaml_path)
546 .map_err(|error| edit_refused("unset", &error))?;
547 document
548 .validate()
549 .map_err(|error| DocumentError::ParseError {
550 format: "YAML".to_string(),
551 detail: error.to_string(),
552 })?;
553 Ok(document.to_string())
554}
555
556pub(crate) fn append_array_item_preserving(
559 content: &str,
560 path: &str,
561 item: &Value,
562) -> DocumentResult<String> {
563 let segments = array_path_segments(path)?;
564 let yaml_path = cst_path(&segments, "add")?;
565 let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
566 format: "YAML".to_string(),
567 detail: error.to_string(),
568 })?;
569 refuse_shared_nodes(&document, content, &segments, segments.len(), "add", false)?;
570 let loaded = load(content)?;
571 let existing = array_at_path(&loaded, path, "add")?;
572 let previous_len = existing.len();
573 let canonical_item = load(&save(item)?)?;
576 if previous_len == 0 {
577 if path.is_empty()
588 || segments
589 .last()
590 .is_some_and(|part| part.parse::<usize>().is_ok())
591 {
592 let (start, end) = document
593 .span_at(&yaml_path)
594 .ok_or_else(|| DocumentError::PathNotFound { path: path.into() })?;
595 let replacement = flow_fragment(&Value::Array(vec![item.clone()]))?;
596 document
597 .replace_span(start, end, &replacement)
598 .map_err(|error| edit_refused("add", &error))?;
599 let output = document.to_string();
600 let edited = load(&output)?;
601 if array_at_path(&edited, path, "add")?.as_slice()
602 != std::slice::from_ref(&canonical_item)
603 {
604 return Err(DocumentError::UnsupportedOperation {
605 format: "YAML".into(),
606 operation: "add".into(),
607 detail: "the source edit did not reproduce the requested item".into(),
608 });
609 }
610 return Ok(output);
611 }
612 return set_preserving(content, path, &Value::Array(vec![item.clone()]));
613 }
614 let mut fragment = yaml_fragment(item, "add")?;
615 {
616 let item_path = format!("{yaml_path}[{}]", previous_len - 1);
617 let (item_start, _) =
618 document
619 .span_at(&item_path)
620 .ok_or_else(|| DocumentError::UnsupportedOperation {
621 format: "YAML".to_string(),
622 operation: "add".to_string(),
623 detail: "could not resolve the existing sequence-item indentation".to_string(),
624 })?;
625 let dash_column = preceding_sequence_dash_column(content, item_start).ok_or_else(|| {
626 DocumentError::UnsupportedOperation {
627 format: "YAML".to_string(),
628 operation: "add".to_string(),
629 detail: "only block sequences can be extended without rebuilding the document"
630 .to_string(),
631 }
632 })?;
633 fragment = indent_continuation_lines(fragment.trim_end(), dash_column + 2);
634 }
635 document
636 .push_back(&yaml_path, fragment.trim_end())
637 .map_err(|error| edit_refused("add", &error))?;
638 document
639 .validate()
640 .map_err(|error| DocumentError::ParseError {
641 format: "YAML".to_string(),
642 detail: error.to_string(),
643 })?;
644 let output = document.to_string();
645 let edited = load(&output)?;
646 let edited_items = array_at_path(&edited, path, "add")?;
647 if edited_items.len() != previous_len + 1 || edited_items.last() != Some(&canonical_item) {
648 return Err(DocumentError::UnsupportedOperation {
649 format: "YAML".to_string(),
650 operation: "add".to_string(),
651 detail: "the source edit did not reproduce the requested keyed item".to_string(),
652 });
653 }
654 Ok(output)
655}
656
657pub(crate) fn remove_array_item_preserving(
659 content: &str,
660 path: &str,
661 index: usize,
662) -> DocumentResult<String> {
663 remove_array_item(content, path, index, "remove")
664}
665
666fn remove_array_item(
667 content: &str,
668 path: &str,
669 index: usize,
670 operation: &str,
671) -> DocumentResult<String> {
672 let segments = array_path_segments(path)?;
673 let mut item_segments = segments.clone();
674 item_segments.push(index.to_string());
675 guard_cst_segments(content, &item_segments, operation, false)?;
676 let loaded = load(content)?;
677 let len = array_at_path(&loaded, path, operation)?.len();
678 let mut document = parse_document(content).map_err(|error| DocumentError::ParseError {
679 format: "YAML".to_string(),
680 detail: error.to_string(),
681 })?;
682 refuse_shared_nodes(
683 &document,
684 content,
685 &item_segments,
686 segments.len(),
687 operation,
688 false,
689 )?;
690 let yaml_path = cst_path(&segments, operation)?;
691 if len == 1 && index == 0 {
692 if !path.is_empty()
693 && segments
694 .last()
695 .is_some_and(|part| part.parse::<usize>().is_err())
696 {
697 return set_preserving(content, path, &Value::Array(Vec::new()));
698 }
699 let (start, end) = if path.is_empty() {
700 root_value_span(document.syntax(), 0)
701 } else {
702 document.span_at(&yaml_path)
703 }
704 .ok_or_else(|| DocumentError::PathNotFound { path: path.into() })?;
705 let end = start + content[start..end].trim_end().len();
706 let prefix = &content[..start];
707 let before_space = prefix.trim_end_matches([' ', '\t', '\r', '\n']);
708 let (start, replacement) = if !path.is_empty()
709 && prefix[before_space.len()..].contains('\n')
710 && before_space.ends_with('-')
711 {
712 (before_space.len(), " []")
715 } else {
716 (start, "[]")
717 };
718 document
719 .replace_span(start, end, replacement)
720 .map_err(|error| edit_refused(operation, &error))?;
721 let output = document.to_string();
722 if array_at_path(&load(&output)?, path, operation)?.is_empty() {
723 return Ok(output);
724 }
725 return Err(DocumentError::WriteWouldCorrupt {
726 format: "YAML".into(),
727 detail: "edited source did not reproduce an empty sequence".into(),
728 });
729 }
730 document
731 .remove(&format!("{yaml_path}[{index}]"))
732 .map_err(|error| edit_refused(operation, &error))?;
733 document
734 .validate()
735 .map_err(|error| DocumentError::ParseError {
736 format: "YAML".to_string(),
737 detail: error.to_string(),
738 })?;
739 Ok(document.to_string())
740}
741
742fn root_value_span(node: &GreenNode, mut offset: usize) -> Option<(usize, usize)> {
745 let mut span: Option<(usize, usize)> = None;
746 for child in node.children() {
747 let end = offset + child.text_len();
748 let child_span = match child {
749 GreenChild::Node(inner) => root_value_span(inner, offset),
750 GreenChild::Token {
751 kind:
752 SyntaxKind::Whitespace
753 | SyntaxKind::Newline
754 | SyntaxKind::Comment
755 | SyntaxKind::Bom
756 | SyntaxKind::Directive
757 | SyntaxKind::DocStart
758 | SyntaxKind::DocEnd,
759 ..
760 } => None,
761 GreenChild::Token { .. } => Some((offset, end)),
762 };
763 if let Some((first, last)) = child_span {
764 span = Some((span.map_or(first, |(start, _)| start), last));
765 }
766 offset = end;
767 }
768 span
769}
770
771fn array_path_segments(path: &str) -> DocumentResult<Vec<String>> {
774 if path.is_empty() {
775 Ok(Vec::new())
776 } else {
777 crate::document::parse_path(path)
778 }
779}
780
781fn array_at_path<'a>(
782 value: &'a Value,
783 path: &str,
784 operation: &str,
785) -> DocumentResult<&'a Vec<Value>> {
786 let target = if path.is_empty() {
787 value
788 } else {
789 crate::document::get_path_ref(value, path, Addressing::INDEX_ONLY)?
790 };
791 target
792 .as_array()
793 .ok_or_else(|| DocumentError::UnsupportedOperation {
794 format: "YAML".to_string(),
795 operation: operation.to_string(),
796 detail: "target is not an array".to_string(),
797 })
798}
799
800fn preceding_sequence_dash_column(content: &str, value_start: usize) -> Option<usize> {
801 let bytes = content.as_bytes();
802 let mut position = value_start;
803 let dash = loop {
804 position = position.checked_sub(1)?;
805 match bytes.get(position)? {
806 b' ' | b'\t' => {}
807 b'-' => break position,
808 _ => return None,
809 }
810 };
811 let line_start = content.as_bytes()[..dash]
812 .iter()
813 .rposition(|byte| *byte == b'\n')
814 .map_or(0, |newline| newline + 1);
815 Some(dash - line_start)
816}
817
818fn indent_continuation_lines(fragment: &str, indent: usize) -> String {
819 if !fragment.contains('\n') {
820 return fragment.to_string();
821 }
822 let padding = " ".repeat(indent);
823 let mut output = String::with_capacity(fragment.len() + indent * 4);
824 for (index, line) in fragment.split('\n').enumerate() {
825 if index > 0 {
826 output.push('\n');
827 if !line.is_empty() {
828 output.push_str(&padding);
829 }
830 }
831 output.push_str(line);
832 }
833 output
834}
835
836fn cst_path(segments: &[String], operation: &str) -> DocumentResult<String> {
837 let mut path = String::new();
838 for segment in segments {
839 if segment.contains(['.', '\\', '[', ']']) {
840 return Err(DocumentError::UnsupportedOperation {
841 format: "YAML".to_string(),
842 operation: operation.to_string(),
843 detail:
844 "escaped or bracketed YAML keys require a quoted-key CST span and are not supported"
845 .to_string(),
846 });
847 }
848 if let Ok(index) = segment.parse::<usize>() {
849 path.push_str(&format!("[{index}]"));
850 } else {
851 if !path.is_empty() {
852 path.push('.');
853 }
854 path.push_str(segment);
855 }
856 }
857 Ok(path)
858}
859
860fn edit_refused(operation: &str, error: &noyalib::Error) -> DocumentError {
865 let reason = match error {
866 noyalib::Error::Parse(message) | noyalib::Error::ParseWithLocation { message, .. } => {
867 message.clone()
868 }
869 other => other.to_string(),
870 };
871 let reason = match reason.split_once(": ") {
872 Some((routine, rest))
873 if !routine.is_empty()
874 && routine.bytes().all(|b| b.is_ascii_lowercase() || b == b'_') =>
875 {
876 rest.to_string()
877 }
878 _ => reason,
879 };
880 let diagnosis = reason.split(" \u{2014} ").next().unwrap_or(&reason);
883 let detail = format!("cannot safely edit this YAML layout in place: {diagnosis}");
884 DocumentError::UnsupportedOperation {
885 format: "YAML".to_string(),
886 operation: operation.to_string(),
887 detail,
888 }
889}
890
891fn through_alias_refused(
897 target: &[String],
898 site: &[String],
899 alias: Option<&str>,
900 operation: &str,
901) -> DocumentError {
902 let alias = alias.map_or_else(|| "a YAML alias".to_string(), |name| format!("`*{name}`"));
903 let target = crate::document::join_path(target);
904 let site = crate::document::join_path(site);
905 let location = if site == target {
906 String::new()
907 } else {
908 format!(" at `{site}`")
909 };
910 DocumentError::SharedNode {
911 operation: operation.to_string(),
912 path: target,
913 detail: format!(
914 "it is reached through the alias {alias}{location}, so the edit would land in the \
915 anchored value and change every alias of it; write the alias site itself to give \
916 it a value of its own"
917 ),
918 }
919}
920
921fn shared_by_aliases_refused(
924 target: &[String],
925 anchored: &[String],
926 anchor: &str,
927 sites: usize,
928 operation: &str,
929) -> DocumentError {
930 let anchored = crate::document::join_path(anchored);
931 DocumentError::SharedNode {
932 operation: operation.to_string(),
933 path: crate::document::join_path(target),
934 detail: format!(
935 "`{anchored}` is anchored as `&{anchor}` and aliased at {sites} other site(s), so \
936 the edit would change every one of them; write each alias site to give it a value \
937 of its own first"
938 ),
939 }
940}
941
942fn inherited_by_merge_refused(target: &[String], operation: &str) -> DocumentError {
945 DocumentError::SharedNode {
946 operation: operation.to_string(),
947 path: crate::document::join_path(target),
948 detail: "the mapping inherits this key through a `<<` merge and has no entry of its \
949 own to change in place; `set` it to give the mapping an entry that \
950 overrides the merge"
951 .to_string(),
952 }
953}
954
955fn anchor_before(document: &noyalib::cst::Document, value_start: usize) -> Option<String> {
958 document
959 .anchors()
960 .into_iter()
961 .rev()
962 .find(|anchor| anchor.mark_span.1 <= value_start)
963 .map(|anchor| anchor.name)
964}
965
966fn refuse_shared_nodes(
984 document: &noyalib::cst::Document,
985 content: &str,
986 target: &[String],
987 walked: usize,
988 operation: &str,
989 leaf_may_be_inherited: bool,
990) -> DocumentResult<()> {
991 let loaded = load(content)?;
992 let mut current = Some(&loaded);
993 for (index, segment) in target.iter().enumerate() {
994 let prefix = &target[..=index];
995 let yaml_prefix = cst_path(prefix, operation)?;
996 current = match current {
997 Some(Value::Object(object)) => object.get(segment),
998 Some(Value::Array(items)) => segment
999 .parse::<usize>()
1000 .ok()
1001 .and_then(|position| items.get(position)),
1002 _ => None,
1003 };
1004 let Some((start, _)) = document.span_at(&yaml_prefix) else {
1005 if current.is_some()
1009 && segment.parse::<usize>().is_err()
1010 && document.key_span(&yaml_prefix).is_none()
1011 && !(leaf_may_be_inherited && index + 1 == target.len())
1012 {
1013 return Err(inherited_by_merge_refused(prefix, operation));
1014 }
1015 return Ok(());
1016 };
1017 let through_alias = match segment.parse::<usize>() {
1018 Ok(0) if index > 0 => document
1019 .span_at(&cst_path(&target[..index], operation)?)
1020 .is_some_and(|(parent_start, _)| start < parent_start),
1021 Ok(0) => false,
1022 Ok(position) => {
1023 let previous = format!(
1024 "{}[{}]",
1025 cst_path(&target[..index], operation)?,
1026 position - 1
1027 );
1028 document
1029 .span_at(&previous)
1030 .is_some_and(|(_, previous_end)| start < previous_end)
1031 }
1032 Err(_) => document
1033 .key_span(&yaml_prefix)
1034 .is_some_and(|(_, key_end)| start < key_end),
1035 };
1036 if through_alias {
1037 if index >= walked {
1038 return Ok(());
1040 }
1041 return Err(through_alias_refused(
1042 target,
1043 prefix,
1044 anchor_before(document, start).as_deref(),
1045 operation,
1046 ));
1047 }
1048 if let Some((anchor, sites)) = anchor_with_sites(document, content, start) {
1049 return Err(shared_by_aliases_refused(
1050 target, prefix, &anchor, sites, operation,
1051 ));
1052 }
1053 }
1054 if operation != "add"
1055 && let Some((start, end)) = document.span_at(&cst_path(target, operation)?)
1056 {
1057 for anchor in document.anchors() {
1058 if anchor.mark_span.0 < start || anchor.mark_span.1 > end {
1059 continue;
1060 }
1061 let external = document
1062 .aliases_of(&anchor.name)
1063 .iter()
1064 .filter(|alias| alias.mark_span.0 < start || alias.mark_span.1 > end)
1065 .count();
1066 if external > 0 {
1067 return Err(shared_by_aliases_refused(
1068 target,
1069 target,
1070 &anchor.name,
1071 external,
1072 operation,
1073 ));
1074 }
1075 }
1076 }
1077 Ok(())
1078}
1079
1080fn anchor_with_sites(
1084 document: &noyalib::cst::Document,
1085 content: &str,
1086 value_start: usize,
1087) -> Option<(String, usize)> {
1088 document.anchors().into_iter().find_map(|anchor| {
1089 let attached = anchor.mark_span.0 == value_start
1091 || content
1092 .get(anchor.mark_span.1..value_start)
1093 .is_some_and(|between| between.trim().is_empty());
1094 if !attached {
1095 return None;
1096 }
1097 let sites = document.aliases_of(&anchor.name).len();
1098 (sites > 0).then_some((anchor.name, sites))
1099 })
1100}
1101
1102fn guard_cst_segments(
1103 content: &str,
1104 segments: &[String],
1105 operation: &str,
1106 allow_missing: bool,
1107) -> DocumentResult<()> {
1108 let root = load(content)?;
1109 let mut current = &root;
1110 for (index, segment) in segments.iter().enumerate() {
1111 match current {
1112 Value::Object(object) => {
1113 if segment.parse::<usize>().is_ok() || segment.contains(['[', ']']) {
1114 return Err(DocumentError::UnsupportedOperation {
1115 format: "YAML".to_string(),
1116 operation: operation.to_string(),
1117 detail: format!(
1118 "mapping key `{segment}` is ambiguous in the CST path grammar"
1119 ),
1120 });
1121 }
1122 match object.get(segment) {
1123 Some(next) => current = next,
1124 None if allow_missing => {
1125 if segments[index..]
1126 .iter()
1127 .any(|part| part.parse::<usize>().is_ok() || part.contains(['[', ']']))
1128 {
1129 return Err(DocumentError::UnsupportedOperation {
1130 format: "YAML".to_string(),
1131 operation: operation.to_string(),
1132 detail: "a missing mapping chain contains a CST-ambiguous key"
1133 .to_string(),
1134 });
1135 }
1136 return Ok(());
1137 }
1138 None => {
1139 return Err(DocumentError::PathNotFound {
1140 path: crate::document::join_path(&segments[..=index]),
1141 });
1142 }
1143 }
1144 }
1145 Value::Array(values) => {
1146 let array_index =
1147 segment
1148 .parse::<usize>()
1149 .map_err(|_| DocumentError::UnregisteredArray {
1150 path: crate::document::join_path(&segments[..index]),
1151 })?;
1152 current =
1153 values
1154 .get(array_index)
1155 .ok_or_else(|| DocumentError::IndexOutOfBounds {
1156 path: crate::document::join_path(&segments[..index]),
1157 index: array_index,
1158 len: values.len(),
1159 })?;
1160 }
1161 value => {
1162 return Err(DocumentError::NotTraversable {
1163 path: crate::document::join_path(&segments[..index]),
1164 got: value.kind_name().to_string(),
1165 });
1166 }
1167 }
1168 }
1169 Ok(())
1170}
1171
1172fn to_noyalib_value(value: &Value) -> DocumentResult<YamlValue> {
1173 match value {
1174 Value::Null => Ok(YamlValue::Null),
1175 Value::Bool(value) => Ok(YamlValue::Bool(*value)),
1176 Value::Integer(value) => Ok(YamlValue::from(*value)),
1177 Value::Unsigned(value) => Ok(YamlValue::from(*value)),
1178 Value::Float(value) if value.is_finite() => Ok(YamlValue::from(*value)),
1179 Value::Float(_) => Err(DocumentError::UnsupportedOperation {
1180 format: "YAML".to_string(),
1181 operation: "set".to_string(),
1182 detail: "non-finite YAML float is not representable".to_string(),
1183 }),
1184 Value::Number(text) if value.is_float() => text
1190 .parse::<f64>()
1191 .ok()
1192 .filter(|value| value.is_finite())
1193 .map(YamlValue::from)
1194 .ok_or_else(|| DocumentError::UnsupportedOperation {
1195 format: "YAML".to_string(),
1196 operation: "set".to_string(),
1197 detail: "float literal is not representable in YAML".to_string(),
1198 }),
1199 Value::Number(_) => Err(DocumentError::UnsupportedOperation {
1200 format: "YAML".to_string(),
1201 operation: "set".to_string(),
1202 detail: "integer literal exceeds YAML's 64-bit integer range".to_string(),
1203 }),
1204 Value::String(value) => Ok(YamlValue::String(value.clone())),
1205 Value::Array(values) => Ok(YamlValue::Sequence(
1206 values
1207 .iter()
1208 .map(to_noyalib_value)
1209 .collect::<DocumentResult<Vec<_>>>()?,
1210 )),
1211 Value::Object(values) => {
1212 let mut mapping = YamlMapping::new();
1213 for (key, value) in values {
1214 mapping.insert(key.clone(), to_noyalib_value(value)?);
1215 }
1216 Ok(YamlValue::Mapping(mapping))
1217 }
1218 }
1219}
1220
1221pub fn save(value: &Value) -> DocumentResult<String> {
1222 render(value, None)
1223}
1224
1225fn flow_fragment(value: &Value) -> DocumentResult<String> {
1231 let config = noyalib::SerializerConfig::new().flow_style(noyalib::FlowStyle::Flow);
1232 let rendered = render(value, Some(&config))?;
1233 let line = rendered.trim_end_matches(['\r', '\n']);
1234 if line.contains('\n') {
1235 return Err(DocumentError::UnsupportedOperation {
1236 format: "YAML".to_string(),
1237 operation: "add".to_string(),
1238 detail: "the item has no single-line flow spelling".to_string(),
1239 });
1240 }
1241 Ok(line.to_string())
1242}
1243
1244fn render(value: &Value, config: Option<&noyalib::SerializerConfig>) -> DocumentResult<String> {
1245 let mut prefix = "__AFDATA_EXACT_NUMBER_".to_string();
1246 while value_contains_text(value, &prefix) {
1247 prefix.push('_');
1248 }
1249 let mut literals = Vec::new();
1250 let yaml_val = our_value_to_yaml_value(value, &prefix, &mut literals)?;
1251 let rendered = match config {
1252 Some(config) => noyalib::to_string_value_with_config(&yaml_val, config),
1253 None => to_string(&yaml_val),
1254 };
1255 let mut output = rendered.map_err(|e| DocumentError::ParseError {
1256 format: "YAML".to_string(),
1257 detail: e.to_string(),
1258 })?;
1259 for (sentinel, literal) in literals {
1260 output = output.replace(&sentinel, &literal);
1261 }
1262 Ok(output)
1263}
1264
1265fn value_to_our_value(v: YamlValue, literals: &std::collections::HashMap<String, String>) -> Value {
1266 match v {
1267 YamlValue::Null => Value::Null,
1268 YamlValue::Bool(b) => Value::Bool(b),
1269 YamlValue::Number(n) => {
1270 if let Some(i) = n.as_i64() {
1271 Value::Integer(i)
1272 } else if let Some(u) = n.as_u64() {
1273 Value::Unsigned(u)
1274 } else {
1275 Value::Float(n.as_f64())
1276 }
1277 }
1278 YamlValue::String(s) => literals
1279 .get(&s)
1280 .cloned()
1281 .map(Value::Number)
1282 .unwrap_or(Value::String(s)),
1283 YamlValue::Sequence(seq) => Value::Array(
1284 seq.into_iter()
1285 .map(|value| value_to_our_value(value, literals))
1286 .collect(),
1287 ),
1288 YamlValue::Mapping(map) => {
1289 let mut obj = std::collections::BTreeMap::new();
1290 for (key, value) in map {
1291 let key = literals.get(&key).cloned().unwrap_or(key);
1292 obj.insert(key, value_to_our_value(value, literals));
1293 }
1294 Value::Object(obj)
1295 }
1296 YamlValue::Tagged(t) => {
1297 let (_, value) = t.into_parts();
1299 value_to_our_value(value, literals)
1300 }
1301 }
1302}
1303
1304fn our_value_to_yaml_value(
1305 v: &Value,
1306 prefix: &str,
1307 literals: &mut Vec<(String, String)>,
1308) -> DocumentResult<YamlValue> {
1309 match v {
1310 Value::Null => Ok(YamlValue::Null),
1311 Value::Bool(b) => Ok(YamlValue::Bool(*b)),
1312 Value::Integer(i) => Ok(YamlValue::Number((*i).into())),
1313 Value::Unsigned(i) => Ok(YamlValue::Number((*i).into())),
1314 Value::Float(f) if f.is_finite() => Ok(YamlValue::Number((*f).into())),
1315 Value::Float(_) => Err(DocumentError::UnsupportedOperation {
1316 format: "YAML".to_string(),
1317 operation: "save".to_string(),
1318 detail: "non-finite float is not representable in YAML".to_string(),
1319 }),
1320 Value::Number(text) => {
1321 if !is_json_number(text) {
1322 return Err(DocumentError::UnsupportedOperation {
1323 format: "YAML".to_string(),
1324 operation: "save".to_string(),
1325 detail: "invalid number literal".to_string(),
1326 });
1327 }
1328 let sentinel = format!("{prefix}{}__", literals.len());
1329 literals.push((sentinel.clone(), text.clone()));
1330 Ok(YamlValue::String(sentinel))
1331 }
1332 Value::String(s) => Ok(YamlValue::String(protect_yaml_string(s, prefix, literals))),
1333 Value::Array(a) => {
1334 let seq = a
1335 .iter()
1336 .map(|value| our_value_to_yaml_value(value, prefix, literals))
1337 .collect::<DocumentResult<Vec<_>>>()?;
1338 Ok(YamlValue::Sequence(seq))
1339 }
1340 Value::Object(o) => {
1341 let mut mapping = YamlMapping::new();
1342 for (k, v) in o {
1343 mapping.insert(
1344 protect_yaml_string(k, prefix, literals),
1345 our_value_to_yaml_value(v, prefix, literals)?,
1346 );
1347 }
1348 Ok(YamlValue::Mapping(mapping))
1349 }
1350 }
1351}
1352
1353fn quoted_yaml_string(text: &str) -> String {
1354 format!("\"{}\"", crate::formatting::escape_yaml_str(text))
1355}
1356
1357fn protect_yaml_string(text: &str, prefix: &str, literals: &mut Vec<(String, String)>) -> String {
1358 if yaml_needs_legacy_quotes(text) {
1359 let placeholder = format!("{prefix}{}__", literals.len());
1360 literals.push((placeholder.clone(), quoted_yaml_string(text)));
1361 placeholder
1362 } else {
1363 text.to_owned()
1364 }
1365}
1366
1367fn yaml_needs_legacy_quotes(text: &str) -> bool {
1369 let lower = text.to_ascii_lowercase();
1370 if matches!(
1371 lower.as_str(),
1372 "" | "y" | "n" | "yes" | "no" | "on" | "off" | "true" | "false" | "null" | "~"
1373 ) {
1374 return true;
1375 }
1376 let unsigned = lower.strip_prefix(['+', '-']).unwrap_or(&lower);
1377 if matches!(unsigned, ".inf" | ".nan") {
1378 return true;
1379 }
1380 let number = unsigned.replace('_', "");
1381 if number.starts_with(|c: char| c.is_ascii_digit() || c == '.')
1382 && (number.parse::<f64>().is_ok()
1383 || ["0b", "0o", "0x"]
1384 .into_iter()
1385 .zip([2, 8, 16])
1386 .any(|(prefix, radix)| {
1387 number.strip_prefix(prefix).is_some_and(|digits| {
1388 !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix))
1389 })
1390 })
1391 || number.split_once(':').is_some_and(|(first, rest)| {
1392 !first.is_empty()
1393 && first.bytes().all(|c| c.is_ascii_digit())
1394 && rest.split(':').all(|part| part.parse::<f64>().is_ok())
1395 }))
1396 {
1397 return true;
1398 }
1399 text.as_bytes().get(4) == Some(&b'-')
1400 && text.as_bytes()[..4].iter().all(u8::is_ascii_digit)
1401 && text[5..].split_once('-').is_some_and(|(month, day)| {
1402 (1..=2).contains(&month.len())
1403 && month.bytes().all(|c| c.is_ascii_digit())
1404 && day.starts_with(|c: char| c.is_ascii_digit())
1405 })
1406}
1407
1408fn quote_inserted_scalars(document: &noyalib::cst::Document, path: &str) -> String {
1412 let source = document.source();
1413 let mut spans = Vec::new();
1414 if let Some((start, end)) = document.key_span(path)
1415 && yaml_needs_legacy_quotes(&source[start..end])
1416 {
1417 spans.push((start, end));
1418 }
1419 if let Some((start, end)) = document.span_at(path) {
1420 collect_legacy_string_spans(document.syntax(), source, 0, start..end, &mut spans);
1421 }
1422 let mut output = source.to_owned();
1423 for (start, end) in spans.into_iter().rev() {
1424 output.replace_range(start..end, "ed_yaml_string(&source[start..end]));
1425 }
1426 output
1427}
1428
1429fn collect_legacy_string_spans(
1430 node: &GreenNode,
1431 source: &str,
1432 mut offset: usize,
1433 range: std::ops::Range<usize>,
1434 spans: &mut Vec<(usize, usize)>,
1435) {
1436 for child in node.children() {
1437 let end = offset + child.text_len();
1438 if offset < range.end && end > range.start {
1439 match child {
1440 GreenChild::Node(node) => {
1441 collect_legacy_string_spans(node, source, offset, range.clone(), spans)
1442 }
1443 GreenChild::Token {
1444 kind: SyntaxKind::PlainScalar,
1445 ..
1446 } if offset >= range.start => {
1447 let text = source[offset..end].trim_end();
1448 if yaml_needs_legacy_quotes(text)
1449 && noyalib::from_str::<YamlValue>(text)
1450 .is_ok_and(|value| matches!(value, YamlValue::String(_)))
1451 {
1452 spans.push((offset, offset + text.len()));
1453 }
1454 }
1455 _ => {}
1456 }
1457 }
1458 offset = end;
1459 }
1460}
1461
1462fn yaml_fragment(value: &Value, operation: &str) -> DocumentResult<String> {
1463 if let Value::String(text) = value
1464 && yaml_needs_legacy_quotes(text)
1465 {
1466 return Ok(quoted_yaml_string(text));
1467 }
1468 if let Value::Number(text) = value
1469 && is_json_number(text)
1470 {
1471 return Ok(text.clone());
1472 }
1473 if matches!(value, Value::Array(_) | Value::Object(_)) {
1474 return save(value);
1475 }
1476 to_string(&to_noyalib_value(value)?).map_err(|error| DocumentError::UnsupportedOperation {
1477 format: "YAML".to_string(),
1478 operation: operation.to_string(),
1479 detail: error.to_string(),
1480 })
1481}
1482
1483fn protect_exact_numbers(
1484 content: &str,
1485) -> DocumentResult<(String, std::collections::HashMap<String, String>)> {
1486 let document = parse_document(content).map_err(|error| match error {
1487 noyalib::Error::MoreThanOneDocument => {
1488 let first_end = noyalib::cst::parse_stream(content).ok()
1489 .and_then(|documents| documents.first().map(|document| document.source().len()));
1490 let line = first_end.map(|end| content[..end].lines().count() + 1);
1491 DocumentError::SourceRefused {
1492 format: "YAML".to_string(),
1493 detail: match line {
1494 Some(line) => format!("multiple documents are not supported (second document starts near line {line})"),
1495 None => "multiple documents are not supported".to_string(),
1496 },
1497 }
1498 }
1499 other => DocumentError::ParseError { format: "YAML".to_string(), detail: other.to_string() },
1500 })?;
1501 let mut spans = Vec::new();
1502 collect_exact_number_spans(document.syntax(), content, 0, &mut spans);
1503 let mut prefix = "__AFDATA_EXACT_NUMBER_".to_string();
1504 while content.contains(&prefix) {
1505 prefix.push('_');
1506 }
1507 let mut protected = content.to_string();
1508 let mut literals = std::collections::HashMap::new();
1509 for (index, (start, end)) in spans.into_iter().enumerate().rev() {
1510 let literal = content[start..end].to_string();
1511 let sentinel = format!("{prefix}{index}__");
1512 let quoted =
1513 serde_json::to_string(&sentinel).map_err(|error| DocumentError::ParseError {
1514 format: "YAML".to_string(),
1515 detail: error.to_string(),
1516 })?;
1517 protected.replace_range(start..end, "ed);
1518 literals.insert(sentinel, literal);
1519 }
1520 Ok((protected, literals))
1521}
1522
1523fn collect_exact_number_spans(
1524 node: &GreenNode,
1525 source: &str,
1526 base: usize,
1527 spans: &mut Vec<(usize, usize)>,
1528) {
1529 let mut offset = base;
1530 for child in node.children() {
1531 match child {
1532 GreenChild::Node(node) => collect_exact_number_spans(node, source, offset, spans),
1533 GreenChild::Token {
1534 kind: SyntaxKind::PlainScalar,
1535 len,
1536 } => {
1537 let token_end = offset + *len as usize;
1538 let text = source[offset..token_end].trim_end_matches([' ', '\t', '\r', '\n']);
1539 let end = offset + text.len();
1540 if should_preserve_number(text) {
1541 spans.push((offset, end));
1542 }
1543 }
1544 GreenChild::Token { .. } => {}
1545 }
1546 offset += child.text_len();
1547 }
1548}
1549
1550fn should_preserve_number(text: &str) -> bool {
1551 if !is_json_number(text) {
1552 return false;
1553 }
1554 text.contains(['.', 'e', 'E']) || (text.parse::<i64>().is_err() && text.parse::<u64>().is_err())
1555}
1556
1557fn is_json_number(text: &str) -> bool {
1558 serde_json::from_str::<serde_json::Value>(text).is_ok_and(|value| value.is_number())
1559}
1560
1561fn value_contains_text(value: &Value, needle: &str) -> bool {
1562 match value {
1563 Value::Number(text) | Value::String(text) => text.contains(needle),
1564 Value::Array(values) => values
1565 .iter()
1566 .any(|value| value_contains_text(value, needle)),
1567 Value::Object(values) => values
1568 .iter()
1569 .any(|(key, value)| key.contains(needle) || value_contains_text(value, needle)),
1570 _ => false,
1571 }
1572}
1573
1574#[cfg(test)]
1575mod tests {
1576 use super::{load, save, set_preserving};
1577 use crate::document::Value;
1578
1579 #[test]
1580 fn new_fields_in_flow_mappings_preserve_their_exact_value_and_source() {
1581 use crate::document::{Document, Format};
1582 for (source, path) in [
1583 ("{}\n", "field"),
1584 ("{existing: before}\n", "field"),
1585 ("outer: {}\n", "outer.field"),
1586 ("# keep\r\n{}\r\n", "field"),
1587 ] {
1588 for value in [
1589 Value::String("new".into()),
1590 Value::Bool(true),
1591 Value::Null,
1592 Value::Integer(7),
1593 Value::Unsigned(7),
1594 Value::Float(2.0),
1595 Value::Array(Vec::new()),
1596 Value::Object(Default::default()),
1597 Value::Number("123456789012345678901234567890".into()),
1598 Value::Number("0.10000000000000000000001".into()),
1599 ] {
1600 let mut document = Document::parse(source, Format::Yaml).unwrap();
1601 document
1602 .set(path, value.clone())
1603 .expect("insert into a flow mapping");
1604 assert_eq!(document.value_at(path).unwrap(), value);
1605 assert_eq!(
1606 load(document.source()).unwrap(),
1607 load(&save(document.value()).unwrap()).unwrap()
1608 );
1609 if source.starts_with("# keep") {
1610 assert!(document.source().starts_with("# keep\r\n"));
1611 assert!(document.source().ends_with("\r\n"));
1612 }
1613 }
1614 }
1615 }
1616
1617 #[test]
1618 fn a_refused_key_cannot_fall_back_to_inserting_multiple_entries() {
1619 use crate::document::{Document, Format};
1620 let source = "attachments:\n";
1621 let mut document = Document::parse(source, Format::Yaml).unwrap();
1622 let original = document.value().clone();
1623 assert!(
1624 document
1625 .set("one:\ntwo", Value::String("injected".into()))
1626 .is_err()
1627 );
1628 assert_eq!(document.source(), source);
1629 assert_eq!(document.value(), &original);
1630 }
1631
1632 #[test]
1633 fn preserves_large_integer_and_high_precision_float_literals() {
1634 let source = concat!(
1635 "huge: 123456789012345678901234567890\n",
1636 "precise: 0.1000000000000000055511151231257827\n",
1637 );
1638 let value = load(source).expect("load");
1639 assert_eq!(
1640 value.get("huge"),
1641 Some(&Value::Number("123456789012345678901234567890".to_string()))
1642 );
1643 assert_eq!(
1644 value.get("precise"),
1645 Some(&Value::Number(
1646 "0.1000000000000000055511151231257827".to_string()
1647 ))
1648 );
1649
1650 let rendered = save(&value).expect("save");
1651 assert!(rendered.contains("123456789012345678901234567890"));
1652 assert!(rendered.contains("0.1000000000000000055511151231257827"));
1653 assert_eq!(load(&rendered).expect("reload"), value);
1654 }
1655
1656 #[test]
1657 fn exact_number_set_keeps_the_literal() {
1658 let edited = set_preserving(
1659 "price: 1.0\n",
1660 "price",
1661 &Value::Number("12345678901234567890.123456789".to_string()),
1662 )
1663 .expect("set");
1664 assert_eq!(edited, "price: 12345678901234567890.123456789\n");
1665 assert_eq!(
1666 load(&edited).expect("reload").get("price"),
1667 Some(&Value::Number("12345678901234567890.123456789".to_string()))
1668 );
1669 }
1670
1671 fn contact_source() -> &'static str {
1674 "# a leading comment\ndisplay_name: Alice Example\nkind: contact\nemails:\n - alice@example.com # work\ntags: []\nrole: ''\n"
1675 }
1676
1677 #[test]
1678 fn replacing_a_collection_keeps_every_other_byte() {
1679 let edited = set_preserving(
1680 contact_source(),
1681 "tags",
1682 &Value::Array(vec![Value::String("vip".into())]),
1683 )
1684 .expect("an empty sequence can grow");
1685 assert_eq!(
1686 edited,
1687 "# a leading comment\ndisplay_name: Alice Example\nkind: contact\nemails:\n - alice@example.com # work\ntags:\n - vip\nrole: ''\n"
1688 );
1689
1690 let cleared = set_preserving(&edited, "tags", &Value::Array(Vec::new()))
1693 .expect("a sequence can shrink to empty");
1694 assert_eq!(cleared, contact_source());
1695 }
1696
1697 #[test]
1698 fn replacing_a_collection_quotes_elements_that_need_it() {
1699 let edited = set_preserving(
1700 contact_source(),
1701 "tags",
1702 &Value::Array(vec![
1703 Value::String("true".into()),
1704 Value::String("123".into()),
1705 Value::String("a: b".into()),
1706 Value::String("#c".into()),
1707 Value::String(String::new()),
1708 ]),
1709 )
1710 .expect("tricky scalars are the emitter's problem, not ours");
1711 let loaded = load(&edited).expect("the result parses");
1713 assert_eq!(
1714 crate::document::get_path(&loaded, "tags", crate::document::Addressing::INDEX_ONLY)
1715 .expect("tags"),
1716 Value::Array(vec![
1717 Value::String("true".into()),
1718 Value::String("123".into()),
1719 Value::String("a: b".into()),
1720 Value::String("#c".into()),
1721 Value::String(String::new()),
1722 ])
1723 );
1724 }
1725
1726 #[test]
1727 fn replacing_a_collection_takes_the_comment_that_described_it() {
1728 let edited = set_preserving(
1731 "emails:\n - alice@example.com # work\nrole: ''\n",
1732 "emails",
1733 &Value::Array(vec![Value::String("bob@example.com".into())]),
1734 )
1735 .expect("replace");
1736 assert_eq!(edited, "emails:\n - bob@example.com\nrole: ''\n");
1737 assert!(!edited.contains("# work"), "{edited}");
1738 }
1739
1740 #[test]
1741 fn a_collection_reached_through_an_alias_is_refused() {
1742 let source = "base: &b\n - x\nother: *b\n";
1745 let error = set_preserving(
1746 source,
1747 "other",
1748 &Value::Array(vec![Value::String("y".into())]),
1749 )
1750 .expect_err("an alias target must not be edited through");
1751 assert!(error.to_string().contains("alias"), "{error}");
1752 }
1753
1754 #[test]
1755 fn a_new_key_can_be_created_with_a_collection_value() {
1756 let edited = set_preserving(
1757 "kind: contact\n",
1758 "tags",
1759 &Value::Array(vec![Value::String("vip".into())]),
1760 )
1761 .expect("a missing key is inserted");
1762 assert_eq!(edited, "kind: contact\ntags:\n - vip\n");
1763
1764 let empty = set_preserving("kind: contact\n", "tags", &Value::Array(Vec::new()))
1765 .expect("a missing key can be inserted empty");
1766 assert_eq!(empty, "kind: contact\ntags: []\n");
1767 }
1768
1769 #[test]
1770 fn replacing_a_collection_keeps_the_source_newline_style() {
1771 let edited = set_preserving(
1772 "kind: contact\r\ntags: []\r\nrole: ''\r\n",
1773 "tags",
1774 &Value::Array(vec![Value::String("vip".into())]),
1775 )
1776 .expect("CRLF source");
1777 assert_eq!(edited, "kind: contact\r\ntags:\r\n - vip\r\nrole: ''\r\n");
1778 assert!(
1780 !edited.replace("\r\n", "").contains('\n'),
1781 "mixed endings: {edited:?}"
1782 );
1783 }
1784
1785 #[test]
1786 fn a_new_key_lands_after_a_bare_null_last_entry() {
1787 let source = "kind: draft\nattachments:\n";
1790 let edited = set_preserving(source, "sync_intent", &Value::String("send".into()))
1791 .expect("a new key can follow a bare-null entry");
1792 assert_eq!(edited, "kind: draft\nattachments:\nsync_intent: send\n");
1793 }
1794
1795 #[test]
1796 fn save_rejects_non_finite_float() {
1797 let error = save(&Value::Float(f64::NAN)).expect_err("NaN must fail");
1798 assert!(error.to_string().contains("non-finite"));
1799 }
1800}