userver: userver/formats/parse/variant.hpp Source File
Loading...
Searching...
No Matches
variant.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/parse/variant.hpp
4/// @brief Generic parser for std::variant type
5///
6/// Parsing is performed for each of the N alternatives in variant, and an
7/// exception is thrown and caught for each alternative that fails to parse.
8/// Alternatives that @ref formats::parse::MayParseAs rejects are parsed only
9/// if no alternative fits, to report their errors.
10///
11/// @ingroup userver_universal userver_formats_parse
12
13#include <array>
14#include <cstddef>
15#include <exception>
16#include <optional>
17#include <string>
18#include <typeinfo>
19#include <utility>
20#include <variant>
21
22#include <fmt/format.h>
23
24#include <userver/compiler/demangle.hpp>
25#include <userver/formats/parse/may_parse.hpp>
26#include <userver/formats/parse/to.hpp>
27
28USERVER_NAMESPACE_BEGIN
29
30namespace formats::json {
31class Value;
32}
33
34namespace formats::parse {
35
36template <typename ParseException, typename Variant, typename TypeA>
37[[noreturn]] void ThrowVariantAmbiguousParse(std::string_view path, std::type_index type_b) {
38 throw ParseException(fmt::format(
39 "Value of '{}' is ambiguous, it is parseable into multiple variants of '{}', at least '{}' and '{}'",
40 path,
41 compiler::GetTypeName<Variant>(),
42 compiler::GetTypeName<TypeA>(),
44 ));
45}
46
47template <class ParseException, typename Variant>
48[[noreturn]] void ThrowVariantParseException(std::string_view path, std::string_view errors) {
49 throw ParseException(fmt::format(
50 "Value of '{}' cannot be parsed as {}. Issues during parsing follow: {}",
51 path,
52 compiler::GetTypeName<Variant>(),
53 errors
54 ));
55}
56
57namespace impl {
58
59template <class T>
60std::string FormatVariantParseError(const std::exception& e) {
61 return fmt::format("\n* Failed to parse as {}: {}", compiler::GetTypeName<T>(), e.what());
62}
63
64template <class T, class Value, typename Result>
65void ParseVariantSingle(const Value& value, std::optional<Result>& result, std::string& error) {
66 if (!formats::parse::MayParseAs<T>(value)) {
67 return;
68 }
69
70 if (result) {
71 const auto old_type = std::visit([](const auto& v) -> std::type_index { return typeid(v); }, *result);
72 try {
73 value.template As<T>();
74 } catch (const std::exception&) {
75 return;
76 }
77
78 using ParseException = typename Value::ParseException;
79 formats::parse::ThrowVariantAmbiguousParse<ParseException, Result, T>(value.GetPath(), old_type);
80 } else {
81 // No result yet
82 try {
83 result = value.template As<T>();
84 } catch (const std::exception& e) {
85 error = impl::FormatVariantParseError<T>(e);
86 }
87 }
88}
89
90template <class T, class Value>
91void ParseRejectedVariantSingle(const Value& value, std::string& error) {
92 if (formats::parse::MayParseAs<T>(value)) {
93 return;
94 }
95
96 try {
97 value.template As<T>();
98 } catch (const std::exception& e) {
99 error = impl::FormatVariantParseError<T>(e);
100 }
101}
102
103template <typename... Types, class Value, typename Result, std::size_t... Indices>
104std::string
105ParseVariantAlternatives(const Value& value, std::optional<Result>& result, std::index_sequence<Indices...>) {
106 std::array<std::string, sizeof...(Types)> errors;
107 (impl::ParseVariantSingle<Types>(value, result, errors[Indices]), ...);
108 if (result) {
109 return {};
110 }
111
112 (impl::ParseRejectedVariantSingle<Types>(value, errors[Indices]), ...);
113 return (std::string{} + ... + errors[Indices]);
114}
115
116} // namespace impl
117
118template <class Value, typename... Types>
119std::variant<decltype(Parse(std::declval<Value>(), To<Types>{}))...>
120Parse(const Value& value, formats::parse::To<std::variant<Types...>>) {
121 using Result = std::variant<decltype(Parse(std::declval<Value>(), To<Types>{}))...>;
122 std::optional<Result> result;
123
124 std::string errors;
125
126 if constexpr (std::is_same_v<Value, formats::json::Value>) {
127 Value value2{value};
128 value2.DropRootPath();
129 errors = impl::ParseVariantAlternatives<Types...>(value2, result, std::index_sequence_for<Types...>{});
130 } else {
131 errors = impl::ParseVariantAlternatives<Types...>(value, result, std::index_sequence_for<Types...>{});
132 }
133
134 if (!result) {
135 formats::parse::ThrowVariantParseException<
136 typename Value::ParseException,
137 std::variant<Types...>>(value.GetPath(), errors);
138 }
139
140 return std::move(*result);
141}
142
143} // namespace formats::parse
144
145USERVER_NAMESPACE_END