From 3055e1ec7a8e17568629a024bc2203ad9d98f3b0 Mon Sep 17 00:00:00 2001 From: Dion Dokter Date: Wed, 3 Sep 2025 20:05:10 +0200 Subject: [PATCH] Assign document leading format to the first node instead --- src/document.rs | 6 +++++- src/v2_parser.rs | 14 ++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/document.rs b/src/document.rs index 329a32b..48aba18 100644 --- a/src/document.rs +++ b/src/document.rs @@ -671,10 +671,14 @@ final;"; ); assert_eq!( doc.format().map(|f| &f.leading[..]), - Some("\n// This is the first node\n") + Some("") ); let foo = doc.get("foo").expect("expected a foo node"); + assert_eq!( + foo.format().map(|f| &f.leading[..]), + Some("\n// This is the first node\n") + ); assert_eq!(foo.format().map(|f| &f.terminator[..]), Some("\n")); assert_eq!(&foo[2], &"three".into()); assert_eq!(&foo["bar"], &"baz".into()); diff --git a/src/v2_parser.rs b/src/v2_parser.rs index 9d6080b..673e91c 100644 --- a/src/v2_parser.rs +++ b/src/v2_parser.rs @@ -282,12 +282,12 @@ pub(crate) fn document(input: &mut Input<'_>) -> PResult { /// `nodes := (line-space* node)* line-space*` fn nodes(input: &mut Input<'_>) -> PResult { - let leading = repeat(0.., alt((line_space.void(), (slashdash, base_node).void()))) + let mut leading = repeat(0.., alt((line_space.void(), (slashdash, base_node).void()))) .map(|()| ()) .take() .parse_next(input)?; let _start = input.checkpoint(); - let ns: Vec = separated( + let mut ns: Vec = separated( 0.., node, alt((node_terminator.void(), (eof.void(), any.void()).void())), @@ -299,6 +299,16 @@ fn nodes(input: &mut Input<'_>) -> PResult { .map(|()| ()) .take() .parse_next(input)?; + + // If there is a node, let it have the leading format + // This gives more consistent behavior + if let Some(first_node) = ns.get_mut(0) { + if let Some(first_node_format) = first_node.format_mut() { + first_node_format.leading = leading.into(); + leading = ""; + } + } + Ok(KdlDocument { nodes: ns, format: Some(KdlDocumentFormat {