46#ifndef LLVM_SUPPORT_JSON_H
47#define LLVM_SUPPORT_JSON_H
80 std::is_integral_v<T> && std::is_unsigned_v<T> &&
94template <
typename T>
Value toJSON(
const std::optional<T> &Opt);
113 explicit Object(std::initializer_list<KV> Properties);
120 bool empty()
const {
return M.empty(); }
121 size_t size()
const {
return M.size(); }
124 std::pair<iterator, bool>
insert(KV
E);
125 template <
typename... Ts>
127 return M.try_emplace(K, std::forward<Ts>(Args)...);
129 template <
typename... Ts>
131 return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
165 std::vector<Value> V;
173 explicit Array(std::initializer_list<Value> Elements);
174 template <
typename Collection>
explicit Array(
const Collection &
C) {
175 for (
const auto &V :
C)
304 Value(std::initializer_list<Value> Elements);
306 create<json::Array>(std::move(Elements));
308 template <
typename Elt>
311 create<json::Object>(std::move(Properties));
313 template <
typename Elt>
318 assert(
false &&
"Invalid UTF-8 in value used as JSON");
321 create<std::string>(std::move(V));
328 create<llvm::StringRef>(V);
330 assert(
false &&
"Invalid UTF-8 in value used as JSON");
338 template <
typename T,
typename = std::enable_if_t<std::is_same_v<T,
bool>>,
345 template <
typename T,
typename = std::enable_if_t<is_u
int_64_bit_v<T>>>
352 template <
typename T,
typename = std::enable_if_t<std::is_
integral_v<T>>,
353 typename = std::enable_if_t<!std::is_same_v<T,
bool>>,
354 typename = std::enable_if_t<!is_u
int_64_bit_v<T>>>
356 create<int64_t>(int64_t{
I});
359 template <
typename T,
360 typename = std::enable_if_t<std::is_floating_point_v<T>>,
363 create<double>(
double{
D});
366 template <
typename T,
367 typename = std::enable_if_t<
368 std::is_same_v<
Value,
decltype(
toJSON(*(
const T *)
nullptr))>>,
379 moveFrom(std::move(M));
421 return as<int64_t>();
423 return as<uint64_t>();
429 return as<int64_t>();
437 double D = as<double>();
439 D >=
double(std::numeric_limits<int64_t>::min()) &&
440 D <=
double(std::numeric_limits<int64_t>::max())))
446 if (
Type == T_UINT64)
447 return as<uint64_t>();
448 else if (
Type == T_Integer) {
449 int64_t
N = as<int64_t>();
451 return as<uint64_t>();
456 if (
Type == T_String)
459 return as<llvm::StringRef>();
477 void copyFrom(
const Value &M);
481 void moveFrom(
const Value &&M);
485 template <
typename T,
typename... U>
void create(U &&... V) {
486#if LLVM_ADDRESS_SANITIZER_BUILD
498 new (
reinterpret_cast<T *
>(&Union))
T(std::forward<U>(V)...);
500 template <
typename T>
T &as()
const {
503 void *Storage =
static_cast<void *
>(&Union);
504 return *
static_cast<T *
>(Storage);
509 enum ValueType :
char16_t {
555 V.emplace_back(std::forward<Args>(
A)...);
559 return V.insert(
P,
E);
562 return V.insert(
P, std::move(
E));
564template <
typename It>
566 return V.insert(
P,
A, Z);
568template <
typename... Args>
570 return V.emplace(
P, std::forward<Args>(
A)...);
583 assert(
false &&
"Invalid UTF-8 in value used as JSON");
584 *Owned =
fixUTF8(std::move(*Owned));
590 assert(
false &&
"Invalid UTF-8 in value used as JSON");
602 Owned.reset(
new std::string(*
C.Owned));
612 std::string
str()
const {
return Data.
str(); }
617 std::unique_ptr<std::string> Owned;
637 for (
const auto &
P : Properties) {
640 R.first->getSecond().moveFrom(std::move(
P.V));
680 Segment(Root *R) : Pointer(reinterpret_cast<uintptr_t>(R)) {}
682 : Pointer(reinterpret_cast<uintptr_t>(
Field.data())),
684 Segment(
unsigned Index) : Pointer(0), Offset(
Index) {}
686 bool isField()
const {
return Pointer != 0; }
687 StringRef field()
const {
688 return StringRef(
reinterpret_cast<const char *
>(Pointer), Offset);
690 unsigned index()
const {
return Offset; }
691 Root *root()
const {
return reinterpret_cast<Root *
>(
Pointer); }
697 Path(
const Path *Parent, Segment S) : Parent(Parent), Seg(S) {}
705 std::vector<Path::Segment> ErrorPath;
732 if (
auto S =
E.getAsString()) {
733 Out = std::string(*S);
736 P.report(
"expected string");
740 if (
auto S =
E.getAsInteger()) {
744 P.report(
"expected integer");
748 if (
auto S =
E.getAsInteger()) {
752 P.report(
"expected integer");
756 if (
auto S =
E.getAsNumber()) {
760 P.report(
"expected number");
764 if (
auto S =
E.getAsBoolean()) {
768 P.report(
"expected boolean");
772 if (
auto S =
E.getAsUINT64()) {
776 P.report(
"expected uint64_t");
780 if (
auto S =
E.getAsNull()) {
784 P.report(
"expected null");
796 Out = std::move(Result);
801 if (
auto *
A =
E.getAsArray()) {
803 Out.resize(
A->size());
804 for (
size_t I = 0;
I <
A->size(); ++
I)
809 P.report(
"expected array");
814 if (
auto *O =
E.getAsObject()) {
816 for (
const auto &KV : *O)
822 P.report(
"expected object");
847 P.report(
"expected object");
852 operator bool()
const {
return O; }
857 assert(*
this &&
"Must check this is an object before calling map()");
868 assert(*
this &&
"Must check this is an object before calling map()");
879 assert(*
this &&
"Must check this is an object before calling map()");
897 unsigned Line, Column, Offset;
901 ParseError(
const char *Msg,
unsigned Line,
unsigned Column,
unsigned Offset)
902 : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
904 OS <<
llvm::formatv(
"[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
915 auto V =
parse(JSON);
917 return V.takeError();
921 return std::move(Result);
984 :
OS(
OS), IndentSize(IndentSize) {
988 assert(Stack.
size() == 1 &&
"Unmatched begin()/end()");
990 assert(Stack.
back().HasValue &&
"Did not write top-level value");
1035 attributeImpl(Key, [&] {
value(Contents); });
1039 attributeImpl(Key, [&] {
array(Contents); });
1043 attributeImpl(Key, [&] {
object(Contents); });
1066 void flushComment();
1076 Context Ctx = Singleton;
1077 bool HasValue =
false;
1082 unsigned IndentSize;
1083 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 __asan_unpoison_memory_region(p, size)
#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 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)
std::vector< const Object::value_type * > sortedElements(const Object &O)
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 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...
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
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.