[PATCH] D87170: [json] Provide a means to delegate writing a value to another API

Daniel Sanders via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 4 15:22:25 PDT 2020


dsanders created this revision.
dsanders added a reviewer: sammccall.
Herald added a subscriber: hiraditya.
Herald added a project: LLVM.
dsanders requested review of this revision.

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.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87170

Files:
  llvm/include/llvm/Support/JSON.h
  llvm/lib/Support/JSON.cpp


Index: llvm/lib/Support/JSON.cpp
===================================================================
--- llvm/lib/Support/JSON.cpp
+++ llvm/lib/Support/JSON.cpp
@@ -636,6 +636,18 @@
   Stack.back().HasValue = true;
 }
 
+void llvm::json::OStream::rawValueBegin() {
+  valueBegin();
+  Stack.emplace_back();
+  Stack.back().Ctx = ExternalStreamWriter;
+}
+
+void llvm::json::OStream::rawValueEnd() {
+  assert(Stack.back().Ctx == ExternalStreamWriter &&
+         "Expected matching rawValueBegin");
+  Stack.pop_back();
+}
+
 void llvm::json::OStream::newline() {
   if (IndentSize) {
     OS.write('\n');
Index: llvm/include/llvm/Support/JSON.h
===================================================================
--- llvm/include/llvm/Support/JSON.h
+++ llvm/include/llvm/Support/JSON.h
@@ -818,7 +818,13 @@
   void attributeBegin(llvm::StringRef Key);
   void attributeEnd();
 
- private:
+  /// Inform the writer that something external is about to write a value to OS.
+  void rawValueBegin();
+  /// Inform the writer that something external has finished writing a value to
+  /// OS.
+  void rawValueEnd();
+
+private:
   void attributeImpl(llvm::StringRef Key, Block Contents) {
     attributeBegin(Key);
     Contents();
@@ -832,6 +838,8 @@
     Singleton, // Top level, or object attribute.
     Array,
     Object,
+    /// Something outside this object is writing to OS such as a 3rd-party API.
+    ExternalStreamWriter,
   };
   struct State {
     Context Ctx = Singleton;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D87170.290041.patch
Type: text/x-patch
Size: 1487 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20200904/444ad654/attachment.bin>


More information about the llvm-commits mailing list