[llvm] r336542 - [Support] Allow JSON serialization of Optional<T> for supported T.

Sam McCall via llvm-commits llvm-commits at lists.llvm.org
Mon Jul 9 05:26:09 PDT 2018


Author: sammccall
Date: Mon Jul  9 05:26:09 2018
New Revision: 336542

URL: http://llvm.org/viewvc/llvm-project?rev=336542&view=rev
Log:
[Support] Allow JSON serialization of Optional<T> for supported T.

This is ported from r333881 to JSON's new home.

Modified:
    llvm/trunk/include/llvm/Support/JSON.h
    llvm/trunk/unittests/Support/JSONTest.cpp

Modified: llvm/trunk/include/llvm/Support/JSON.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/JSON.h?rev=336542&r1=336541&r2=336542&view=diff
==============================================================================
--- llvm/trunk/include/llvm/Support/JSON.h (original)
+++ llvm/trunk/include/llvm/Support/JSON.h Mon Jul  9 05:26:09 2018
@@ -57,6 +57,7 @@ namespace json {
 class Array;
 class ObjectKey;
 class Value;
+template <typename T> Value toJSON(const llvm::Optional<T> &Opt);
 
 /// An Object is a JSON object, which maps strings to heterogenous JSON values.
 /// It simulates DenseMap<ObjectKey, Value>. ObjectKey is a maybe-owned string.
@@ -579,6 +580,11 @@ bool fromJSON(const Value &E, std::map<s
   return false;
 }
 
+// Allow serialization of Optional<T> for supported T.
+template <typename T> Value toJSON(const llvm::Optional<T> &Opt) {
+  return Opt ? Value(*Opt) : Value(nullptr);
+}
+
 /// Helper for mapping JSON objects onto protocol structs.
 ///
 /// Example:

Modified: llvm/trunk/unittests/Support/JSONTest.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/Support/JSONTest.cpp?rev=336542&r1=336541&r2=336542&view=diff
==============================================================================
--- llvm/trunk/unittests/Support/JSONTest.cpp (original)
+++ llvm/trunk/unittests/Support/JSONTest.cpp Mon Jul  9 05:26:09 2018
@@ -37,6 +37,8 @@ TEST(JSONTest, Constructors) {
   EXPECT_EQ(R"({"A":{"B":{}}})", s(Object{{"A", Object{{"B", Object{}}}}}));
   EXPECT_EQ(R"({"A":{"B":{"X":"Y"}}})",
             s(Object{{"A", Object{{"B", Object{{"X", "Y"}}}}}}));
+  EXPECT_EQ("null", s(llvm::Optional<double>()));
+  EXPECT_EQ("2.5", s(llvm::Optional<double>(2.5)));
 }
 
 TEST(JSONTest, StringOwnership) {




More information about the llvm-commits mailing list