martinohmann / hcl-rs

HCL parsing and encoding libraries for rust with serde support
Apache License 2.0
121 stars 14 forks source link

hcl-edit: hardcoded newline for Body #270

Closed denfren closed 1 year ago

denfren commented 1 year ago

hcl-edit roundtrip on Body:

For the first case I would expect there to be no newline in the result.

There seems to be a static newline here https://github.com/martinohmann/hcl-rs/blob/b92d3d49920683c83bf70008c8c6f832c0cf5481/crates/hcl-edit/src/encode/structure.rs#L12 and something is eating up a newline in the parser

martinohmann commented 1 year ago

Actually, the HCL spec says that attributes and blocks that are not newline-terminated are invalid: https://github.com/hashicorp/hcl/blob/main/hclsyntax/spec.md#structural-elements

So if anything, the parser should reject foo = "bar" because it is lacking the trailing newline. Let me see how the go implementation handles this.

martinohmann commented 1 year ago

The go parser allows the final attribute or block in the top-level body to be either terminated by a newline or EOF, so a body ending in foo = "bar" is valid. I need to think a bit more about how to handle the absence (or presence) of a trailing newline at the end of the top-level body. As noted in #271 it cannot be part of a structure's decor suffix, because it's actually mandatory, except at the document end.

denfren commented 1 year ago

Well, you beat me by a couple of minutes!

https://github.com/martinohmann/hcl-rs/compare/main...denfren:hcl-rs:body-trailing-newlines

I have not read your solution yet.

denfren commented 1 year ago

I have moved the one-line parts into Block. Block now checks if Body did not print its newline and just does it for it - so that a user of the API can safely prefer to omit the final newline (if possible). EDIT: Which is not required at all - not sure why I did that :)

Apart from that we're doing pretty much the same as far as I can see.

martinohmann commented 1 year ago

Yeah, this is indeed quite similar, except that the changes to Block are not really necessary since the absence or presence of the trailing newline is only a concern for the top-level body.

martinohmann commented 1 year ago

@denfren fix is released as 0.7.2