diff --git a/decode.go b/decode.go index 82f60ddc..656c4caf 100644 --- a/decode.go +++ b/decode.go @@ -347,6 +347,14 @@ func (p *parser) mapping() *Node { n.EndColumn = p.event.end_mark.column + 1 } else if len(n.Content) > 0 { last := n.Content[len(n.Content)-1] + // An explicit key with no value gets a null the document never + // wrote, marked at the start of the line after the key. Ending + // there reaches past the key's own text, and past the whole input + // when the key is on the last line, so end with the text that is + // actually there. + if prev := len(n.Content) - 2; prev >= 0 && unwritten(last) && last.Line > n.Content[prev].EndLine { + last = n.Content[prev] + } n.EndLine, n.EndColumn = last.EndLine, last.EndColumn } else { n.EndLine = p.event.end_mark.line + 1 @@ -357,6 +365,13 @@ func (p *parser) mapping() *Node { return n } +// unwritten reports whether n stands for a value the document does not contain: +// a null the parser supplies for a missing value, spanning no text. +func unwritten(n *Node) bool { + return n.Kind == ScalarNode && n.Tag == nullTag && n.Value == "" && + n.Line == n.EndLine && n.Column == n.EndColumn +} + // ---------------------------------------------------------------------------- // Decoder, unmarshals a node into a provided value. diff --git a/end_position_test.go b/end_position_test.go index dd3a1a6e..d7d9386d 100644 --- a/end_position_test.go +++ b/end_position_test.go @@ -440,3 +440,33 @@ tail: | c.Assert(root.EndLine, Equals, 6) c.Assert(root.EndColumn, Equals, 4) } + +// An explicit key with no value gets a null the parser supplies, marked at the +// start of the line after the key. A mapping that ended there would reach past +// its own text, and past the whole document when the key is on the last line. +func (s *S) TestNodeEndPositionExplicitKeyWithoutValue(c *C) { + // 1: a: + // 2: ? b + src := "a:\n? b" + + var doc yaml.Node + c.Assert(yaml.Unmarshal([]byte(src), &doc), IsNil) + + root := doc.Content[0] + c.Assert(root.Kind, Equals, yaml.MappingNode) + c.Assert(root.EndLine, Equals, 2) // the key `b` is the last text there is + c.Assert(root.EndColumn, Equals, 4) // just past `b` (col 3) + + // The supplied null still carries the mark it was given. + null := root.Content[3] + c.Assert(null.Tag, Equals, "!!null") + c.Assert(null.Line, Equals, 3) + + // A value that is only empty, rather than absent, is on the key's own line + // and keeps ending the entry. + var withEmpty yaml.Node + c.Assert(yaml.Unmarshal([]byte("a:\n"), &withEmpty), IsNil) + empty := withEmpty.Content[0] + c.Assert(empty.EndLine, Equals, 1) + c.Assert(empty.EndColumn, Equals, 3) +}