Comment ownership¶
Removing a key raises a question the parse tree cannot answer: which nearby comments belonged to it?
Get it wrong in one direction and you destroy a section heading that described ten other keys. Get it wrong in the other and you leave comments describing things that no longer exist.
The problem¶
These two documents produce identical comment attachment in the AST:
server:
host: localhost
# ==== TLS SECTION ==== ← describes everything below
tls_cert: /etc/cert.pem
Both are "a comment block immediately above a key". The parser attaches them the same way. The only thing distinguishing them is the blank line, which lives in the source text, not the tree.
yamldoc therefore retains the source's blank-line positions and uses them to
decide ownership.
The rules¶
| Comment | Belongs to | On removal |
|---|---|---|
| Directly above the key, no blank line | the key | removed with it |
| Above the key, blank line above the comment | the section | survives, re-attached to the next key |
| On the key's own line (inline) | the key | removed with it |
| Below the last key in a block | the block | hoisted onto the preceding key |
| The following key's own comment | that key | untouched |
The trailing case¶
This one is the least obvious and the most damaging when wrong:
server:
host: localhost
port: 8080
# end of the server block — applies to the whole section
database:
host: db.internal
The parser attaches that comment to port, because port is the last entry of
the block. It describes the block, not port — so removing port naively
takes it with it.
yamldoc hoists it onto host instead, where it still reads correctly.
When it is genuinely ambiguous¶
Sometimes there is no right answer. A comment might describe the key below it and the section it opens.
Where ambiguity is unavoidable, yamldoc errs towards survival. Orphaning a
comment is untidy and immediately visible — you see it and delete it. Destroying
one loses work the author did, silently, and they may not notice for months.
That asymmetry decides the tie.