1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
|
/*
* Copyright (c) 2020, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/CheckedFormatString.h>
#include <AK/AllOf.h>
#include <AK/AnyOf.h>
#include <AK/Array.h>
#include <AK/Error.h>
#include <AK/FixedPoint.h>
#include <AK/Forward.h>
#include <AK/Optional.h>
#include <AK/StringView.h>
#ifndef KERNEL
# include <stdio.h>
# include <string.h>
#endif
namespace AK {
class TypeErasedFormatParams;
class FormatParser;
class FormatBuilder;
template<typename T, typename = void>
struct Formatter {
using __no_formatter_defined = void;
};
template<typename T, typename = void>
inline constexpr bool HasFormatter = true;
template<typename T>
inline constexpr bool HasFormatter<T, typename Formatter<T>::__no_formatter_defined> = false;
constexpr size_t max_format_arguments = 256;
struct TypeErasedParameter {
enum class Type {
UInt8,
UInt16,
UInt32,
UInt64,
Int8,
Int16,
Int32,
Int64,
Custom
};
template<size_t size, bool is_unsigned>
static consteval Type get_type_from_size()
{
if constexpr (is_unsigned) {
if constexpr (size == 1)
return Type::UInt8;
if constexpr (size == 2)
return Type::UInt16;
if constexpr (size == 4)
return Type::UInt32;
if constexpr (size == 8)
return Type::UInt64;
} else {
if constexpr (size == 1)
return Type::Int8;
if constexpr (size == 2)
return Type::Int16;
if constexpr (size == 4)
return Type::Int32;
if constexpr (size == 8)
return Type::Int64;
}
VERIFY_NOT_REACHED();
}
template<typename T>
static consteval Type get_type()
{
if constexpr (IsIntegral<T>)
return get_type_from_size<sizeof(T), IsUnsigned<T>>();
else
return Type::Custom;
}
template<typename Visitor>
constexpr auto visit(Visitor&& visitor) const
{
switch (type) {
case TypeErasedParameter::Type::UInt8:
return visitor(*static_cast<u8 const*>(value));
case TypeErasedParameter::Type::UInt16:
return visitor(*static_cast<u16 const*>(value));
case TypeErasedParameter::Type::UInt32:
return visitor(*static_cast<u32 const*>(value));
case TypeErasedParameter::Type::UInt64:
return visitor(*static_cast<u64 const*>(value));
case TypeErasedParameter::Type::Int8:
return visitor(*static_cast<i8 const*>(value));
case TypeErasedParameter::Type::Int16:
return visitor(*static_cast<i16 const*>(value));
case TypeErasedParameter::Type::Int32:
return visitor(*static_cast<i32 const*>(value));
case TypeErasedParameter::Type::Int64:
return visitor(*static_cast<i64 const*>(value));
default:
TODO();
}
}
constexpr size_t to_size() const
{
return visit([]<typename T>(T value) {
if constexpr (sizeof(T) > sizeof(size_t))
VERIFY(value < NumericLimits<size_t>::max());
if constexpr (IsSigned<T>)
VERIFY(value > 0);
return static_cast<size_t>(value);
});
}
// FIXME: Getters and setters.
void const* value;
Type type;
ErrorOr<void> (*formatter)(TypeErasedFormatParams&, FormatBuilder&, FormatParser&, void const* value);
};
class FormatBuilder {
public:
enum class Align {
Default,
Left,
Center,
Right,
};
enum class SignMode {
OnlyIfNeeded,
Always,
Reserved,
Default = OnlyIfNeeded,
};
explicit FormatBuilder(StringBuilder& builder)
: m_builder(builder)
{
}
ErrorOr<void> put_padding(char fill, size_t amount);
ErrorOr<void> put_literal(StringView value);
ErrorOr<void> put_string(
StringView value,
Align align = Align::Left,
size_t min_width = 0,
size_t max_width = NumericLimits<size_t>::max(),
char fill = ' ');
ErrorOr<void> put_u64(
u64 value,
u8 base = 10,
bool prefix = false,
bool upper_case = false,
bool zero_pad = false,
Align align = Align::Right,
size_t min_width = 0,
char fill = ' ',
SignMode sign_mode = SignMode::OnlyIfNeeded,
bool is_negative = false);
ErrorOr<void> put_i64(
i64 value,
u8 base = 10,
bool prefix = false,
bool upper_case = false,
bool zero_pad = false,
Align align = Align::Right,
size_t min_width = 0,
char fill = ' ',
SignMode sign_mode = SignMode::OnlyIfNeeded);
ErrorOr<void> put_fixed_point(
i64 integer_value,
u64 fraction_value,
u64 fraction_one,
u8 base = 10,
bool upper_case = false,
bool zero_pad = false,
Align align = Align::Right,
size_t min_width = 0,
size_t precision = 6,
char fill = ' ',
SignMode sign_mode = SignMode::OnlyIfNeeded);
#ifndef KERNEL
ErrorOr<void> put_f80(
long double value,
u8 base = 10,
bool upper_case = false,
Align align = Align::Right,
size_t min_width = 0,
size_t precision = 6,
char fill = ' ',
SignMode sign_mode = SignMode::OnlyIfNeeded);
ErrorOr<void> put_f64(
double value,
u8 base = 10,
bool upper_case = false,
bool zero_pad = false,
Align align = Align::Right,
size_t min_width = 0,
size_t precision = 6,
char fill = ' ',
SignMode sign_mode = SignMode::OnlyIfNeeded);
#endif
ErrorOr<void> put_hexdump(
ReadonlyBytes,
size_t width,
char fill = ' ');
StringBuilder const& builder() const
{
return m_builder;
}
StringBuilder& builder() { return m_builder; }
private:
StringBuilder& m_builder;
};
class TypeErasedFormatParams {
public:
Span<const TypeErasedParameter> parameters() const { return m_parameters; }
void set_parameters(Span<const TypeErasedParameter> parameters) { m_parameters = parameters; }
size_t take_next_index() { return m_next_index++; }
private:
Span<const TypeErasedParameter> m_parameters;
size_t m_next_index { 0 };
};
template<typename T>
ErrorOr<void> __format_value(TypeErasedFormatParams& params, FormatBuilder& builder, FormatParser& parser, void const* value)
{
Formatter<T> formatter;
formatter.parse(params, parser);
return formatter.format(builder, *static_cast<const T*>(value));
}
template<typename... Parameters>
class VariadicFormatParams : public TypeErasedFormatParams {
public:
static_assert(sizeof...(Parameters) <= max_format_arguments);
explicit VariadicFormatParams(Parameters const&... parameters)
: m_data({ TypeErasedParameter { ¶meters, TypeErasedParameter::get_type<Parameters>(), __format_value<Parameters> }... })
{
this->set_parameters(m_data);
}
private:
Array<TypeErasedParameter, sizeof...(Parameters)> m_data;
};
// We use the same format for most types for consistency. This is taken directly from
// std::format. One difference is that we are not counting the width or sign towards the
// total width when calculating zero padding for numbers.
// https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification
struct StandardFormatter {
enum class Mode {
Default,
Binary,
BinaryUppercase,
Decimal,
Octal,
Hexadecimal,
HexadecimalUppercase,
Character,
String,
Pointer,
Float,
Hexfloat,
HexfloatUppercase,
HexDump,
};
FormatBuilder::Align m_align = FormatBuilder::Align::Default;
FormatBuilder::SignMode m_sign_mode = FormatBuilder::SignMode::OnlyIfNeeded;
Mode m_mode = Mode::Default;
bool m_alternative_form = false;
char m_fill = ' ';
bool m_zero_pad = false;
Optional<size_t> m_width;
Optional<size_t> m_precision;
void parse(TypeErasedFormatParams&, FormatParser&);
};
template<Integral T>
struct Formatter<T> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(move(formatter))
{
}
ErrorOr<void> format(FormatBuilder&, T);
};
template<>
struct Formatter<StringView> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(move(formatter))
{
}
ErrorOr<void> format(FormatBuilder&, StringView);
};
template<typename T, size_t inline_capacity>
requires(HasFormatter<T>) struct Formatter<Vector<T, inline_capacity>> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(move(formatter))
{
}
ErrorOr<void> format(FormatBuilder& builder, Vector<T> value)
{
if (m_mode == Mode::Pointer) {
Formatter<FlatPtr> formatter { *this };
TRY(formatter.format(builder, reinterpret_cast<FlatPtr>(value.data())));
return {};
}
if (m_sign_mode != FormatBuilder::SignMode::Default)
VERIFY_NOT_REACHED();
if (m_alternative_form)
VERIFY_NOT_REACHED();
if (m_zero_pad)
VERIFY_NOT_REACHED();
if (m_mode != Mode::Default)
VERIFY_NOT_REACHED();
if (m_width.has_value() && m_precision.has_value())
VERIFY_NOT_REACHED();
m_width = m_width.value_or(0);
m_precision = m_precision.value_or(NumericLimits<size_t>::max());
Formatter<T> content_fmt;
TRY(builder.put_literal("[ "sv));
bool first = true;
for (auto& content : value) {
if (!first) {
TRY(builder.put_literal(", "sv));
content_fmt = Formatter<T> {};
}
first = false;
TRY(content_fmt.format(builder, content));
}
TRY(builder.put_literal(" ]"sv));
return {};
}
};
template<>
struct Formatter<ReadonlyBytes> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, ReadonlyBytes value)
{
if (m_mode == Mode::Pointer) {
Formatter<FlatPtr> formatter { *this };
return formatter.format(builder, reinterpret_cast<FlatPtr>(value.data()));
}
if (m_mode == Mode::Default || m_mode == Mode::HexDump) {
m_mode = Mode::HexDump;
return Formatter<StringView>::format(builder, value);
}
return Formatter<StringView>::format(builder, value);
}
};
template<>
struct Formatter<Bytes> : Formatter<ReadonlyBytes> {
};
// FIXME: Printing raw char pointers is inherently dangerous. Remove this and
// its users and prefer StringView over it.
template<>
struct Formatter<char const*> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, char const* value)
{
if (m_mode == Mode::Pointer) {
Formatter<FlatPtr> formatter { *this };
return formatter.format(builder, reinterpret_cast<FlatPtr>(value));
}
return Formatter<StringView>::format(builder, value != nullptr ? StringView { value, __builtin_strlen(value) } : "(null)"sv);
}
};
template<>
struct Formatter<char*> : Formatter<char const*> {
};
template<size_t Size>
struct Formatter<char[Size]> : Formatter<char const*> {
};
template<size_t Size>
struct Formatter<unsigned char[Size]> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, unsigned char const* value)
{
if (m_mode == Mode::Pointer) {
Formatter<FlatPtr> formatter { *this };
return formatter.format(builder, reinterpret_cast<FlatPtr>(value));
}
return Formatter<StringView>::format(builder, { value, Size });
}
};
template<>
struct Formatter<String> : Formatter<StringView> {
};
template<>
struct Formatter<FlyString> : Formatter<StringView> {
};
template<typename T>
struct Formatter<T*> : StandardFormatter {
ErrorOr<void> format(FormatBuilder& builder, T* value)
{
if (m_mode == Mode::Default)
m_mode = Mode::Pointer;
Formatter<FlatPtr> formatter { *this };
return formatter.format(builder, reinterpret_cast<FlatPtr>(value));
}
};
template<>
struct Formatter<char> : StandardFormatter {
ErrorOr<void> format(FormatBuilder&, char);
};
template<>
struct Formatter<wchar_t> : StandardFormatter {
ErrorOr<void> format(FormatBuilder& builder, wchar_t);
};
template<>
struct Formatter<bool> : StandardFormatter {
ErrorOr<void> format(FormatBuilder&, bool);
};
#ifndef KERNEL
template<>
struct Formatter<float> : StandardFormatter {
ErrorOr<void> format(FormatBuilder&, float value);
};
template<>
struct Formatter<double> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(formatter)
{
}
ErrorOr<void> format(FormatBuilder&, double);
};
template<>
struct Formatter<long double> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(formatter)
{
}
ErrorOr<void> format(FormatBuilder&, long double value);
};
#endif
template<size_t precision, typename Underlying>
struct Formatter<FixedPoint<precision, Underlying>> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(formatter)
{
}
ErrorOr<void> format(FormatBuilder& builder, FixedPoint<precision, Underlying> value)
{
u8 base;
bool upper_case;
if (m_mode == Mode::Default || m_mode == Mode::Float) {
base = 10;
upper_case = false;
} else if (m_mode == Mode::Hexfloat) {
base = 16;
upper_case = false;
} else if (m_mode == Mode::HexfloatUppercase) {
base = 16;
upper_case = true;
} else {
VERIFY_NOT_REACHED();
}
m_width = m_width.value_or(0);
m_precision = m_precision.value_or(6);
i64 integer = value.ltrunk();
constexpr u64 one = static_cast<Underlying>(1) << precision;
u64 fraction_raw = value.raw() & (one - 1);
return builder.put_fixed_point(integer, fraction_raw, one, base, upper_case, m_zero_pad, m_align, m_width.value(), m_precision.value(), m_fill, m_sign_mode);
}
};
template<>
struct Formatter<std::nullptr_t> : Formatter<FlatPtr> {
ErrorOr<void> format(FormatBuilder& builder, std::nullptr_t)
{
if (m_mode == Mode::Default)
m_mode = Mode::Pointer;
return Formatter<FlatPtr>::format(builder, 0);
}
};
ErrorOr<void> vformat(StringBuilder&, StringView fmtstr, TypeErasedFormatParams&);
#ifndef KERNEL
void vout(FILE*, StringView fmtstr, TypeErasedFormatParams&, bool newline = false);
template<typename... Parameters>
void out(FILE* file, CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
{
VariadicFormatParams variadic_format_params { parameters... };
vout(file, fmtstr.view(), variadic_format_params);
}
template<typename... Parameters>
void outln(FILE* file, CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
{
VariadicFormatParams variadic_format_params { parameters... };
vout(file, fmtstr.view(), variadic_format_params, true);
}
inline void outln(FILE* file) { fputc('\n', file); }
template<typename... Parameters>
void out(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters) { out(stdout, move(fmtstr), parameters...); }
template<typename... Parameters>
void outln(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters) { outln(stdout, move(fmtstr), parameters...); }
inline void outln() { outln(stdout); }
# define outln_if(flag, fmt, ...) \
do { \
if constexpr (flag) \
outln(fmt, ##__VA_ARGS__); \
} while (0)
template<typename... Parameters>
void warn(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
{
out(stderr, move(fmtstr), parameters...);
}
template<typename... Parameters>
void warnln(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters) { outln(stderr, move(fmtstr), parameters...); }
inline void warnln() { outln(stderr); }
# define warnln_if(flag, fmt, ...) \
do { \
if constexpr (flag) \
warnln(fmt, ##__VA_ARGS__); \
} while (0)
#endif
void vdbgln(StringView fmtstr, TypeErasedFormatParams&);
template<typename... Parameters>
void dbgln(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
{
VariadicFormatParams variadic_format_params { parameters... };
vdbgln(fmtstr.view(), variadic_format_params);
}
inline void dbgln() { dbgln(""); }
void set_debug_enabled(bool);
#ifdef KERNEL
void vdmesgln(StringView fmtstr, TypeErasedFormatParams&);
template<typename... Parameters>
void dmesgln(CheckedFormatString<Parameters...>&& fmt, Parameters const&... parameters)
{
VariadicFormatParams variadic_format_params { parameters... };
vdmesgln(fmt.view(), variadic_format_params);
}
void v_critical_dmesgln(StringView fmtstr, TypeErasedFormatParams&);
// be very careful to not cause any allocations here, since we could be in
// a very unstable situation
template<typename... Parameters>
void critical_dmesgln(CheckedFormatString<Parameters...>&& fmt, Parameters const&... parameters)
{
VariadicFormatParams variadic_format_params { parameters... };
v_critical_dmesgln(fmt.view(), variadic_format_params);
}
#endif
template<typename T>
class FormatIfSupported {
public:
explicit FormatIfSupported(const T& value)
: m_value(value)
{
}
const T& value() const { return m_value; }
private:
const T& m_value;
};
template<typename T, bool Supported = false>
struct __FormatIfSupported : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, FormatIfSupported<T> const&)
{
return Formatter<StringView>::format(builder, "?"sv);
}
};
template<typename T>
struct __FormatIfSupported<T, true> : Formatter<T> {
ErrorOr<void> format(FormatBuilder& builder, FormatIfSupported<T> const& value)
{
return Formatter<T>::format(builder, value.value());
}
};
template<typename T>
struct Formatter<FormatIfSupported<T>> : __FormatIfSupported<T, HasFormatter<T>> {
};
// This is a helper class, the idea is that if you want to implement a formatter you can inherit
// from this class to "break down" the formatting.
struct FormatString {
};
template<>
struct Formatter<FormatString> : Formatter<StringView> {
template<typename... Parameters>
ErrorOr<void> format(FormatBuilder& builder, StringView fmtstr, Parameters const&... parameters)
{
VariadicFormatParams variadic_format_params { parameters... };
return vformat(builder, fmtstr, variadic_format_params);
}
ErrorOr<void> vformat(FormatBuilder& builder, StringView fmtstr, TypeErasedFormatParams& params);
};
template<>
struct Formatter<Error> : Formatter<FormatString> {
ErrorOr<void> format(FormatBuilder& builder, Error const& error)
{
#if defined(__serenity__) && defined(KERNEL)
if (error.is_errno())
return Formatter<FormatString>::format(builder, "Error(errno={})"sv, error.code());
return Formatter<FormatString>::format(builder, "Error({})"sv, error.string_literal());
#else
if (error.is_syscall())
return Formatter<FormatString>::format(builder, "{}: {} (errno={})"sv, error.string_literal(), strerror(error.code()), error.code());
if (error.is_errno())
return Formatter<FormatString>::format(builder, "{} (errno={})"sv, strerror(error.code()), error.code());
return Formatter<FormatString>::format(builder, "{}"sv, error.string_literal());
#endif
}
};
template<typename T, typename ErrorType>
struct Formatter<ErrorOr<T, ErrorType>> : Formatter<FormatString> {
ErrorOr<void> format(FormatBuilder& builder, ErrorOr<T, ErrorType> const& error_or)
{
if (error_or.is_error())
return Formatter<FormatString>::format(builder, "{}"sv, error_or.error());
return Formatter<FormatString>::format(builder, "{{{}}}"sv, error_or.value());
}
};
} // namespace AK
#ifdef KERNEL
using AK::critical_dmesgln;
using AK::dmesgln;
#else
using AK::out;
using AK::outln;
using AK::warn;
using AK::warnln;
#endif
using AK::dbgln;
using AK::CheckedFormatString;
using AK::FormatIfSupported;
using AK::FormatString;
#define dbgln_if(flag, fmt, ...) \
do { \
if constexpr (flag) \
dbgln(fmt, ##__VA_ARGS__); \
} while (0)
|