LLDB mainline
StructuredData.cpp
Go to the documentation of this file.
1//===-- StructuredData.cpp ------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "lldb/Utility/Status.h"
12#include "llvm/Support/MemoryBuffer.h"
13#include <cerrno>
14#include <cinttypes>
15#include <cstdlib>
16
17using namespace lldb_private;
18using namespace llvm;
19
20static StructuredData::ObjectSP ParseJSONValue(json::Value &value);
21static StructuredData::ObjectSP ParseJSONObject(json::Object *object);
22static StructuredData::ObjectSP ParseJSONArray(json::Array *array);
23
25StructuredData::ParseJSON(const std::string &json_text) {
26 llvm::Expected<json::Value> value = json::parse(json_text);
27 if (!value) {
28 llvm::consumeError(value.takeError());
29 return nullptr;
30 }
31 return ParseJSONValue(*value);
32}
33
37
38 auto buffer_or_error = llvm::MemoryBuffer::getFile(input_spec.GetPath());
39 if (!buffer_or_error) {
40 error.SetErrorStringWithFormatv("could not open input file: {0} - {1}.",
41 input_spec.GetPath(),
42 buffer_or_error.getError().message());
43 return return_sp;
44 }
45 llvm::Expected<json::Value> value =
46 json::parse(buffer_or_error.get()->getBuffer().str());
47 if (value)
48 return ParseJSONValue(*value);
49 error.SetErrorString(toString(value.takeError()));
51}
52
54 return object_sp->GetType() == lldb::eStructuredDataTypeArray ||
55 object_sp->GetType() == lldb::eStructuredDataTypeDictionary;
56}
57
58static StructuredData::ObjectSP ParseJSONValue(json::Value &value) {
59 if (json::Object *O = value.getAsObject())
60 return ParseJSONObject(O);
61
62 if (json::Array *A = value.getAsArray())
63 return ParseJSONArray(A);
64
65 if (auto s = value.getAsString())
66 return std::make_shared<StructuredData::String>(*s);
67
68 if (auto b = value.getAsBoolean())
69 return std::make_shared<StructuredData::Boolean>(*b);
70
71 if (auto i = value.getAsInteger())
72 return std::make_shared<StructuredData::Integer>(*i);
73
74 if (auto d = value.getAsNumber())
75 return std::make_shared<StructuredData::Float>(*d);
76
77 if (auto n = value.getAsNull())
78 return std::make_shared<StructuredData::Null>();
79
81}
82
83static StructuredData::ObjectSP ParseJSONObject(json::Object *object) {
84 auto dict_up = std::make_unique<StructuredData::Dictionary>();
85 for (auto &KV : *object) {
86 StringRef key = KV.first;
87 json::Value value = KV.second;
88 if (StructuredData::ObjectSP value_sp = ParseJSONValue(value))
89 dict_up->AddItem(key, value_sp);
90 }
91 return std::move(dict_up);
92}
93
94static StructuredData::ObjectSP ParseJSONArray(json::Array *array) {
95 auto array_up = std::make_unique<StructuredData::Array>();
96 for (json::Value &value : *array) {
97 if (StructuredData::ObjectSP value_sp = ParseJSONValue(value))
98 array_up->AddItem(value_sp);
99 }
100 return std::move(array_up);
101}
102
106 std::pair<llvm::StringRef, llvm::StringRef> match = path.split('.');
107 std::string key = match.first.str();
108 ObjectSP value = this->GetAsDictionary()->GetValueForKey(key);
109 if (value.get()) {
110 // Do we have additional words to descend? If not, return the value
111 // we're at right now.
112 if (match.second.empty()) {
113 return value;
114 } else {
115 return value->GetObjectForDotSeparatedPath(match.second);
116 }
117 }
118 return ObjectSP();
119 }
120
122 std::pair<llvm::StringRef, llvm::StringRef> match = path.split('[');
123 if (match.second.empty()) {
124 return this->shared_from_this();
125 }
126 errno = 0;
127 uint64_t val = strtoul(match.second.str().c_str(), nullptr, 10);
128 if (errno == 0) {
129 return this->GetAsArray()->GetItemAtIndex(val);
130 }
131 return ObjectSP();
132 }
133
134 return this->shared_from_this();
135}
136
137void StructuredData::Object::DumpToStdout(bool pretty_print) const {
138 json::OStream stream(llvm::outs(), pretty_print ? 2 : 0);
139 Serialize(stream);
140}
141
142void StructuredData::Array::Serialize(json::OStream &s) const {
143 s.arrayBegin();
144 for (const auto &item_sp : m_items) {
145 item_sp->Serialize(s);
146 }
147 s.arrayEnd();
148}
149
150void StructuredData::Integer::Serialize(json::OStream &s) const {
151 s.value(static_cast<int64_t>(m_value));
152}
153
154void StructuredData::Float::Serialize(json::OStream &s) const {
155 s.value(m_value);
156}
157
158void StructuredData::Boolean::Serialize(json::OStream &s) const {
159 s.value(m_value);
160}
161
162void StructuredData::String::Serialize(json::OStream &s) const {
163 s.value(m_value);
164}
165
166void StructuredData::Dictionary::Serialize(json::OStream &s) const {
167 s.objectBegin();
168 for (const auto &pair : m_dict) {
169 s.attributeBegin(pair.first.GetStringRef());
170 pair.second->Serialize(s);
171 s.attributeEnd();
172 }
173 s.objectEnd();
174}
175
176void StructuredData::Null::Serialize(json::OStream &s) const {
177 s.value(nullptr);
178}
179
180void StructuredData::Generic::Serialize(json::OStream &s) const {
181 s.value(llvm::formatv("{0:X}", m_object));
182}
183
185 s.Printf("%" PRId64, static_cast<int64_t>(m_value));
186}
187
189 s.Printf("%f", m_value);
190}
191
193 s.Printf(m_value ? "True" : "False");
194}
195
197 s.Printf("%s", m_value.empty() ? "\"\"" : m_value.c_str());
198}
199
201 size_t index = 0;
202 size_t indentation_level = s.GetIndentLevel();
203 for (const auto &item_sp : m_items) {
204 // Sanitize.
205 if (!item_sp)
206 continue;
207
208 // Reset original indentation level.
209 s.SetIndentLevel(indentation_level);
210 s.Indent();
211
212 // Print key
213 s.Printf("[%zu]:", index++);
214
215 // Return to new line and increase indentation if value is record type.
216 // Otherwise add spacing.
217 bool should_indent = IsRecordType(item_sp);
218 if (should_indent) {
219 s.EOL();
220 s.IndentMore();
221 } else {
222 s.PutChar(' ');
223 }
224
225 // Print value and new line if now last pair.
226 item_sp->GetDescription(s);
227 if (item_sp != *(--m_items.end()))
228 s.EOL();
229
230 // Reset indentation level if it was incremented previously.
231 if (should_indent)
232 s.IndentLess();
233 }
234}
235
237 size_t indentation_level = s.GetIndentLevel();
238 for (const auto &pair : m_dict) {
239 // Sanitize.
240 if (pair.first.IsNull() || pair.first.IsEmpty() || !pair.second)
241 continue;
242
243 // Reset original indentation level.
244 s.SetIndentLevel(indentation_level);
245 s.Indent();
246
247 // Print key.
248 s.Printf("%s:", pair.first.AsCString());
249
250 // Return to new line and increase indentation if value is record type.
251 // Otherwise add spacing.
252 bool should_indent = IsRecordType(pair.second);
253 if (should_indent) {
254 s.EOL();
255 s.IndentMore();
256 } else {
257 s.PutChar(' ');
258 }
259
260 // Print value and new line if now last pair.
261 pair.second->GetDescription(s);
262 if (pair != *(--m_dict.end()))
263 s.EOL();
264
265 // Reset indentation level if it was incremented previously.
266 if (should_indent)
267 s.IndentLess();
268 }
269}
270
272 s.Printf("NULL");
273}
274
276 s.Printf("%p", m_object);
277}
static llvm::raw_ostream & error(Stream &strm)
static StructuredData::ObjectSP ParseJSONValue(json::Value &value)
static StructuredData::ObjectSP ParseJSONObject(json::Object *object)
static StructuredData::ObjectSP ParseJSONArray(json::Array *array)
A file utility class.
Definition: FileSpec.h:56
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:366
An error handling class.
Definition: Status.h:44
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition: Stream.cpp:130
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:107
size_t PutChar(char ch)
Definition: Stream.cpp:104
void SetIndentLevel(unsigned level)
Set the current indentation level.
Definition: Stream.cpp:163
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:128
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition: Stream.cpp:171
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition: Stream.cpp:168
unsigned GetIndentLevel() const
Get the current indentation level.
Definition: Stream.cpp:160
void Serialize(llvm::json::OStream &s) const override
ObjectSP GetItemAtIndex(size_t idx) const
void GetDescription(lldb_private::Stream &s) const override
void Serialize(llvm::json::OStream &s) const override
void GetDescription(lldb_private::Stream &s) const override
void Serialize(llvm::json::OStream &s) const override
ObjectSP GetValueForKey(llvm::StringRef key) const
void GetDescription(lldb_private::Stream &s) const override
void Serialize(llvm::json::OStream &s) const override
void GetDescription(lldb_private::Stream &s) const override
void GetDescription(lldb_private::Stream &s) const override
void Serialize(llvm::json::OStream &s) const override
void Serialize(llvm::json::OStream &s) const override
void GetDescription(lldb_private::Stream &s) const override
void GetDescription(lldb_private::Stream &s) const override
void Serialize(llvm::json::OStream &s) const override
void DumpToStdout(bool pretty_print=true) const
lldb::StructuredDataType GetType() const
ObjectSP GetObjectForDotSeparatedPath(llvm::StringRef path)
void GetDescription(lldb_private::Stream &s) const override
void Serialize(llvm::json::OStream &s) const override
static bool IsRecordType(const ObjectSP object_sp)
std::shared_ptr< Object > ObjectSP
static ObjectSP ParseJSON(const std::string &json_text)
static ObjectSP ParseJSONFromFile(const FileSpec &file, Status &error)
A class that represents a running process on the host machine.
const char * toString(AppleArm64ExceptionClass EC)
@ eStructuredDataTypeDictionary
@ eStructuredDataTypeArray
Definition: Debugger.h:51