github.com/google/syzkaller@v0.0.0-20251211124644-a066d2bc4b02/tools/clang/json.h (about) 1 // Copyright 2024 syzkaller project authors. All rights reserved. 2 // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. 3 4 #ifndef SYZ_DECLEXTRACT_JSON_H 5 #define SYZ_DECLEXTRACT_JSON_H 6 7 #include <cassert> 8 #include <cstdio> 9 #include <memory> 10 #include <string> 11 #include <vector> 12 13 class JSONPrinter { 14 public: 15 JSONPrinter() : Top(*this) {} 16 17 template <typename T> void Field(const char* Name, const T& V, bool Last = false) { 18 printf("%s\"%s\": ", Indent(), Name); 19 print(*this, V); 20 printf("%s\n", Last ? "" : ","); 21 } 22 23 const char* Indent() const { 24 static std::string Indents; 25 while (Indents.size() < Nesting) 26 Indents.push_back('\t'); 27 return Indents.c_str() + Indents.size() - Nesting; 28 } 29 30 class Scope { 31 public: 32 Scope(JSONPrinter& Printer, bool Array = false) : Printer(Printer), Array(Array) { 33 printf("%c\n", "{["[Array]); 34 Printer.Nesting++; 35 assert(Printer.Nesting < 1000); 36 } 37 38 ~Scope() { 39 assert(Printer.Nesting > 0); 40 Printer.Nesting--; 41 printf("%s%c", Printer.Indent(), "}]"[Array]); 42 } 43 44 private: 45 JSONPrinter& Printer; 46 const bool Array; 47 }; 48 49 private: 50 friend class Scope; 51 size_t Nesting = 0; 52 Scope Top; 53 }; 54 55 inline void print(JSONPrinter& Printer, int V) { printf("%d", V); } 56 inline void print(JSONPrinter& Printer, unsigned V) { printf("%u", V); } 57 inline void print(JSONPrinter& Printer, int64_t V) { printf("%ld", V); } 58 inline void print(JSONPrinter& Printer, bool V) { printf("%s", V ? "true" : "false"); } 59 inline void print(JSONPrinter& Printer, const char* V) { printf("\"%s\"", V ? V : ""); } 60 inline void print(JSONPrinter& Printer, const std::string& V) { print(Printer, V.c_str()); } 61 62 template <typename E> void print(JSONPrinter& Printer, const std::unique_ptr<E>& V) { 63 if (!V) 64 printf("null"); 65 else 66 print(Printer, *V); 67 } 68 69 template <typename E> void print(JSONPrinter& Printer, const std::vector<E>& V) { 70 JSONPrinter::Scope Scope(Printer, true); 71 size_t i = 0; 72 for (const auto& Elem : V) { 73 printf("%s", Printer.Indent()); 74 print(Printer, Elem); 75 printf("%s\n", ++i == V.size() ? "" : ","); 76 } 77 } 78 79 #endif