1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef TOOLS_BLINK_GC_PLUGIN_JSON_WRITER_H_ 6 #define TOOLS_BLINK_GC_PLUGIN_JSON_WRITER_H_ 7 8 #include "llvm/Support/raw_ostream.h" 9 10 // Helper to write information for the points-to graph. 11 class JsonWriter { 12 public: from(std::unique_ptr<llvm::raw_ostream> os)13 static JsonWriter* from(std::unique_ptr<llvm::raw_ostream> os) { 14 return os ? new JsonWriter(std::move(os)) : 0; 15 } OpenList()16 void OpenList() { 17 Separator(); 18 *os_ << "["; 19 state_.push(false); 20 } OpenList(const std::string & key)21 void OpenList(const std::string& key) { 22 Write(key); 23 *os_ << ":"; 24 OpenList(); 25 } CloseList()26 void CloseList() { 27 *os_ << "]"; 28 state_.pop(); 29 } OpenObject()30 void OpenObject() { 31 Separator(); 32 *os_ << "{"; 33 state_.push(false); 34 } CloseObject()35 void CloseObject() { 36 *os_ << "}\n"; 37 state_.pop(); 38 } Write(const size_t val)39 void Write(const size_t val) { 40 Separator(); 41 *os_ << val; 42 } Write(const std::string & val)43 void Write(const std::string& val) { 44 Separator(); 45 *os_ << "\"" << val << "\""; 46 } Write(const std::string & key,const size_t val)47 void Write(const std::string& key, const size_t val) { 48 Separator(); 49 *os_ << "\"" << key << "\":" << val; 50 } Write(const std::string & key,const std::string & val)51 void Write(const std::string& key, const std::string& val) { 52 Separator(); 53 *os_ << "\"" << key << "\":\"" << val << "\""; 54 } 55 private: JsonWriter(std::unique_ptr<llvm::raw_ostream> os)56 JsonWriter(std::unique_ptr<llvm::raw_ostream> os) : os_(std::move(os)) {} Separator()57 void Separator() { 58 if (state_.empty()) 59 return; 60 if (state_.top()) { 61 *os_ << ","; 62 return; 63 } 64 state_.top() = true; 65 } 66 std::unique_ptr<llvm::raw_ostream> os_; 67 std::stack<bool> state_; 68 }; 69 70 #endif // TOOLS_BLINK_GC_PLUGIN_JSON_WRITER_H_ 71