Page MenuHomePhabricator

[json] Provide a means to delegate writing a value to another API
Needs ReviewPublic

Authored by dsanders on Sep 4 2020, 3:22 PM.
This revision needs review, but all reviewers have resigned.



I recently had need to call out to an external API to emit a JSON object as part
of one an LLVM tool was emitting. However, our JSON support didn't provide a way
to delegate part of the JSON output to that API.

Add rawValueBegin() and rawValueEnd() to maintain and check the internal state
while something else is writing to the stream. It's the users responsibility to
ensure that the resulting JSON output is still valid.

Diff Detail

Event Timeline

dsanders created this revision.Sep 4 2020, 3:22 PM
Herald added a project: Restricted Project. · View Herald TranscriptSep 4 2020, 3:22 PM
Herald added a subscriber: hiraditya. · View Herald Transcript
dsanders requested review of this revision.Sep 4 2020, 3:22 PM

This is really nice. There's an argument for parsing and emitting (validation and formatting) but obviously also a performance tradeoff so the feature makes sense.

Just some style nits (mostly local consistency) and a small API tweak again for consistency.


can we have a rawValue(function_ref<void(raw_ostream&)>)?

The "low-level" ideas of raw-output and no-lexical-nesting are independent.

Providing the ostream as a parameter makes the usable lifetime clear.


Consistently with the others, we should doc this among the high level functions, and leave the low-level ones undocumented.


"something external" is a bit vague.

Maybe "Write an externally-serialized value. The caller must write exactly one valid JSON value to the provided stream. No validation or formatting is performed on the output."


This can return raw_ostream&, to relieve the caller of needing to hold a reference, and to hide the implementation detail that we don't internally wrap the original ostream.


nit: this should match the name of the feature elsewhere, as they directly correspond. RawValue?
nit: comment needs to mention that it's a single value
nit: line comment as above.

Maybe "// External code is writing a single value to OS directly"?


nit: move after attributeBegin/End to match decls?


nit: drop assertion message for consistency with other End functions

I like this feature, and we have a use case for it too (inside the error-printer in JSON.cpp itself).

Do you want to do another pass on it, and add some tests? If not, I'm happy to do this myself

D88902 is a stab at addressing the comments here, adding a test, and using this to implement printErrorContext().

sammccall resigned from this revision.Mon, Oct 12, 8:45 AM