From 8502d2fe4c455ebd3ebfb982912389588b132a5f Mon Sep 17 00:00:00 2001 From: martinohmann Date: Thu, 24 Aug 2023 22:13:19 +0200 Subject: [PATCH] fix(parser): prevent panic in object item parser (#285) Fixes #284 --- crates/hcl-edit/src/parser/expr.rs | 8 ++++---- crates/hcl-edit/tests/regressions.rs | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/hcl-edit/src/parser/expr.rs b/crates/hcl-edit/src/parser/expr.rs index 93c35c2e..d2a34911 100644 --- a/crates/hcl-edit/src/parser/expr.rs +++ b/crates/hcl-edit/src/parser/expr.rs @@ -431,12 +431,12 @@ fn object_items<'i, 's>( // Associate the trailing comment with the item value, updating the span if it // already has a decor suffix. - let suffix_start = match decor.suffix() { - Some(suffix) => suffix.span().unwrap().start, - None => comment_span.start, + let suffix_span = match decor.suffix().and_then(RawString::span) { + Some(span) => span.start..comment_span.end, + None => comment_span, }; - decor.set_suffix(RawString::from_span(suffix_start..comment_span.end)); + decor.set_suffix(RawString::from_span(suffix_span)); line_ending .value(ObjectValueTerminator::Newline) diff --git a/crates/hcl-edit/tests/regressions.rs b/crates/hcl-edit/tests/regressions.rs index 5d26ce6f..0c82d2c3 100644 --- a/crates/hcl-edit/tests/regressions.rs +++ b/crates/hcl-edit/tests/regressions.rs @@ -57,3 +57,18 @@ fn issue_270() { body.set_prefer_omit_trailing_newline(true); assert_eq!(body.to_string(), no_trailing_newline); } + +#[test] +fn issue_284() { + let input = r#" + locals { + test = { + a = b// this comment breaks the parser + c = d // but this one doesn't + } + } + "#; + + let res: Result = input.parse(); + assert!(res.is_ok()); +}