Ref-impl: Non-well-formed XML output - is this "legal"?

Consider this example:

<!-- watch this! --><foobar>
  Dolor sit amet
</foobar>

I’m not sure what the expected output here is according to the spec, but I certainly would expect to see well-formed XML.

However, the actual output is not well-formed:

<!-- watch this! -->
<foobar>
    <p>Dolor sit amet</foobar>
</p>

[ Edit: Same result with span substituted for foobar, but not with div: This could be related to the block/inline classification distinction when parsing HTML “blocks” vs “tags”. ]

[ This is quite possibly a rather trivial bug in the implementation, but I haven’t investigated yet. ]