yaml-cpp icon indicating copy to clipboard operation
yaml-cpp copied to clipboard

Preserving Tags in YAML::Load

Open joergbrech opened this issue 3 years ago • 5 comments

When I YAML::Load a node with a local tag, the tag type and tag contents are not preserved.

Minimal example

I am using the 0.7.0 conan package.

auto x = YAML::Node(42);

YAML::Emitter e;
e << YAML::LocalTag("x") << x;
std::string s = e.c_str();
auto y = YAML::Load(s);

std::cout << "before: " << s << std::endl;
std::cout << "tag:    " << y.Tag() << std::endl;
std::cout << "after:  " << YAML::Dump(y) << std::endl;

prints

before: !x 42
tag:    !x
after:  !<!x> 42

Expected:

before: !x 42
tag:    x
after:  !x 42

I suppose two things are going wrong here:

  1. The leading exclamation mark is added to the tag contents
  2. The tag type changes from _Tag::Type::PrimaryHandle to _Tag::Type::Verbatim

So I have two questions:

  1. Is this a bug or am I doing it wrong? I am not 100% sure I correctly understand the complicated yaml specs for tags...
  2. Is there any way to set the _Tag::Type for an existing node as a workaround?

joergbrech avatar Oct 07 '22 13:10 joergbrech

I would be happy to contribute, if you would point me in the right direction. :grin:

joergbrech avatar Oct 11 '22 09:10 joergbrech

@jbeder, just a short ping. Is this a bug? Can I contribute?

joergbrech avatar Nov 19 '22 00:11 joergbrech

I just had some help from Stackoverflow.

Playing around a bit I noticed that changing

https://github.com/jbeder/yaml-cpp/blob/1b50109f7bea60bd382d8ea7befce3d2bd67da5f/src/emitfromevents.cpp#L118-L123

to

void EmitFromEvents::EmitProps(const std::string& tag, anchor_t anchor) {
  if (!tag.empty() && tag != "?" && tag != "!"){
      if (tag[0] == Keys::Tag) {
        m_emitter << LocalTag(std::string(tag.begin()+1, tag.end()));
      } else {
        m_emitter << VerbatimTag(tag);
      }
  }
  if (anchor)
    m_emitter << Anchor(ToString(anchor));
}

will let both VerbatimTags and LocalTags without prefixes roundtrip. All unit tests still succeed. So my specific issue would be solved and I would be happy, but it still wouldn't roundtrip for LocalTag with a prefix and SecondaryTag.

joergbrech avatar Nov 21 '22 11:11 joergbrech

I know this is an old bug, but has there been any updates on this?

davidzchen avatar Jun 20 '24 08:06 davidzchen

I don't think so. As usual, open to PRs.

jbeder avatar Jun 20 '24 12:06 jbeder