[llvm] [Support] ScopedPrinter: support pretty-printing JSON (PR #214806)

James Henderson via llvm-commits llvm-commits at lists.llvm.org
Mon Aug 17 01:54:23 PDT 2026


================
@@ -399,6 +399,15 @@ class LLVM_ABI ScopedPrinter {
     printString(Label, to_string(Value));
   }
 
+  virtual void printObject(StringRef Label, const json::Value &Value) {
+    std::string PrettyValue;
+    raw_string_ostream PrettyStream(PrettyValue);
+    json::OStream(PrettyStream, 2, getIndentLevel()).value(Value);
+    startLine() << Label << ": "
+                << PrettyValue.substr(PrettyValue.find_first_not_of(" "))
+                << "\n";
----------------
jh7370 wrote:

Ah, I didn't realise that `json::Value` is an arbitrary JSON type. Isn't the value you're passing in from #214375 always a JSON object, per the spec? As such, you should be able to know that it's an `Object` at this point without needing to do any particular decoding of the passed-in type (and it would be reasonable to warn if it isn't and do something else like print it as a raw string). Indeed, this function is `printObject`, not `printValue`, so I'd argue that passing in anything other than an `Object` type would be incorrect.

That being said, I've been staring at the `json` and `ScopedPrinter` interfaces and I think the correct thing to do is actually to have a `printJSONValue` method instead, which takes a `json::Value` then switches on the underlying type and calls the appropriate `ScopedPrinter` function(s). For `Object` and `Array` types, it would call the appropriate sequence of `*Begin`/`print*`/`*End` methods. I wouldn't be entirely surprised if there is already an example of iterating over an arbitrary json Value and doing something on each different type already in tree.

https://github.com/llvm/llvm-project/pull/214806


More information about the llvm-commits mailing list