C++Spec 1.1.0
BDD testing for C++
Loading...
Searching...
No Matches
pretty_matchers.hpp
Go to the documentation of this file.
1
2#pragma once
3
4#include <algorithm>
5#include <array>
6#include <cstddef>
7#include <cstdint>
8#include <deque>
9#include <format>
10#include <forward_list>
11#include <list>
12#include <map>
13#include <memory>
14#include <optional>
15#include <ranges>
16#include <regex>
17#include <set>
18#include <span>
19#include <string>
20#include <string_view>
21#include <tuple>
22#include <type_traits>
23#include <unordered_map>
24#include <unordered_set>
25#include <utility>
26#include <vector>
27
28#include "prettyprint.hpp"
29#include "util.hpp"
30
31// C++26 (P3168) gives std::optional begin()/end(), so cxx-prettyprint's
32// has_begin_end/has_const_iterator detection now classifies optional<T> as a
33// container and tries to element-print its value_type — which hard-errors for
34// element types lacking operator<< (and is wrong regardless: an optional is not
35// a container). Exclude it from prettyprint's container detection so optionals
36// reach Pretty's own optional to_word overload.
37namespace pretty_print {
38template <typename T>
39struct is_container<std::optional<T>> : std::false_type {};
40} // namespace pretty_print
41
42namespace CppSpec {
43
44namespace Util {
45
46// Whether T is Template<Args...> for some type arguments; std::array and std::span, which take a size, have their own.
47template <typename T, template <typename...> class Template>
48inline constexpr bool is_specialization_of = false;
49
50template <template <typename...> class Template, typename... Args>
51inline constexpr bool is_specialization_of<Template<Args...>, Template> = true;
52
53template <typename T>
54inline constexpr bool is_std_array = false;
55
56template <typename T, std::size_t N>
57inline constexpr bool is_std_array<std::array<T, N>> = true;
58
59template <typename T>
60inline constexpr bool is_std_span = false;
61
62template <typename T, std::size_t Extent>
63inline constexpr bool is_std_span<std::span<T, Extent>> = true;
64
71template <typename T>
73 std::is_array_v<T> || is_std_array<T> || is_std_span<T> || is_specialization_of<T, std::vector> ||
74 is_specialization_of<T, std::deque> || is_specialization_of<T, std::list> ||
75 is_specialization_of<T, std::forward_list> || is_specialization_of<T, std::set> ||
76 is_specialization_of<T, std::multiset> || is_specialization_of<T, std::unordered_set> ||
77 is_specialization_of<T, std::unordered_multiset> || is_specialization_of<T, std::map> ||
78 is_specialization_of<T, std::multimap> || is_specialization_of<T, std::unordered_map> ||
79 is_specialization_of<T, std::unordered_multimap> || is_specialization_of<T, std::pair> ||
80 is_specialization_of<T, std::tuple>;
81
93template <typename T>
95 : std::bool_constant<std::same_as<T, bool> || std::same_as<T, signed char> || std::same_as<T, unsigned char> ||
96 is_wide_character<T> || is_c_string<T> || is_non_text_character_pointer<T> ||
97 (std::is_enum_v<T> && !is_streamable<T>)> {};
98
99template <typename T>
100struct prints_through_pretty<std::optional<T>> : std::true_type {};
101
102template <typename A, typename B>
103struct prints_through_pretty<std::pair<A, B>> : std::bool_constant<prints_through_pretty<std::remove_cv_t<A>>::value ||
104 prints_through_pretty<std::remove_cv_t<B>>::value> {
105};
106
107template <typename... Ts>
108struct prints_through_pretty<std::tuple<Ts...>>
109 : std::bool_constant<(prints_through_pretty<std::remove_cv_t<Ts>>::value || ...)> {};
110
111// A range whose elements are of its own type, such as std::filesystem::path, is printed whole, and so is a range type
112// with an operator<< of its own.
113template <typename R>
114 requires std::ranges::input_range<const R> && (!is_string_like<R>) &&
115 (!std::same_as<std::remove_cv_t<std::ranges::range_value_t<const R>>, R>) &&
117struct prints_through_pretty<R> : prints_through_pretty<std::remove_cv_t<std::ranges::range_value_t<const R>>> {};
118
125template <typename T>
127 (std::is_class_v<T> || std::is_array_v<T>) && !is_string_like<T> && !is_optional_v<std::remove_cv_t<T>> &&
128 prints_through_pretty<std::remove_cv_t<T>>::value;
129
130} // namespace Util
131
132namespace Matchers {
133template <typename A, typename E>
134class MatcherBase;
135}
136
144struct Pretty {
145 std::string _name;
146 [[nodiscard]] std::string name(const std::string& name) const;
147 [[nodiscard]] std::string name_to_sentence(const std::string& name) const;
148 static std::string split_words(const std::string& sym);
149 static std::string underscore(const std::string& camel_cased_word);
150 static std::string last(const std::string& s, char delim);
151 static std::string improve_hash_formatting(const std::string& inspect_string);
152
153 template <typename T>
156 static std::string to_word(const T& item);
157
158 template <typename T>
159 static std::string to_word(const T& item);
160
161 template <typename T>
163 static std::string to_word(const T& item);
164
165 template <typename T>
167 static std::string to_word(const T& item);
168
169 template <typename T>
171 static std::string to_word(const T& item);
172
173 template <typename T>
174 requires std::is_enum_v<T> && (!Util::is_streamable<T>)
175 static std::string to_word(const T& item);
176
177 template <typename T>
178 static std::string to_word(const std::optional<T>& item);
179
180 template <typename T>
181 static std::string to_word_type(const T& item);
182
183 template <typename A, typename E>
184 static std::string to_word(const Matchers::MatcherBase<A, E>& matcher);
185
186 template <class T>
187 static std::string to_sentence(const T& item);
188
189 template <class T>
190 static std::string to_sentence(const std::vector<T>& words);
191
192 template <typename T>
193 static std::string inspect_object(const T& object);
194
204 static std::string address_of(const void* address) { return std::format("{}", address); }
205};
206
215template <typename T>
216inline std::string Pretty::to_sentence(const std::vector<T>& objects) {
217 std::vector<std::string> words;
218 for (const auto& object : objects) {
219 words.push_back(to_word(object));
220 }
221
222 std::stringstream ss;
223 switch (words.size()) {
224 case 0:
225 return "";
226 case 1:
227 ss << " " << words[0];
228 break;
229 case 2:
230 ss << " " << words[0] << " and " << words[1];
231 break;
232 default:
233 ss << " ";
234 for (size_t i = 0; i < words.size() - 1; ++i) {
235 if (i != 0) {
236 ss << ", ";
237 }
238 ss << words[i];
239 }
240 ss << ", and " << words.back();
241 break;
242 }
243
244 return ss.str();
245}
246
254template <typename T>
255inline std::string Pretty::to_sentence(const T& item) {
256 return to_sentence(std::vector{item});
257}
258
270template <typename T>
273inline std::string Pretty::to_word(const T& item) {
274 if constexpr (Util::is_c_string<T>) {
275 // A C string is printed through its view, so a null one prints as nullptr instead of being read.
276 const auto text = string_view_of(item);
277 return text ? std::string(*text) : std::string("nullptr");
278 } else {
279 std::ostringstream oss;
280 oss << item; // use operator<< to convert and append
281 return oss.str();
282 }
283}
284
285template <>
286inline std::string Pretty::to_word<bool>(const bool& item) {
287 return item ? "true" : "false";
288}
289
290// A byte-sized integer streams as a character; it is printed as the number it holds.
291template <>
292inline std::string Pretty::to_word<unsigned char>(const unsigned char& item) {
293 return std::to_string(item);
294}
295
296template <>
297inline std::string Pretty::to_word<signed char>(const signed char& item) {
298 return std::to_string(item);
299}
300
301template <>
302inline std::string Pretty::to_word<std::true_type>(const std::true_type& /* item */) {
303 return "true";
304}
305
306template <>
307inline std::string Pretty::to_word<std::false_type>(const std::false_type& /* item */) {
308 return "false";
309}
310
318template <typename T>
319inline std::string Pretty::to_word(const T& item) {
320 std::stringstream ss;
321 // Ruby-style inspect for objects without an overloaded operator<<
322 ss << "#<" << Util::demangle(typeid(item).name()) << ":" << address_of(std::addressof(item)) << ">";
323 return ss.str();
324}
325
335template <typename T>
337inline std::string Pretty::to_word(const T& item) {
338 return std::to_string(static_cast<std::uint_least32_t>(item));
339}
340
351template <typename T>
353inline std::string Pretty::to_word(const T& item) {
354 if (item == nullptr) {
355 return "nullptr";
356 }
357 return address_of(item);
358}
359
371template <typename T>
373inline std::string Pretty::to_word(const T& item) {
374 const auto& delimiters = pretty_print::delimiters<T, char>::values;
375 std::string word = delimiters.prefix != nullptr ? delimiters.prefix : "";
376 bool first = true;
377 auto append = [&](const auto& element) {
378 if (!first && delimiters.delimiter != nullptr) {
379 word += delimiters.delimiter;
380 }
381 word += to_word(element);
382 first = false;
383 };
384 if constexpr (std::ranges::input_range<const T>) {
385 for (const auto& element : item) {
386 // std::vector<bool> may hand out a proxy for each element, as libc++'s does; it is printed as the bool it holds.
387 if constexpr (std::same_as<std::remove_cv_t<std::ranges::range_value_t<const T>>, bool>) {
388 append(static_cast<bool>(element));
389 } else {
390 append(element);
391 }
392 }
393 } else {
394 std::apply([&](const auto&... elements) { (append(elements), ...); }, item);
395 }
396 if (delimiters.postfix != nullptr) {
397 word += delimiters.postfix;
398 }
399 return word;
400}
401
412template <typename T>
413 requires std::is_enum_v<T> && (!Util::is_streamable<T>)
414inline std::string Pretty::to_word(const T& item) {
415 using Widest = std::conditional_t<std::is_signed_v<std::underlying_type_t<T>>, long long, unsigned long long>;
416 return std::format("{}({})", Util::demangle(typeid(T).name()), static_cast<Widest>(std::to_underlying(item)));
417}
418
429template <typename T>
430inline std::string Pretty::to_word(const std::optional<T>& item) {
431 if (!item.has_value()) {
432 return "std::nullopt";
433 }
434 if constexpr (Util::is_optional_v<T>) {
435 return "std::optional(" + to_word(*item) + ")";
436 } else {
437 return to_word(*item);
438 }
439}
440
452template <typename A, typename E>
453inline std::string Pretty::to_word(const Matchers::MatcherBase<A, E>& matcher) {
454 std::string description = matcher.description();
455 if (description.empty()) {
456 return "[No description]";
457 }
458 return description;
459}
460
461template <typename T>
462inline std::string Pretty::to_word_type(const T& item) {
463 std::string word = to_word(item);
464 if constexpr (Util::is_streamable<T>) {
465 word += " : " + Util::demangle(typeid(T).name());
466 }
467 return word;
468}
469
470inline std::string Pretty::name_to_sentence(const std::string& n) const {
471 return split_words(name(n));
472}
473
474inline std::string Pretty::name(const std::string& name) const {
475 if (_name.empty()) {
476 return last(name, ':');
477 }
478 return _name;
479}
480
481inline std::string Pretty::split_words(const std::string& sym) {
482 return std::regex_replace(sym, std::regex("_"), " ");
483}
484
485inline std::string Pretty::underscore(const std::string& word) {
486 std::string str = std::regex_replace(word, std::regex("([A-Z]+)([A-Z][a-z])"), "$1_$2");
487 str = std::regex_replace(str, std::regex("([a-z\\d])([A-Z])"), "$1_$2");
488 str = std::regex_replace(str, std::regex("-"), "_");
489 std::ranges::transform(str, str.begin(), ::tolower);
490 return str;
491}
492
493// The last non-empty piece of s between delimiters, or an empty string when s has none.
494inline std::string Pretty::last(const std::string& s, const char delim) {
495 std::vector<std::string> elems;
496 std::stringstream ss(s);
497 std::string item;
498 while (getline(ss, item, delim)) {
499 if (!item.empty()) {
500 elems.push_back(item);
501 }
502 }
503 return elems.empty() ? std::string() : elems.back();
504}
505
506inline std::string Pretty::improve_hash_formatting(const std::string& inspect_string) {
507 return std::regex_replace(inspect_string, std::regex("(\\S)=>(\\S)"), "$1 => $2");
508}
509
517template <typename O>
518inline std::string Pretty::inspect_object(const O& o) {
519 if constexpr (Util::is_c_string<O>) {
520 // A C string is named by its type and printed quoted, or as nullptr when it is null.
521 constexpr std::string_view constness = std::is_const_v<std::remove_pointer_t<std::decay_t<O>>> ? "const " : "";
522 const std::string type = std::is_array_v<O> ? std::format("{}char [{}]", constness, std::extent_v<O>)
523 : std::format("{}char *", constness);
524 const auto text = string_view_of(o);
525 return text ? std::format("({}) => \"{}\"", type, *text) : std::format("({}) => nullptr", type);
526 } else {
527 return std::format("({}) => {}", Util::demangle(typeid(o).name()), to_word(o));
528 }
529}
530
538template <>
539inline std::string Pretty::inspect_object<std::string>(const std::string& o) {
540 return std::format("(std::string) => \"{}\"", o);
541}
542
543template <>
544inline std::string Pretty::inspect_object<std::string_view>(const std::string_view& o) {
545 return std::format("(std::string_view) => \"{}\"", o);
546}
547
548} // namespace CppSpec
the base class for all Matcher classes and objects
Definition matcher_base.hpp:77
virtual std::string description()
Get the description of the Matcher.
Definition matcher_base.hpp:200
Checks whether T is a C string: a pointer to char, const or not, or a char array, which decays to one...
Definition util.hpp:152
Checks whether T is a pointer to a character type other than char: signed char, unsigned char,...
Definition util.hpp:175
Checks whether T is a standard container, a std::span, a std::pair, a std::tuple or a built-in array:...
Definition pretty_matchers.hpp:72
Checks whether T can be streamed.
Definition util.hpp:120
Checks whether T is text that CppSpec::string_view_of() can view: a C string, or a type that converts...
Definition util.hpp:201
Checks whether T is a character type that std::ostream does not print as a character: wchar_t,...
Definition util.hpp:162
Checks whether T is a container, pair or tuple that Pretty prints element by element,...
Definition pretty_matchers.hpp:126
A helper base class that assists in pretty-printing various objects.
Definition pretty_matchers.hpp:144
static std::string to_word(const T &item)
Formats an object as a string when operator<< is available.
Definition pretty_matchers.hpp:273
static std::string address_of(const void *address)
Formats an address as 0x and lowercase hex digits, the same on every platform.
Definition pretty_matchers.hpp:204
static std::string to_sentence(const T &item)
Take a single object and format it as a sentance.
Definition pretty_matchers.hpp:255
Whether T prints differently through Pretty than through operator<<, so a container holding it is pri...
Definition pretty_matchers.hpp:97
Utility functions and classes.
constexpr bool is_optional_v
Checks whether T is a std::optional.
Definition util.hpp:189
std::string demangle(const char *name)
Definition util.hpp:77
constexpr std::optional< std::string_view > string_view_of(const T &text)
View text as a std::string_view, the one form the string matchers and the printer compare and print.
Definition util.hpp:337