JsonWriter.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #ifndef TOOLS_BLINK_GC_PLUGIN_JSON_WRITER_H_
  5. #define TOOLS_BLINK_GC_PLUGIN_JSON_WRITER_H_
  6. #include "llvm/Support/raw_ostream.h"
  7. // Helper to write information for the points-to graph.
  8. class JsonWriter {
  9. public:
  10. static JsonWriter* from(std::unique_ptr<llvm::raw_ostream> os) {
  11. return os ? new JsonWriter(std::move(os)) : 0;
  12. }
  13. void OpenList() {
  14. Separator();
  15. *os_ << "[";
  16. state_.push(false);
  17. }
  18. void OpenList(const std::string& key) {
  19. Write(key);
  20. *os_ << ":";
  21. OpenList();
  22. }
  23. void CloseList() {
  24. *os_ << "]";
  25. state_.pop();
  26. }
  27. void OpenObject() {
  28. Separator();
  29. *os_ << "{";
  30. state_.push(false);
  31. }
  32. void CloseObject() {
  33. *os_ << "}\n";
  34. state_.pop();
  35. }
  36. void Write(const size_t val) {
  37. Separator();
  38. *os_ << val;
  39. }
  40. void Write(const std::string& val) {
  41. Separator();
  42. *os_ << "\"" << val << "\"";
  43. }
  44. void Write(const std::string& key, const size_t val) {
  45. Separator();
  46. *os_ << "\"" << key << "\":" << val;
  47. }
  48. void Write(const std::string& key, const std::string& val) {
  49. Separator();
  50. *os_ << "\"" << key << "\":\"" << val << "\"";
  51. }
  52. private:
  53. JsonWriter(std::unique_ptr<llvm::raw_ostream> os) : os_(std::move(os)) {}
  54. void Separator() {
  55. if (state_.empty())
  56. return;
  57. if (state_.top()) {
  58. *os_ << ",";
  59. return;
  60. }
  61. state_.top() = true;
  62. }
  63. std::unique_ptr<llvm::raw_ostream> os_;
  64. std::stack<bool> state_;
  65. };
  66. #endif // TOOLS_BLINK_GC_PLUGIN_JSON_WRITER_H_