46#ifndef LLVM_SUPPORT_JSON_H
47#define LLVM_SUPPORT_JSON_H
88template <
typename T>
Value toJSON(
const std::optional<T> &Opt);
107 explicit Object(std::initializer_list<KV> Properties);
114 bool empty()
const {
return M.empty(); }
115 size_t size()
const {
return M.size(); }
118 std::pair<iterator, bool>
insert(KV
E);
119 template <
typename... Ts>
121 return M.try_emplace(K, std::forward<Ts>(Args)...);
123 template <
typename... Ts>
125 return M.try_emplace(std::move(K), std::forward<Ts>(Args)...);
159 std::vector<Value> V;
167 explicit Array(std::initializer_list<Value> Elements);
168 template <
typename Collection>
explicit Array(
const Collection &
C) {
169 for (
const auto &V :
C)
298 Value(std::initializer_list<Value> Elements);
300 create<json::Array>(std::move(Elements));
302 template <
typename Elt>
305 create<json::Object>(std::move(Properties));
307 template <
typename Elt>
312 assert(
false &&
"Invalid UTF-8 in value used as JSON");
315 create<std::string>(std::move(V));
322 create<llvm::StringRef>(V);
324 assert(
false &&
"Invalid UTF-8 in value used as JSON");
332 template <
typename T,
333 typename = std::enable_if_t<std::is_same<T, bool>::value>,
340 template <
typename T,
341 typename = std::enable_if_t<std::is_same<T, uint64_t>::value>,
342 bool =
false,
bool =
false>
349 template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>,
350 typename = std::enable_if_t<!std::is_same<T, bool>::value>,
351 typename = std::enable_if_t<!std::is_same<T, uint64_t>::value>>
353 create<int64_t>(int64_t{
I});
356 template <
typename T,
357 typename = std::enable_if_t<std::is_floating_point<T>::value>,
360 create<double>(
double{
D});
363 template <
typename T,
364 typename = std::enable_if_t<std::is_same<
376 moveFrom(std::move(M));
418 return as<int64_t>();
420 return as<uint64_t>();
426 return as<int64_t>();
428 double D = as<double>();
430 D >=
double(std::numeric_limits<int64_t>::min()) &&
431 D <=
double(std::numeric_limits<int64_t>::max())))
437 if (
Type == T_UINT64)
438 return as<uint64_t>();
439 else if (
Type == T_Integer) {
440 int64_t
N = as<int64_t>();
442 return as<uint64_t>();
447 if (
Type == T_String)
450 return as<llvm::StringRef>();
468 void copyFrom(
const Value &M);
472 void moveFrom(
const Value &&M);
476 template <
typename T,
typename... U>
void create(U &&... V) {
477 new (
reinterpret_cast<T *
>(&Union))
T(std::forward<U>(V)...);
479 template <
typename T>
T &as()
const {
482 void *Storage =
static_cast<void *
>(&Union);
483 return *
static_cast<T *
>(Storage);
488 enum ValueType :
char16_t {
534 V.emplace_back(std::forward<Args>(
A)...);
538 return V.insert(
P,
E);
541 return V.insert(
P, std::move(
E));
543template <
typename It>
545 return V.insert(
P,
A, Z);
547template <
typename... Args>
549 return V.emplace(
P, std::forward<Args>(
A)...);
562 assert(
false &&
"Invalid UTF-8 in value used as JSON");
563 *Owned =
fixUTF8(std::move(*Owned));
569 assert(
false &&
"Invalid UTF-8 in value used as JSON");
581 Owned.reset(
new std::string(*
C.Owned));
591 std::string
str()
const {
return Data.
str(); }
596 std::unique_ptr<std::string> Owned;
616 for (
const auto &
P : Properties) {
619 R.first->getSecond().moveFrom(std::move(
P.V));
657 Segment(Root *R) : Pointer(reinterpret_cast<uintptr_t>(R)) {}
659 : Pointer(reinterpret_cast<uintptr_t>(
Field.data())),
661 Segment(
unsigned Index) : Pointer(0), Offset(
Index) {}
663 bool isField()
const {
return Pointer != 0; }
664 StringRef field()
const {
665 return StringRef(
reinterpret_cast<const char *
>(Pointer), Offset);
667 unsigned index()
const {
return Offset; }
668 Root *root()
const {
return reinterpret_cast<Root *
>(
Pointer); }
674 Path(
const Path *Parent, Segment S) : Parent(Parent), Seg(S) {}
682 std::vector<Path::Segment> ErrorPath;
709 if (
auto S =
E.getAsString()) {
710 Out = std::string(*S);
713 P.report(
"expected string");
717 if (
auto S =
E.getAsInteger()) {
721 P.report(
"expected integer");
725 if (
auto S =
E.getAsInteger()) {
729 P.report(
"expected integer");
733 if (
auto S =
E.getAsNumber()) {
737 P.report(
"expected number");
741 if (
auto S =
E.getAsBoolean()) {
745 P.report(
"expected boolean");
749 if (
auto S =
E.getAsUINT64()) {
753 P.report(
"expected uint64_t");
757 if (
auto S =
E.getAsNull()) {
761 P.report(
"expected null");
773 Out = std::move(Result);
778 if (
auto *
A =
E.getAsArray()) {
780 Out.resize(
A->size());
781 for (
size_t I = 0;
I <
A->size(); ++
I)
786 P.report(
"expected array");
791 if (
auto *O =
E.getAsObject()) {
793 for (
const auto &KV : *O)
799 P.report(
"expected object");
824 P.report(
"expected object");
829 operator bool()
const {
return O; }
834 assert(*
this &&
"Must check this is an object before calling map()");
845 assert(*
this &&
"Must check this is an object before calling map()");
856 assert(*
this &&
"Must check this is an object before calling map()");
874 unsigned Line, Column, Offset;
878 ParseError(
const char *Msg,
unsigned Line,
unsigned Column,
unsigned Offset)
879 : Msg(Msg), Line(Line), Column(Column), Offset(Offset) {}
881 OS <<
llvm::formatv(
"[{0}:{1}, byte={2}]: {3}", Line, Column, Offset, Msg);
892 auto V =
parse(JSON);
894 return V.takeError();
898 return std::move(Result);
961 : OS(OS), IndentSize(IndentSize) {
965 assert(Stack.
size() == 1 &&
"Unmatched begin()/end()");
967 assert(Stack.
back().HasValue &&
"Did not write top-level value");
1012 attributeImpl(Key, [&] {
value(Contents); });
1016 attributeImpl(Key, [&] {
array(Contents); });
1020 attributeImpl(Key, [&] {
object(Contents); });
1043 void flushComment();
1054 bool HasValue =
false;
1059 unsigned IndentSize;
1060 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.
return ToRemove size() > 0
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.
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))...))>
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.
A suitably aligned and sized character array member which can hold elements of any type.