Does <llvm/Support/Json.h> support parsing comments? Why not?

I wrote a small program to parse a json file with comment:

#include <llvm/Support/JSON.h>
#include <llvm/Support/MemoryBuffer.h>

int
main(int argc, char* argv[])
{
  auto path = argv[1];
  auto fOrErr = llvm::MemoryBuffer::getFile(path);
  auto f = std::move(fOrErr.get());
  auto jval = llvm::json::parse(f->getBuffer());
  if (!jval) {
    llvm::errs() << jval.takeError();
    return 1;
  }
  llvm::outs() << *jval << '\n';
}

Here’s my JSON file:

{
  // 123
  "dadaf": 123
}

And it fails to parse:

[2:3, byte=5]: Expected object key

I thought <llvm/Support/Json.h> may not support handling comments, but it suprised me that llvm::json::OStream has a void comment(llvm::StringRef); method to emit comments. To me, it seems weird that <llvm/Support/Json.h> can dump comments but cannot parse them back.

Am I wrong? If not, why doesn’t <llvm/Support/Json.h> support parsing comments? Does LLVM support any other data formats in substitution of JSON comments?

Comments are not part of the JSON specification, so that’s probably why. Any JSON parser that supports comments is a non-standard extension.

From your observation though, as they seem to be intended, maybe adding it upstream would be accepted.

1 Like