Path: blob/main/contrib/llvm-project/lldb/source/Utility/StructuredData.cpp
39587 views
//===-- StructuredData.cpp ------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Utility/StructuredData.h"9#include "lldb/Utility/FileSpec.h"10#include "lldb/Utility/Status.h"11#include "llvm/ADT/StringExtras.h"12#include "llvm/Support/MemoryBuffer.h"13#include <cerrno>14#include <cinttypes>15#include <cstdlib>1617using namespace lldb_private;18using namespace llvm;1920static StructuredData::ObjectSP ParseJSONValue(json::Value &value);21static StructuredData::ObjectSP ParseJSONObject(json::Object *object);22static StructuredData::ObjectSP ParseJSONArray(json::Array *array);2324StructuredData::ObjectSP StructuredData::ParseJSON(llvm::StringRef json_text) {25llvm::Expected<json::Value> value = json::parse(json_text);26if (!value) {27llvm::consumeError(value.takeError());28return nullptr;29}30return ParseJSONValue(*value);31}3233StructuredData::ObjectSP34StructuredData::ParseJSONFromFile(const FileSpec &input_spec, Status &error) {35StructuredData::ObjectSP return_sp;3637auto buffer_or_error = llvm::MemoryBuffer::getFile(input_spec.GetPath());38if (!buffer_or_error) {39error.SetErrorStringWithFormatv("could not open input file: {0} - {1}.",40input_spec.GetPath(),41buffer_or_error.getError().message());42return return_sp;43}44llvm::Expected<json::Value> value =45json::parse(buffer_or_error.get()->getBuffer().str());46if (value)47return ParseJSONValue(*value);48error.SetErrorString(toString(value.takeError()));49return StructuredData::ObjectSP();50}5152bool StructuredData::IsRecordType(const ObjectSP object_sp) {53return object_sp->GetType() == lldb::eStructuredDataTypeArray ||54object_sp->GetType() == lldb::eStructuredDataTypeDictionary;55}5657static StructuredData::ObjectSP ParseJSONValue(json::Value &value) {58if (json::Object *O = value.getAsObject())59return ParseJSONObject(O);6061if (json::Array *A = value.getAsArray())62return ParseJSONArray(A);6364if (auto s = value.getAsString())65return std::make_shared<StructuredData::String>(*s);6667if (auto b = value.getAsBoolean())68return std::make_shared<StructuredData::Boolean>(*b);6970if (auto u = value.getAsUINT64())71return std::make_shared<StructuredData::UnsignedInteger>(*u);7273if (auto i = value.getAsInteger())74return std::make_shared<StructuredData::SignedInteger>(*i);7576if (auto d = value.getAsNumber())77return std::make_shared<StructuredData::Float>(*d);7879if (auto n = value.getAsNull())80return std::make_shared<StructuredData::Null>();8182return StructuredData::ObjectSP();83}8485static StructuredData::ObjectSP ParseJSONObject(json::Object *object) {86auto dict_up = std::make_unique<StructuredData::Dictionary>();87for (auto &KV : *object) {88StringRef key = KV.first;89json::Value value = KV.second;90if (StructuredData::ObjectSP value_sp = ParseJSONValue(value))91dict_up->AddItem(key, value_sp);92}93return std::move(dict_up);94}9596static StructuredData::ObjectSP ParseJSONArray(json::Array *array) {97auto array_up = std::make_unique<StructuredData::Array>();98for (json::Value &value : *array) {99if (StructuredData::ObjectSP value_sp = ParseJSONValue(value))100array_up->AddItem(value_sp);101}102return std::move(array_up);103}104105StructuredData::ObjectSP106StructuredData::Object::GetObjectForDotSeparatedPath(llvm::StringRef path) {107if (GetType() == lldb::eStructuredDataTypeDictionary) {108std::pair<llvm::StringRef, llvm::StringRef> match = path.split('.');109llvm::StringRef key = match.first;110ObjectSP value = GetAsDictionary()->GetValueForKey(key);111if (!value)112return {};113114// Do we have additional words to descend? If not, return the value115// we're at right now.116if (match.second.empty())117return value;118119return value->GetObjectForDotSeparatedPath(match.second);120}121122if (GetType() == lldb::eStructuredDataTypeArray) {123std::pair<llvm::StringRef, llvm::StringRef> match = path.split('[');124if (match.second.empty())125return shared_from_this();126127uint64_t val = 0;128if (!llvm::to_integer(match.second, val, /* Base = */ 10))129return {};130131return GetAsArray()->GetItemAtIndex(val);132}133134return shared_from_this();135}136137void StructuredData::Object::DumpToStdout(bool pretty_print) const {138json::OStream stream(llvm::outs(), pretty_print ? 2 : 0);139Serialize(stream);140}141142void StructuredData::Array::Serialize(json::OStream &s) const {143s.arrayBegin();144for (const auto &item_sp : m_items) {145item_sp->Serialize(s);146}147s.arrayEnd();148}149150void StructuredData::Float::Serialize(json::OStream &s) const {151s.value(m_value);152}153154void StructuredData::Boolean::Serialize(json::OStream &s) const {155s.value(m_value);156}157158void StructuredData::String::Serialize(json::OStream &s) const {159s.value(m_value);160}161162void StructuredData::Dictionary::Serialize(json::OStream &s) const {163s.objectBegin();164165// To ensure the output format is always stable, we sort the dictionary by key166// first.167using Entry = std::pair<llvm::StringRef, ObjectSP>;168std::vector<Entry> sorted_entries;169for (const auto &pair : m_dict)170sorted_entries.push_back({pair.first(), pair.second});171172llvm::sort(sorted_entries);173174for (const auto &pair : sorted_entries) {175s.attributeBegin(pair.first);176pair.second->Serialize(s);177s.attributeEnd();178}179s.objectEnd();180}181182void StructuredData::Null::Serialize(json::OStream &s) const {183s.value(nullptr);184}185186void StructuredData::Generic::Serialize(json::OStream &s) const {187s.value(llvm::formatv("{0:X}", m_object));188}189190void StructuredData::Float::GetDescription(lldb_private::Stream &s) const {191s.Printf("%f", m_value);192}193194void StructuredData::Boolean::GetDescription(lldb_private::Stream &s) const {195s.Printf(m_value ? "True" : "False");196}197198void StructuredData::String::GetDescription(lldb_private::Stream &s) const {199s.Printf("%s", m_value.empty() ? "\"\"" : m_value.c_str());200}201202void StructuredData::Array::GetDescription(lldb_private::Stream &s) const {203size_t index = 0;204size_t indentation_level = s.GetIndentLevel();205for (const auto &item_sp : m_items) {206// Sanitize.207if (!item_sp)208continue;209210// Reset original indentation level.211s.SetIndentLevel(indentation_level);212s.Indent();213214// Print key215s.Printf("[%zu]:", index++);216217// Return to new line and increase indentation if value is record type.218// Otherwise add spacing.219bool should_indent = IsRecordType(item_sp);220if (should_indent) {221s.EOL();222s.IndentMore();223} else {224s.PutChar(' ');225}226227// Print value and new line if now last pair.228item_sp->GetDescription(s);229if (item_sp != *(--m_items.end()))230s.EOL();231232// Reset indentation level if it was incremented previously.233if (should_indent)234s.IndentLess();235}236}237238void StructuredData::Dictionary::GetDescription(lldb_private::Stream &s) const {239size_t indentation_level = s.GetIndentLevel();240241// To ensure the output format is always stable, we sort the dictionary by key242// first.243using Entry = std::pair<llvm::StringRef, ObjectSP>;244std::vector<Entry> sorted_entries;245for (const auto &pair : m_dict)246sorted_entries.push_back({pair.first(), pair.second});247248llvm::sort(sorted_entries);249250for (auto iter = sorted_entries.begin(); iter != sorted_entries.end();251iter++) {252// Sanitize.253if (iter->first.empty() || !iter->second)254continue;255256// Reset original indentation level.257s.SetIndentLevel(indentation_level);258s.Indent();259260// Print key.261s.Format("{0}:", iter->first);262263// Return to new line and increase indentation if value is record type.264// Otherwise add spacing.265bool should_indent = IsRecordType(iter->second);266if (should_indent) {267s.EOL();268s.IndentMore();269} else {270s.PutChar(' ');271}272273// Print value and new line if now last pair.274iter->second->GetDescription(s);275if (std::next(iter) != sorted_entries.end())276s.EOL();277278// Reset indentation level if it was incremented previously.279if (should_indent)280s.IndentLess();281}282}283284void StructuredData::Null::GetDescription(lldb_private::Stream &s) const {285s.Printf("NULL");286}287288void StructuredData::Generic::GetDescription(lldb_private::Stream &s) const {289s.Printf("%p", m_object);290}291292293