Skip to main content

agent_first_data/document/format/
toml.rs

1//! TOML format backend (format-preserving via toml_edit).
2
3use super::keep_bom;
4use crate::document::{DocumentError, DocumentResult, Value};
5
6/// Edit an existing TOML item without reserializing the surrounding document.
7///
8/// Scalars, arrays, inline tables, and ordinary tables are supported. Existing
9/// collection nodes are updated in place so their outer decor, element/key
10/// decor, ordering, multiline layout, comments, and trailing-comma style stay
11/// attached to the target wherever the replacement still has a corresponding
12/// element or key. Arrays of tables are addressed element by element (the
13/// caller has already resolved any element identity to an index); replacing
14/// one wholesale is refused.
15pub(crate) fn set_preserving(content: &str, path: &str, value: &Value) -> DocumentResult<String> {
16    keep_bom(content, |body| set_body(body, path, value))
17}
18
19// Path segments arrive unescaped, and `toml_edit` quotes any key that needs
20// it, so `hosts.example\.com` from `paths` addresses `"example.com"` here
21// exactly as it does in every other format.
22fn set_body(content: &str, path: &str, value: &Value) -> DocumentResult<String> {
23    let segments = crate::document::parse_path(path)?;
24    let mut document =
25        content
26            .parse::<toml_edit::DocumentMut>()
27            .map_err(|error| DocumentError::ParseError {
28                format: "TOML".to_string(),
29                detail: error.to_string(),
30            })?;
31    let (last, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
32    let mut current = document.as_item_mut();
33    for parent in parents {
34        if current.is_array_of_tables()
35            || current
36                .as_value()
37                .and_then(toml_edit::Value::as_array)
38                .is_some()
39        {
40            let index = parent
41                .parse::<usize>()
42                .map_err(|_| DocumentError::UnregisteredArray {
43                    path: path.to_string(),
44                })?;
45            current = current
46                .get_mut(index)
47                .ok_or_else(|| DocumentError::PathNotFound {
48                    path: path.to_string(),
49                })?;
50            continue;
51        }
52        // Auto-create a missing intermediate table so a sparse config can grow
53        // (`set imap.host` when `[imap]` is absent), matching `set_path`.
54        // toml_edit returns `Some(Item::None)` for absent keys, so treat that as
55        // a genuinely missing parent rather than a navigable node.
56        {
57            let table =
58                current
59                    .as_table_like_mut()
60                    .ok_or_else(|| DocumentError::UnsupportedOperation {
61                        format: "TOML".to_string(),
62                        operation: "set".to_string(),
63                        detail: "cannot address a key inside a non-table TOML value".to_string(),
64                    })?;
65            if table.get(parent).filter(|item| !item.is_none()).is_none() {
66                let mut created = toml_edit::Table::new();
67                created.set_implicit(true);
68                table.insert(parent, toml_edit::Item::Table(created));
69                hand_closing_space_to_new_entry(current);
70            }
71        }
72        current = current
73            .get_mut(parent)
74            .filter(|item| !item.is_none())
75            .ok_or_else(|| DocumentError::PathNotFound {
76                path: path.to_string(),
77            })?;
78    }
79    if current
80        .as_value()
81        .and_then(toml_edit::Value::as_array)
82        .is_some()
83    {
84        if last == "-" {
85            let parent_key = crate::document::join_path(parents);
86            let mut values = match crate::document::get_path(
87                &load(content)?,
88                &parent_key,
89                crate::document::Addressing::INDEX_ONLY,
90            )? {
91                Value::Array(values) => values,
92                _ => return Err(collection_refusal("set", "append target is not an array")),
93            };
94            let unchanged = values.len();
95            values.push(value.clone());
96            let existing = current
97                .as_array()
98                .ok_or_else(|| collection_refusal("set", "append target is not an array"))?;
99            *current = toml_edit::Item::Value(array_value_with_prefix(
100                &values,
101                Some(existing),
102                unchanged,
103            )?);
104            return Ok(preserve_line_endings(content, document.to_string()));
105        }
106        let index = last
107            .parse::<usize>()
108            .map_err(|_| DocumentError::UnregisteredArray {
109                path: path.to_string(),
110            })?;
111        let target = current
112            .get_mut(index)
113            .ok_or_else(|| DocumentError::PathNotFound {
114                path: path.to_string(),
115            })?;
116        replace_item_preserving(target, value)?;
117    } else if let Some(tables) = current.as_array_of_tables_mut() {
118        set_table_element(tables, last, value, path)?;
119    } else {
120        let table =
121            current
122                .as_table_like_mut()
123                .ok_or_else(|| DocumentError::UnsupportedOperation {
124                    format: "TOML".to_string(),
125                    operation: "set".to_string(),
126                    detail: "cannot address a key inside a non-table TOML value".to_string(),
127                })?;
128        match table.get_mut(last).filter(|item| !item.is_none()) {
129            Some(target) => replace_item_preserving(target, value)?,
130            // New leaf: append into the existing parent table.
131            None => {
132                table.insert(last, toml_item(value)?);
133                hand_closing_space_to_new_entry(current);
134            }
135        }
136    }
137    Ok(preserve_line_endings(content, document.to_string()))
138}
139
140/// After an entry was appended to `item`, move the space before `}` onto it.
141///
142/// In `{ y = 1 }` the space before `}` is the last value's suffix; left there
143/// it ends up before the new comma (`{ y = 1 , z = 2 }`). Hand it to the new
144/// last entry — a new leaf and a new table created on the way to one alike.
145/// Anything other than an inline table has no such space and is left alone.
146fn hand_closing_space_to_new_entry(item: &mut toml_edit::Item) {
147    let Some(inline) = item.as_inline_table_mut() else {
148        return;
149    };
150    let count = inline.len();
151    if count < 2 {
152        return;
153    }
154    let moved = inline.iter_mut().nth(count - 2).and_then(|(_, previous)| {
155        let suffix = previous.decor().suffix()?.as_str()?.to_string();
156        (!suffix.is_empty() && suffix.trim().is_empty()).then(|| {
157            previous.decor_mut().set_suffix("");
158            suffix
159        })
160    });
161    if let Some((_, added)) = inline.iter_mut().last() {
162        added.decor_mut().set_suffix(moved.unwrap_or_default());
163    }
164}
165
166/// Remove an existing TOML item through `toml_edit`, retaining document decor.
167pub(crate) fn unset_preserving(content: &str, path: &str) -> DocumentResult<String> {
168    keep_bom(content, |body| unset_body(body, path))
169}
170
171fn unset_body(content: &str, path: &str) -> DocumentResult<String> {
172    let segments = crate::document::parse_path(path)?;
173    let (last, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
174    let mut document =
175        content
176            .parse::<toml_edit::DocumentMut>()
177            .map_err(|error| DocumentError::ParseError {
178                format: "TOML".to_string(),
179                detail: error.to_string(),
180            })?;
181    // The same walk `set` makes: an array is entered by index, so the two
182    // verbs reach the same nodes.
183    let mut current = document.as_item_mut();
184    for (depth, parent) in parents.iter().enumerate() {
185        if let Some(table) = current.as_table_mut()
186            && table.get(parent).is_some_and(|item| {
187                item.as_array_of_tables()
188                    .is_some_and(|tables| tables.len() == 1)
189            })
190            && depth + 1 == parents.len()
191        {
192            table.set_implicit(false);
193            if let Some(mut key) = table.key_mut(parent) {
194                key.leaf_decor_mut().set_suffix(" ");
195            }
196        }
197        let next = if current.as_array().is_some() || current.is_array_of_tables() {
198            parent
199                .parse::<usize>()
200                .ok()
201                .and_then(|index| current.get_mut(index))
202        } else {
203            current.get_mut(parent)
204        };
205        current =
206            next.filter(|item| !item.is_none())
207                .ok_or_else(|| DocumentError::PathNotFound {
208                    path: path.to_string(),
209                })?;
210    }
211    if let Some(tables) = current.as_array_of_tables_mut() {
212        let index = last
213            .parse::<usize>()
214            .ok()
215            .filter(|index| *index < tables.len())
216            .ok_or_else(|| DocumentError::PathNotFound {
217                path: path.to_string(),
218            })?;
219        // toml_edit stores the document preamble on the first table's
220        // decor. Keep the part separated from that table by a blank line.
221        let preamble = document_preamble(
222            content,
223            tables.get(index).map(toml_edit::Table::decor),
224            removed_leads_document(content, &segments),
225        );
226        tables.remove(index);
227        if tables.is_empty() {
228            *current = toml_edit::Item::Value(toml_edit::Value::Array(toml_edit::Array::new()));
229        }
230        let rendered = format!("{preamble}{document}");
231        return Ok(preserve_line_endings(content, rendered));
232    }
233    if let Some(array) = current.as_array_mut() {
234        let index = last
235            .parse::<usize>()
236            .ok()
237            .filter(|index| *index < array.len())
238            .ok_or_else(|| DocumentError::PathNotFound {
239                path: path.to_string(),
240            })?;
241        let removed = array.remove(index);
242        remove_element_comment(array, index, &removed);
243        return Ok(preserve_line_endings(content, document.to_string()));
244    }
245    // `as_table_like_mut`, not `as_table_mut`: an inline table is a `Value`, not
246    // an `Item::Table`, and reading only the latter made `unset` refuse a key
247    // `set` had just written — `foo = { path = "..." }` could be edited but not
248    // emptied. The two verbs address the same nodes or neither is trustworthy.
249    let table = current
250        .as_table_like_mut()
251        .ok_or_else(|| DocumentError::UnsupportedOperation {
252            format: "TOML".to_string(),
253            operation: "unset".to_string(),
254            detail: "cannot address a key inside a non-table TOML value".to_string(),
255        })?;
256    let decor = table
257        .get(last)
258        .and_then(|item| {
259            item.as_table()
260                .or_else(|| item.as_array_of_tables()?.get(0))
261                .map(toml_edit::Table::decor)
262        })
263        .or_else(|| table.key(last).map(toml_edit::Key::leaf_decor));
264    let preamble = document_preamble(content, decor, removed_leads_document(content, &segments));
265    let Some(removed) = table.remove(last) else {
266        return Err(DocumentError::PathNotFound {
267            path: path.to_string(),
268        });
269    };
270    // An inline table's closing space lives in the trailing decor of its final
271    // value, so removing the last entry takes ` }` down to `}` — a change to
272    // source the caller did not address. Hand that suffix to the new final
273    // entry, unless it already carries one of its own.
274    let removed_suffix = removed
275        .as_value()
276        .and_then(|value| value.decor().suffix())
277        .cloned();
278    if let (Some(inline), Some(suffix)) = (current.as_inline_table_mut(), removed_suffix)
279        && let Some((_, final_value)) = inline.iter_mut().last()
280    {
281        let carries_its_own = final_value
282            .decor()
283            .suffix()
284            .and_then(|raw| raw.as_str())
285            .is_some_and(|text| !text.is_empty());
286        if !carries_its_own {
287            final_value.decor_mut().set_suffix(suffix);
288        }
289    }
290    // An implicit TOML parent disappears when its last child is removed.
291    // Emit an explicit header so the staged empty object survives reopening.
292    if let Some(table) = current.as_table_mut()
293        && table.is_empty()
294    {
295        table.set_implicit(false);
296        table.set_dotted(false);
297    }
298    Ok(preserve_line_endings(
299        content,
300        format!("{preamble}{document}"),
301    ))
302}
303
304/// Whether the item at `segments` is the first thing in the document. A
305/// span-carrying parse answers positionally: the item's decor prefix begins at
306/// byte 0 only for the document's first item. Comparing prefix text with the
307/// file's opening text cannot, since a later item may repeat that text.
308fn removed_leads_document(content: &str, segments: &[String]) -> bool {
309    let Ok(document) = toml_edit::Document::parse(content) else {
310        return false;
311    };
312    let Some((last, parents)) = segments.split_last() else {
313        return false;
314    };
315    let mut current = document.as_item();
316    for parent in parents {
317        let next = if current.as_array().is_some() || current.is_array_of_tables() {
318            parent
319                .parse::<usize>()
320                .ok()
321                .and_then(|index| current.get(index))
322        } else {
323            current.get(parent.as_str())
324        };
325        let Some(next) = next else {
326            return false;
327        };
328        current = next;
329    }
330    let prefix_start = |decor: &toml_edit::Decor| {
331        decor
332            .prefix()
333            .and_then(toml_edit::RawString::span)
334            .map(|span| span.start)
335    };
336    if let Some(tables) = current.as_array_of_tables() {
337        return last
338            .parse::<usize>()
339            .ok()
340            .and_then(|index| tables.get(index))
341            .and_then(|table| prefix_start(table.decor()))
342            == Some(0);
343    }
344    let Some(table) = current.as_table_like() else {
345        return false;
346    };
347    let start = table.get(last).and_then(|item| {
348        item.as_table()
349            .or_else(|| item.as_array_of_tables().and_then(|tables| tables.get(0)))
350            .and_then(|table| prefix_start(table.decor()))
351            .or_else(|| {
352                table
353                    .get_key_value(last)
354                    .and_then(|(key, _)| prefix_start(key.leaf_decor()))
355            })
356    });
357    start == Some(0)
358}
359
360fn document_preamble<'a>(
361    content: &'a str,
362    decor: Option<&toml_edit::Decor>,
363    leads_document: bool,
364) -> &'a str {
365    let Some(prefix) = decor
366        .and_then(toml_edit::Decor::prefix)
367        .and_then(toml_edit::RawString::as_str)
368        .filter(|_| leads_document)
369    else {
370        return "";
371    };
372    let mut end = 0;
373    let mut preamble_end = 0;
374    for line in prefix.split_inclusive('\n') {
375        end += line.len();
376        if line.ends_with('\n') && line.trim().is_empty() {
377            preamble_end = end;
378        }
379    }
380    let preamble = &content[..preamble_end];
381    if preamble.contains('#') { preamble } else { "" }
382}
383
384fn preserve_line_endings(content: &str, rendered: String) -> String {
385    if content.contains("\r\n")
386        && content.as_bytes().iter().enumerate().all(|(index, byte)| {
387            *byte != b'\n' || (index > 0 && content.as_bytes()[index - 1] == b'\r')
388        })
389    {
390        rendered.replace("\r\n", "\n").replace('\n', "\r\n")
391    } else {
392        rendered
393    }
394}
395
396fn toml_item(value: &Value) -> DocumentResult<toml_edit::Item> {
397    toml_value(value, None).map(toml_edit::Item::Value)
398}
399
400fn toml_value(
401    value: &Value,
402    existing: Option<&toml_edit::Value>,
403) -> DocumentResult<toml_edit::Value> {
404    let mut converted = match value {
405        Value::Null => Err(DocumentError::UnsupportedOperation {
406            format: "TOML".to_string(),
407            operation: "set".to_string(),
408            detail: "TOML has no null value".to_string(),
409        }),
410        Value::Bool(value) => Ok(toml_edit::Value::from(*value)),
411        Value::Integer(value) => Ok(toml_edit::Value::from(*value)),
412        Value::Unsigned(value) => i64::try_from(*value)
413            .map(toml_edit::Value::from)
414            .map_err(|_| DocumentError::UnsupportedOperation {
415                format: "TOML".to_string(),
416                operation: "set".to_string(),
417                detail: "unsigned integer exceeds TOML i64 range".to_string(),
418            }),
419        Value::Float(value) if value.is_finite() => Ok(toml_edit::Value::from(*value)),
420        Value::Float(_) => Err(DocumentError::UnsupportedOperation {
421            format: "TOML".to_string(),
422            operation: "set".to_string(),
423            detail: "non-finite TOML float is not representable".to_string(),
424        }),
425        // A `Value::Number` literal is float-shaped (has a `.`/`e`) or
426        // integer-shaped (does not); an integer-shaped one only exists
427        // because it overflows `u64`, which also overflows TOML's 64-bit
428        // integer grammar, so it can never be written. A float-shaped one
429        // parses to `f64` cleanly (it already passed JSON-number syntax
430        // validation) and writes like any other TOML float — TOML floats
431        // are canonically `f64` at the format level, so this is not a
432        // fidelity regression versus `Value::Float` above.
433        Value::Number(text) if value.is_float() => text
434            .parse::<f64>()
435            .ok()
436            .filter(|value| value.is_finite())
437            .map(toml_edit::Value::from)
438            .ok_or_else(|| DocumentError::UnsupportedOperation {
439                format: "TOML".to_string(),
440                operation: "set".to_string(),
441                detail: "float literal is not representable in TOML".to_string(),
442            }),
443        Value::Number(_) => Err(DocumentError::UnsupportedOperation {
444            format: "TOML".to_string(),
445            operation: "set".to_string(),
446            detail: "integer literal exceeds TOML's 64-bit integer range".to_string(),
447        }),
448        Value::String(value) => {
449            // Reads report a datetime as its text, so text written back
450            // over a datetime stays one when it still spells a datetime;
451            // otherwise a read-edit-write round trip turns it into a string.
452            let existing_datetime = existing.filter(|item| item.is_datetime());
453            if let Some(existing) = existing_datetime.filter(|item| {
454                item.as_datetime()
455                    .is_some_and(|datetime| datetime.to_string() == *value)
456            }) {
457                Ok(existing.clone())
458            } else if let Some(datetime) =
459                existing_datetime.and_then(|_| value.parse::<toml_edit::Datetime>().ok())
460            {
461                Ok(toml_edit::Value::from(datetime))
462            } else if value.contains('\n') {
463                single_line_string(value)
464            } else {
465                Ok(toml_edit::Value::from(value.clone()))
466            }
467        }
468        Value::Array(values) => array_value(values, existing.and_then(toml_edit::Value::as_array)),
469        Value::Object(values) => {
470            inline_table_value(values, existing.and_then(toml_edit::Value::as_inline_table))
471        }
472    }?;
473    if let Some(existing) = existing {
474        *converted.decor_mut() = existing.decor().clone();
475    }
476    Ok(converted)
477}
478
479/// A string holding a newline, written as a one-line basic string.
480///
481/// The default rendering is a `\"\"\"` multiline literal, which puts the value's
482/// own newlines into the source as raw line breaks. [`preserve_line_endings`]
483/// cannot tell those from the document's line endings, so on a CRLF file it
484/// would rewrite the value's `\n` to `\r\n` — a successful `set` that stores
485/// something other than what it was given. Escaped, the value carries no raw
486/// line break for a line-ending pass to touch.
487fn single_line_string(value: &str) -> DocumentResult<toml_edit::Value> {
488    use std::fmt::Write as _;
489    let mut literal = String::with_capacity(value.len() + 2);
490    literal.push('"');
491    for character in value.chars() {
492        match character {
493            '\\' => literal.push_str("\\\\"),
494            '"' => literal.push_str("\\\""),
495            '\n' => literal.push_str("\\n"),
496            '\r' => literal.push_str("\\r"),
497            '\t' => literal.push_str("\\t"),
498            control if control.is_control() => {
499                let _ = write!(literal, "\\u{:04X}", u32::from(control));
500            }
501            other => literal.push(other),
502        }
503    }
504    literal.push('"');
505    let mut parsed = literal.parse::<toml_edit::Value>().map_err(|error| {
506        DocumentError::UnsupportedOperation {
507            format: "TOML".to_string(),
508            operation: "set".to_string(),
509            detail: format!("string is not representable in TOML: {error}"),
510        }
511    })?;
512    // A parsed value carries explicit empty decor; clear it so the surrounding
513    // table or array applies its own spacing as it does for any new value.
514    parsed.decor_mut().clear();
515    Ok(parsed)
516}
517
518/// Keep a decor's layout (newlines and indentation) and drop its comments.
519///
520/// An element's prefix decor holds whatever followed the previous element's
521/// comma, which in a multiline array is that element's trailing comment. Copying
522/// it verbatim onto an appended element would reproduce a comment beside a value
523/// the author never wrote it for — inventing content in the one module whose
524/// promise is that it preserves the author's bytes. The indentation is safe to
525/// reuse; the prose is not.
526fn layout_without_comments(decor: &str) -> String {
527    let mut kept = String::with_capacity(decor.len());
528    let mut rest = decor;
529    while let Some(hash) = rest.find('#') {
530        // Also drop the spaces that separated the comment from the value, or
531        // removing it leaves a ragged trailing run behind.
532        kept.push_str(rest[..hash].trim_end_matches([' ', '\t']));
533        match rest[hash..].find('\n') {
534            // Drop the comment body, keep the newline that ends it.
535            Some(newline) => rest = &rest[hash + newline..],
536            // A trailing comment with no newline ends the decor.
537            None => return kept,
538        }
539    }
540    kept.push_str(rest);
541    kept
542}
543
544/// Re-attach comments after `removed` left `array` at `index`.
545///
546/// An element's own comment is written after its comma, so it is stored in the
547/// *next* element's prefix, or in the array's trailing decor (the removed
548/// element's suffix, without a trailing comma) when it was the last one. Left
549/// alone, removal deletes the comment of the element before it and hands the
550/// removed element's comment to that neighbour. The first line of each decor
551/// is the comment beside the previous value; later lines (own-line comments,
552/// indentation) belong to what follows and stay put.
553///
554/// The first element is the same rule with `[` as the "previous value": the
555/// first line of its prefix is the comment beside the bracket (`[ # header`),
556/// which stays, while its later lines are the removed element's own-line
557/// comments, which go with it.
558fn remove_element_comment(array: &mut toml_edit::Array, index: usize, removed: &toml_edit::Value) {
559    let decor_text = |raw: Option<&toml_edit::RawString>| {
560        raw.and_then(toml_edit::RawString::as_str)
561            .unwrap_or_default()
562            .to_string()
563    };
564    let removed_prefix = decor_text(removed.decor().prefix());
565    if index == 0
566        && let Some(first) = array.get_mut(0)
567    {
568        let prefix = decor_text(first.decor().prefix());
569        let beside_bracket = removed_prefix.split('\n').next().unwrap_or_default();
570        let layout = if prefix.contains('\n') {
571            // The new first element keeps its own lines — the own-line
572            // comments above it — and drops its first line, which was the
573            // removed element's comment.
574            format!("{beside_bracket}{}", after_first_line(&prefix))
575        } else if removed_prefix.contains('\n') {
576            // `[\n  1, 2\n]`: the new first element sat on the removed one's
577            // line, so it takes the line break and indentation it had.
578            let indentation = &removed_prefix[removed_prefix.rfind('\n').unwrap_or_default()..];
579            format!("{beside_bracket}{indentation}")
580        } else {
581            // One line (`[ 1, 2 ]`): the space after `[` is the array's
582            // layout, so it stays at the front.
583            removed_prefix
584        };
585        first.decor_mut().set_prefix(layout);
586        return;
587    }
588    // The comment beside the element (or, for the first one, the bracket)
589    // before the removed one, which the removed element's prefix held.
590    let carried = comment_line(&removed_prefix);
591    if let Some(next) = array.get_mut(index) {
592        let prefix = decor_text(next.decor().prefix());
593        let rest = after_first_line(&prefix);
594        match (carried, comment_line(&prefix)) {
595            (Some(comment), _) => next.decor_mut().set_prefix(format!("{comment}{rest}")),
596            (None, Some(_)) => next.decor_mut().set_prefix(rest.to_string()),
597            (None, None) => {}
598        }
599        return;
600    }
601    let tail = format!(
602        "{}{}",
603        decor_text(removed.decor().suffix()),
604        array.trailing().as_str().unwrap_or_default()
605    );
606    let rest = after_first_line(&tail);
607    let trailing = match (carried, comment_line(&tail)) {
608        // A comment must end its line before the closing bracket.
609        (Some(comment), _) if rest.is_empty() => format!("{comment}\n"),
610        (Some(comment), _) => format!("{comment}{rest}"),
611        (None, Some(_)) => rest.to_string(),
612        (None, None) => tail.clone(),
613    };
614    array.set_trailing(trailing);
615}
616
617/// A decor's first line when it carries a comment — the comment written
618/// beside the preceding value — including the spaces before it.
619fn comment_line(decor: &str) -> Option<&str> {
620    let line = decor.split('\n').next().unwrap_or_default();
621    line.contains('#').then_some(line)
622}
623
624/// Everything from a decor's first line break on.
625fn after_first_line(decor: &str) -> &str {
626    decor.find('\n').map_or("", |newline| &decor[newline..])
627}
628
629/// The first comment in a decor string, without its leading whitespace.
630fn first_comment(decor: &str) -> Option<&str> {
631    let start = decor.find('#')?;
632    let end = decor[start..]
633        .find('\n')
634        .map_or(decor.len(), |newline| start + newline);
635    Some(&decor[start..end])
636}
637
638/// Rewrite a decor's first comment, or remove it when `replacement` is `None`.
639fn with_first_comment(decor: &str, replacement: Option<&str>) -> String {
640    let Some(start) = decor.find('#') else {
641        return decor.to_string();
642    };
643    let end = decor[start..]
644        .find('\n')
645        .map_or(decor.len(), |newline| start + newline);
646    let mut out = String::with_capacity(decor.len());
647    match replacement {
648        Some(comment) => {
649            out.push_str(&decor[..start]);
650            out.push_str(comment);
651        }
652        None => out.push_str(decor[..start].trim_end_matches([' ', '\t'])),
653    }
654    out.push_str(&decor[end..]);
655    out
656}
657
658fn array_value(
659    values: &[Value],
660    existing: Option<&toml_edit::Array>,
661) -> DocumentResult<toml_edit::Value> {
662    array_value_with_prefix(values, existing, 0)
663}
664
665/// `unchanged` leading elements are kept verbatim for an append operation.
666fn array_value_with_prefix(
667    values: &[Value],
668    existing: Option<&toml_edit::Array>,
669    unchanged: usize,
670) -> DocumentResult<toml_edit::Value> {
671    let existing_values = existing
672        .map(|array| array.iter().cloned().collect::<Vec<_>>())
673        .unwrap_or_default();
674    let mut array = existing.cloned().unwrap_or_default();
675    if array.len() > values.len() {
676        // The comment written after element N-1's comma is stored in element
677        // N's *prefix*, and the last element's trailing comment lives in the
678        // array's trailing decor. Truncating therefore deletes the comment that
679        // documented the last surviving element while keeping the one that
680        // documented a value being removed — leaving a comment attached to the
681        // wrong element. Carry the surviving element's own comment across.
682        let surviving_comment = existing_values
683            .get(values.len())
684            .and_then(|item| item.decor().prefix())
685            .and_then(toml_edit::RawString::as_str)
686            .and_then(first_comment)
687            .map(str::to_string);
688        while array.len() > values.len() {
689            let last = array.len() - 1;
690            array.remove(last);
691        }
692        let trailing = array.trailing().as_str().unwrap_or_default().to_string();
693        if first_comment(&trailing).is_some() {
694            array.set_trailing(with_first_comment(&trailing, surviving_comment.as_deref()));
695        }
696    }
697    let length_before_append = array.len();
698    // Without a trailing comma, the comment and line break after the last
699    // element are that element's suffix rather than the array's trailing
700    // decor, so the new comma would land after them (`"y" # c\n,`). Moving
701    // them to the trailing decor lets the branch below treat both spellings
702    // alike.
703    if values.len() > length_before_append
704        && let Some(last) = length_before_append
705            .checked_sub(1)
706            .and_then(|index| array.get_mut(index))
707    {
708        let suffix = last
709            .decor()
710            .suffix()
711            .and_then(toml_edit::RawString::as_str)
712            .unwrap_or_default()
713            .to_string();
714        if suffix.contains(['#', '\n']) {
715            last.decor_mut().set_suffix("");
716            let trailing = array.trailing().as_str().unwrap_or_default().to_string();
717            array.set_trailing(format!("{suffix}{trailing}"));
718        }
719    }
720    for (index, value) in values.iter().enumerate() {
721        if index < unchanged {
722            continue;
723        }
724        let hint = existing_values.get(index);
725        let mut converted = toml_value(value, hint)?;
726        if index < array.len() {
727            array.replace_formatted(index, converted);
728        } else {
729            let layout = existing_values
730                .last()
731                .and_then(|item| item.decor().prefix())
732                .and_then(toml_edit::RawString::as_str)
733                .map(layout_without_comments)
734                .unwrap_or_default();
735            // The first element of `[1]` has no prefix to copy, but a second
736            // one still needs the space after its comma.
737            let layout = if layout.is_empty() && index > 0 {
738                " ".to_string()
739            } else {
740                layout
741            };
742            converted.decor_mut().set_prefix(layout);
743            if index == length_before_append {
744                // A last element's inline comment is held in the array's
745                // trailing decor. Keep it beside that element when extending.
746                let trailing = array.trailing().as_str().unwrap_or_default().to_string();
747                if first_comment(&trailing).is_some() {
748                    let layout = converted
749                        .decor()
750                        .prefix()
751                        .and_then(toml_edit::RawString::as_str)
752                        .unwrap_or_default();
753                    let indent = layout.rsplit('\n').next().unwrap_or_default().to_string();
754                    converted.decor_mut().set_prefix(format!(
755                        "{}{indent}",
756                        trailing.trim_end_matches([' ', '\t'])
757                    ));
758                    // Everything up to the last line break moved in front of
759                    // the new element; only the bracket's own indentation stays.
760                    let bracket_indent = trailing.rsplit('\n').next().unwrap_or_default();
761                    array.set_trailing(format!("\n{bracket_indent}"));
762                }
763            }
764            array.push_formatted(converted);
765        }
766    }
767    // Appending to a single-line array: the previously-last element's suffix is
768    // the space that sat before `]`. Left where it is, it ends up before the new
769    // comma (`[ "one" , "two"]`), so move it to the array's trailing decor where
770    // it goes on separating the last value from the bracket. Done after the
771    // element loop, which restores each replaced element's original decor.
772    if values.len() > length_before_append
773        && let Some(last_index) = length_before_append.checked_sub(1)
774    {
775        let suffix = array
776            .get(last_index)
777            .and_then(|item| item.decor().suffix())
778            .and_then(toml_edit::RawString::as_str)
779            .filter(|suffix| !suffix.is_empty() && suffix.chars().all(|c| c == ' ' || c == '\t'))
780            .map(str::to_string);
781        let trailing_is_empty = array.trailing().as_str().is_none_or(str::is_empty);
782        if let Some(suffix) = suffix
783            && trailing_is_empty
784        {
785            if let Some(item) = array.get_mut(last_index) {
786                item.decor_mut().set_suffix("");
787            }
788            array.set_trailing(suffix);
789        }
790    }
791    if values.is_empty() {
792        array.set_trailing_comma(false);
793    }
794    if existing.is_none() {
795        array.fmt();
796    }
797    Ok(toml_edit::Value::Array(array))
798}
799
800fn inline_table_value(
801    values: &std::collections::BTreeMap<String, Value>,
802    existing: Option<&toml_edit::InlineTable>,
803) -> DocumentResult<toml_edit::Value> {
804    let mut table = existing.cloned().unwrap_or_default();
805    table.retain(|key, _| values.contains_key(key));
806    for (key, value) in values {
807        if let Some(current) = table.get_mut(key) {
808            *current = toml_value(value, Some(current))?;
809        } else {
810            table.insert(key, toml_value(value, None)?);
811        }
812    }
813    if values.is_empty() {
814        table.set_trailing_comma(false);
815    }
816    if existing.is_none() {
817        table.fmt();
818    }
819    Ok(toml_edit::Value::InlineTable(table))
820}
821
822fn replace_item_preserving(target: &mut toml_edit::Item, value: &Value) -> DocumentResult<()> {
823    if target.is_array_of_tables() {
824        return Err(DocumentError::UnsupportedOperation {
825            format: "TOML".to_string(),
826            operation: "set".to_string(),
827            detail:
828                "an array of tables cannot be replaced as a whole; set, add, or unset its elements"
829                    .to_string(),
830        });
831    }
832    if let (Some(table), Value::Object(values)) = (target.as_table_mut(), value) {
833        return sync_table(table, values);
834    }
835    let converted = toml_value(value, target.as_value())?;
836    *target = toml_edit::Item::Value(converted);
837    Ok(())
838}
839
840fn sync_table(
841    table: &mut toml_edit::Table,
842    values: &std::collections::BTreeMap<String, Value>,
843) -> DocumentResult<()> {
844    table.retain(|key, _| values.contains_key(key));
845    for (key, value) in values {
846        if let Some(current) = table.get_mut(key) {
847            replace_item_preserving(current, value)?;
848        } else {
849            table.insert(key, toml_item(value)?);
850        }
851    }
852    Ok(())
853}
854
855/// Append `item` to the array at `key`: an inline array, or an array of tables.
856pub(crate) fn append_array_item_preserving(
857    content: &str,
858    key: &str,
859    item: &Value,
860) -> DocumentResult<String> {
861    if key.is_empty() {
862        return Err(collection_refusal(
863            "add",
864            "a TOML document root is a table, so it has no array to append to",
865        ));
866    }
867    keep_bom(content, |body| {
868        let loaded = load(body)?;
869        let target =
870            crate::document::get_path_ref(&loaded, key, crate::document::Addressing::INDEX_ONLY)?;
871        if !matches!(target, Value::Array(_)) {
872            return Err(collection_refusal("add", "target is not an array"));
873        }
874        set_body(body, &format!("{key}.-"), item).map_err(|error| match error {
875            DocumentError::UnsupportedOperation { detail, .. } => {
876                collection_refusal("add", &detail)
877            }
878            other => other,
879        })
880    })
881}
882
883/// Remove the element at `index` from the array at `key`: an inline array, or
884/// an array of tables.
885pub(crate) fn remove_array_item_preserving(
886    content: &str,
887    key: &str,
888    index: usize,
889) -> DocumentResult<String> {
890    if key.is_empty() {
891        return Err(collection_refusal(
892            "remove",
893            "a TOML document root is a table, so it has no array to remove from",
894        ));
895    }
896    keep_bom(content, |body| unset_body(body, &format!("{key}.{index}")))
897}
898
899/// Edit one element of an array of tables: `-` appends a table, an index
900/// replaces the table there. An element of this kind is a table, so only an
901/// object can be written to it.
902fn set_table_element(
903    tables: &mut toml_edit::ArrayOfTables,
904    last: &str,
905    value: &Value,
906    path: &str,
907) -> DocumentResult<()> {
908    let Value::Object(fields) = value else {
909        return Err(collection_refusal(
910            "set",
911            "an element of an array of tables is a table; write an object",
912        ));
913    };
914    if last == "-" {
915        let mut table = toml_edit::Table::new();
916        sync_table(&mut table, fields)?;
917        tables.push(table);
918        return Ok(());
919    }
920    let index = last
921        .parse::<usize>()
922        .map_err(|_| DocumentError::UnregisteredArray {
923            path: path.to_string(),
924        })?;
925    let table = tables
926        .get_mut(index)
927        .ok_or_else(|| DocumentError::PathNotFound {
928            path: path.to_string(),
929        })?;
930    sync_table(table, fields)
931}
932
933fn collection_refusal(operation: &str, detail: &str) -> DocumentError {
934    DocumentError::UnsupportedOperation {
935        format: "TOML".to_string(),
936        operation: operation.to_string(),
937        detail: detail.to_string(),
938    }
939}
940
941pub fn load(content: &str) -> DocumentResult<Value> {
942    toml::from_str::<toml::Value>(content)
943        .map(value_to_our_value)
944        .map_err(|e| DocumentError::ParseError {
945            format: "TOML".to_string(),
946            detail: e.to_string(),
947        })
948}
949
950pub fn save(value: &Value) -> DocumentResult<String> {
951    let toml_val = our_value_to_toml_value(value)?;
952    toml::to_string_pretty(&toml_val).map_err(|e| DocumentError::ParseError {
953        format: "TOML".to_string(),
954        detail: e.to_string(),
955    })
956}
957
958fn value_to_our_value(v: toml::Value) -> Value {
959    match v {
960        toml::Value::Boolean(b) => Value::Bool(b),
961        toml::Value::Integer(i) => Value::Integer(i),
962        toml::Value::Float(f) => Value::Float(f),
963        toml::Value::String(s) => Value::String(s),
964        toml::Value::Array(a) => Value::Array(a.into_iter().map(value_to_our_value).collect()),
965        toml::Value::Table(t) => {
966            let map = t
967                .into_iter()
968                .map(|(k, v)| (k, value_to_our_value(v)))
969                .collect();
970            Value::Object(map)
971        }
972        toml::Value::Datetime(dt) => Value::String(dt.to_string()),
973    }
974}
975
976fn our_value_to_toml_value(v: &Value) -> DocumentResult<toml::Value> {
977    match v {
978        Value::Null => Err(DocumentError::UnsupportedOperation {
979            format: "TOML".to_string(),
980            operation: "save".to_string(),
981            detail: "TOML has no null value".to_string(),
982        }),
983        Value::Bool(b) => Ok(toml::Value::Boolean(*b)),
984        Value::Integer(i) => Ok(toml::Value::Integer(*i)),
985        Value::Unsigned(i) => i64::try_from(*i).map(toml::Value::Integer).map_err(|_| {
986            DocumentError::UnsupportedOperation {
987                format: "TOML".to_string(),
988                operation: "save".to_string(),
989                detail: "unsigned integer exceeds TOML i64 range".to_string(),
990            }
991        }),
992        Value::Float(f) => Ok(toml::Value::Float(*f)),
993        Value::Number(text) if v.is_float() => text
994            .parse::<f64>()
995            .ok()
996            .filter(|value| value.is_finite())
997            .map(toml::Value::Float)
998            .ok_or_else(|| DocumentError::UnsupportedOperation {
999                format: "TOML".to_string(),
1000                operation: "save".to_string(),
1001                detail: "float literal is not representable in TOML".to_string(),
1002            }),
1003        Value::Number(_) => Err(DocumentError::UnsupportedOperation {
1004            format: "TOML".to_string(),
1005            operation: "save".to_string(),
1006            detail: "integer literal exceeds TOML's 64-bit integer range".to_string(),
1007        }),
1008        Value::String(s) => Ok(toml::Value::String(s.clone())),
1009        Value::Array(a) => {
1010            let arr = a
1011                .iter()
1012                .map(our_value_to_toml_value)
1013                .collect::<DocumentResult<Vec<_>>>()?;
1014            Ok(toml::Value::Array(arr))
1015        }
1016        Value::Object(o) => {
1017            let mut table = toml::map::Map::new();
1018            for (k, v) in o {
1019                table.insert(k.clone(), our_value_to_toml_value(v)?);
1020            }
1021            Ok(toml::Value::Table(table))
1022        }
1023    }
1024}