46#ifndef LLVM_SUPPORT_JSON_H
47#define LLVM_SUPPORT_JSON_H
79 std::is_integral_v<T> && std::is_unsigned_v<T> &&
93template <
typename T>
Value toJSON(
const std::optional<T> &Opt);
112 explicit Object(std::initializer_list<KV> Properties);
119 bool empty()
const {
return M.empty(); }
120 size_t size()
const {
return M.size(); }
123 std::pair<iterator, bool>
insert(KV
E);
124 template <
typename... Ts>
126 return M.try_emplace(K, std::forward<Ts>(Args)...);
128 template <
typename... Ts>
130 return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
164 std::vector<Value> V;
172 explicit Array(std::initializer_list<Value> Elements);
173 template <
typename Collection>
explicit Array(
const Collection &
C) {
174 for (
const auto &V :
C)
303 Value(std::initializer_list<Value> Elements);
305 create<json::Array>(std::move(Elements));
307 template <
typename Elt>
310 create<json::Object>(std::move(Properties));
312 template <
typename Elt>
317 assert(
false &&
"Invalid UTF-8 in value used as JSON");
320 create<std::string>(std::move(V));
327 create<llvm::StringRef>(V);
329 assert(
false &&
"Invalid UTF-8 in value used as JSON");
337 template <
typename T,
typename = std::enable_if_t<std::is_same_v<T,
bool>>,
344 template <
typename T,
typename = std::enable_if_t<is_u
int_64_bit_v<T>>>
351 template <
typename T,
typename = std::enable_if_t<std::is_
integral_v<T>>,
352 typename = std::enable_if_t<!std::is_same_v<T,
bool>>,
353 typename = std::enable_if_t<!is_u
int_64_bit_v<T>>>
355 create<int64_t>(int64_t{
I});
358 template <
typename T,
359 typename = std::enable_if_t<std::is_floating_point_v<T>>,
362 create<double>(
double{
D});
365 template <
typename T,
366 typename = std::enable_if_t<
367 std::is_same_v<
Value,
decltype(
toJSON(*(
const T *)
nullptr))>>,
378 moveFrom(std::move(M));
420 return as<int64_t>();
422 return as<uint64_t>();
428 return as<int64_t>();
436 double D = as<double>();
438 D >=
double(std::numeric_limits<int64_t>::min()) &&
439 D <=
double(std::numeric_limits<int64_t>::max())))
445 if (
Type == T_UINT64)
446 return as<uint64_t>();
447 else if (
Type == T_Integer) {
448 int64_t
N = as<int64_t>();
450 return as<uint64_t>();
455 if (
Type == T_String)
458 return as<llvm::StringRef>();
476 void copyFrom(
const Value &M);
480 void moveFrom(
const Value &&M);
484 template <
typename T,
typename... U>
void create(U &&... V) {
485 new (
reinterpret_cast<T *
>(&Union))
T(std::forward<U>(V)...);
487 template <
typename T>
T &as()
const {
490 void *Storage =
static_cast<void *
>(&Union);
491 return *
static_cast<T *
>(Storage);
496 enum ValueType :
char16_t {
542 V.emplace_back(std::forward<Args>(
A)...);
546 return V.insert(
P,
E);
549 return V.insert(
P, std::move(
E));
551template <
typename It>
553 return V.insert(
P,
A, Z);
555template <
typename... Args>
557 return V.emplace(
P, std::forward<Args>(
A)...);
570 assert(
false &&
"Invalid UTF-8 in value used as JSON");
571 *Owned =
fixUTF8(std::move(*Owned));
577 assert(
false &&
"Invalid UTF-8 in value used as JSON");
589 Owned.reset(
new std::string(*
C.Owned));
599 std::string
str()
const {
return Data.
str(); }
604 std::unique_ptr<std::string> Owned;
624 for (
const auto &
P : Properties) {
627 R.first->getSecond().moveFrom(std::move(
P.V));
665 Segment(Root *R) : Pointer(reinterpret_cast<uintptr_t>(R)) {}
667 : Pointer(reinterpret_cast<uintptr_t>(
Field.data())),
669 Segment(
unsigned Index) : Pointer(0), Offset(
Index) {}
671 bool isField()
const {
return Pointer != 0; }
672 StringRef field()
const {
673 return StringRef(
reinterpret_cast<const char *
>(Pointer), Offset);
675 unsigned index()
const {
return Offset; }
676 Root *root()
const {
return reinterpret_cast<Root *
>(
Pointer); }
682 Path(
const Path *Parent, Segment S) : Parent(Parent), Seg(S) {}
690 std::vector<Path::Segment> ErrorPath;
717 if (
auto S =
E.getAsString()) {
718 Out = std::string(*S);
721 P.report(
"expected string");
725 if (
auto S =
E.getAsInteger()) {
729 P.report(
"expected integer");
733 if (
auto S =
E.getAsInteger()) {
737 P.report(
"expected integer");
741 if (
auto S =
E.getAsNumber()) {
745 P.report(
"expected number");
749 if (
auto S =
E.getAsBoolean()) {
753 P.report(
"expected boolean");
757 if (
auto S =
E.getAsUINT64()) {
761 P.report(
"expected uint64_t");
765 if (
auto S =
E.getAsNull()) {
769 P.report(
"expected null");
781 Out = std::move(Result);
786 if (
auto *
A =
E.getAsArray()) {
788 Out.resize(
A->size());
789 for (
size_t I = 0;
I <
A->size(); ++
I)
794 P.report(
"expected array");
799 if (
auto *O =
E.getAsObject()) {
801 for (
const auto &KV : *O)
807 P.report(
"expected object");
832 P.report(
"expected object");
837 operator bool()
const {
return O; }
842 assert(*
this &&
"Must check this is an object before calling map()");
853 assert(*
this &&
"Must check this is an object before calling map()");
864 assert(*
this &&
"Must check this is an object before calling map()");
882 unsigned Line, Column, Offset;
886 ParseError(
const char *Msg,
unsigned Line,
unsigned Column,
unsigned Offset)
887 : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
889 OS <<
llvm::formatv(
"[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
900 auto V =
parse(JSON);
902 return V.takeError();
906 return std::move(Result);
969 :
OS(
OS), IndentSize(IndentSize) {
973 assert(Stack.
size() == 1 &&
"Unmatched begin()/end()");
975 assert(Stack.
back().HasValue &&
"Did not write top-level value");
1020 attributeImpl(Key, [&] {
value(Contents); });
1024 attributeImpl(Key, [&] {
array(Contents); });
1028 attributeImpl(Key, [&] {
object(Contents); });
1051 void flushComment();
1062 bool HasValue =
false;
1067 unsigned IndentSize;
1068 unsigned Indent = 0;
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
Given that RA is a live value
This file defines the DenseMap class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
bool erase(const KeyT &Val)
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Base class for user error types.
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
StringRef - Represent a constant reference to a string, i.e.
std::string str() const
str - Get the contents as an std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
An efficient, type-erasing, non-owning reference to a callable.
An Array is a JSON array, which contains heterogeneous JSON values.
void emplace_back(Args &&...A)
friend bool operator==(const Array &L, const Array &R)
std::vector< Value >::const_iterator const_iterator
Value & operator[](size_t I)
iterator emplace(const_iterator P, Args &&...A)
std::vector< Value >::iterator iterator
iterator insert(const_iterator P, const Value &E)
void push_back(const Value &E)
Array(const Collection &C)
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
void object(Block Contents)
Emit an object whose elements are emitted in the provided Block.
void rawValue(llvm::function_ref< void(raw_ostream &)> Contents)
Emit an externally-serialized value.
void attributeObject(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an object with attributes from the Block.
OStream(llvm::raw_ostream &OS, unsigned IndentSize=0)
void attributeBegin(llvm::StringRef Key)
void attribute(llvm::StringRef Key, const Value &Contents)
Emit an attribute whose value is self-contained (number, vector<int> etc).
void flush()
Flushes the underlying ostream. OStream does not buffer internally.
raw_ostream & rawValueBegin()
void attributeArray(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an array with elements from the Block.
void comment(llvm::StringRef)
Emit a JavaScript comment associated with the next printed value.
void array(Block Contents)
Emit an array whose elements are emitted in the provided Block.
void rawValue(llvm::StringRef Contents)
void value(const Value &V)
Emit a self-contained value (number, string, vector<string> etc).
llvm::function_ref< void()> Block
ObjectKey is a used to capture keys in Object.
ObjectKey & operator=(ObjectKey &&)=default
ObjectKey(const ObjectKey &C)
ObjectKey(const llvm::formatv_object_base &V)
ObjectKey(llvm::StringRef S)
ObjectKey & operator=(const ObjectKey &C)
ObjectKey(const llvm::SmallVectorImpl< char > &V)
Helper for mapping JSON objects onto protocol structs.
ObjectMapper(const Value &E, Path P)
If O is not an object, this mapper is invalid and an error is reported.
bool map(StringLiteral Prop, T &Out)
Maps a property to a field.
bool mapOptional(StringLiteral Prop, T &Out)
Maps a property to a field, if it exists.
bool map(StringLiteral Prop, std::optional< T > &Out)
Maps a property to a field, if it exists.
An Object is a JSON object, which maps strings to heterogenous JSON values.
std::optional< bool > getBoolean(StringRef K) const
const_iterator end() const
Value & operator[](const ObjectKey &K)
std::optional< double > getNumber(StringRef K) const
const json::Object * getObject(StringRef K) const
std::optional< llvm::StringRef > getString(StringRef K) const
Storage::value_type value_type
std::pair< iterator, bool > try_emplace(ObjectKey &&K, Ts &&... Args)
std::optional< int64_t > getInteger(StringRef K) const
std::optional< std::nullptr_t > getNull(StringRef K) const
std::pair< iterator, bool > try_emplace(const ObjectKey &K, Ts &&... Args)
const_iterator begin() const
const_iterator find(StringRef K) const
iterator find(StringRef K)
std::pair< iterator, bool > insert(KV E)
const json::Array * getArray(StringRef K) const
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(llvm::raw_ostream &OS) const override
Print an error message to an output stream.
ParseError(const char *Msg, unsigned Line, unsigned Column, unsigned Offset)
The root is the trivial Path to the root value.
void printErrorContext(const Value &, llvm::raw_ostream &) const
Print the root value with the error shown inline as a comment.
Root & operator=(const Root &)=delete
Error getError() const
Returns the last error reported, or else a generic error.
Root(const Root &)=delete
Root & operator=(Root &&)=delete
Root(llvm::StringRef Name="")
A "cursor" marking a position within a Value.
Path index(unsigned Index) const
Derives a path for an array element: this[Index].
void report(llvm::StringLiteral Message)
Records that the value at the current path is invalid.
Path field(StringRef Field) const
Derives a path for an object field: this.Field.
Path(Root &R)
The root may be treated as a Path.
A Value is an JSON value of unknown type.
friend bool operator==(const Value &, const Value &)
Value(json::Object &&Properties)
Value(const std::vector< Elt > &C)
std::optional< bool > getAsBoolean() const
std::optional< double > getAsNumber() const
std::optional< uint64_t > getAsUINT64() const
Value & operator=(Value &&M)
Value & operator=(const Value &M)
Value(const llvm::formatv_object_base &V)
json::Object * getAsObject()
std::optional< int64_t > getAsInteger() const
Value(const llvm::SmallVectorImpl< char > &V)
Value(const std::map< std::string, Elt > &C)
json::Array * getAsArray()
Value(json::Array &&Elements)
@ Number
Number values can store both int64s and doubles at full precision, depending on what they were constr...
std::optional< llvm::StringRef > getAsString() const
std::optional< std::nullptr_t > getAsNull() const
const json::Object * getAsObject() const
const json::Array * getAsArray() const
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
constexpr bool is_uint_64_bit_v
Value toJSON(const std::optional< T > &Opt)
bool operator<(const ObjectKey &L, const ObjectKey &R)
bool operator==(const Object &LHS, const Object &RHS)
bool isUTF8(llvm::StringRef S, size_t *ErrOffset=nullptr)
Returns true if S is valid UTF-8, which is required for use as JSON.
bool fromJSON(const Value &E, std::string &Out, Path P)
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const Value &V)
Serializes this Value to JSON, writing it to the provided stream.
std::string fixUTF8(llvm::StringRef S)
Replaces invalid UTF-8 sequences in S with the replacement character (U+FFFD).
bool operator!=(const Object &LHS, const Object &RHS)
This is an optimization pass for GlobalISel generic memory operations.
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Implement std::hash so that hash_code can be used in STL containers.
A suitably aligned and sized character array member which can hold elements of any type.