summaryrefslogtreecommitdiff
path: root/Userland/Utilities/printf.cpp
blob: fe7a9b7f27fe3a0ce70ad961613fe5f3153ded13 (plain)
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
/*
 * Copyright (c) 2020, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Assertions.h>
#include <AK/PrintfImplementation.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/Types.h>
#include <LibMain/Main.h>
#include <stdio.h>
#include <unistd.h>

[[gnu::noreturn]] static void fail(const char* message)
{
    fputs("\e[31m", stderr);
    fputs(message, stderr);
    fputs("\e[0m\n", stderr);
    exit(1);
}

template<typename PutChFunc, typename ArgumentListRefT, template<typename T, typename U = ArgumentListRefT> typename NextArgument, typename CharType>
requires(IsSame<CharType, char>) struct PrintfImpl : public PrintfImplementation::PrintfImpl<PutChFunc, ArgumentListRefT, NextArgument, CharType> {
    ALWAYS_INLINE PrintfImpl(PutChFunc& putch, char*& bufptr, const int& nwritten)
        : PrintfImplementation::PrintfImpl<PutChFunc, ArgumentListRefT, NextArgument>(putch, bufptr, nwritten)
    {
    }

    ALWAYS_INLINE int format_q(const PrintfImplementation::ModifierState& state, ArgumentListRefT& ap) const
    {
        auto state_copy = state;
        auto str = NextArgument<const char*>()(ap);
        if (!str)
            str = "(null)";

        constexpr auto make_len_or_escape = [](auto str, bool mk_len, size_t field_width, auto putc) {
            unsigned len = 2;
            if (!mk_len)
                putc('"');

            for (size_t i = 0; str[i] && (mk_len ? true : (field_width >= len)); ++i) {
                auto ch = str[i];
                switch (ch) {
                case '"':
                case '$':
                case '\\':
                    ++len;
                    if (!mk_len)
                        putc('\\');
                }
                ++len;
                if (!mk_len)
                    putc(ch);
            }

            if (!mk_len)
                putc('"');

            return len;
        };

        auto len = make_len_or_escape(str, true, state_copy.field_width, [&](auto c) { this->m_putch(this->m_bufptr, c); });

        if (!state_copy.dot && (!state_copy.field_width || state_copy.field_width < len))
            state_copy.field_width = len;
        size_t pad_amount = state_copy.field_width > len ? state_copy.field_width - len : 0;

        if (!state_copy.left_pad) {
            for (size_t i = 0; i < pad_amount; ++i)
                this->m_putch(this->m_bufptr, ' ');
        }

        make_len_or_escape(str, false, state_copy.field_width, [&](auto c) { this->m_putch(this->m_bufptr, c); });

        if (state_copy.left_pad) {
            for (size_t i = 0; i < pad_amount; ++i)
                this->m_putch(this->m_bufptr, ' ');
        }

        return state_copy.field_width;
    }
};

template<typename T, typename V>
struct ArgvNextArgument {
    ALWAYS_INLINE T operator()(V) const
    {
        static_assert(sizeof(V) != sizeof(V), "Base instantiated");
        return declval<T>();
    }
};

template<typename V>
struct ArgvNextArgument<char*, V> {
    ALWAYS_INLINE char* operator()(V arg) const
    {
        if (arg.argc == 0)
            fail("Not enough arguments");

        auto result = *arg.argv++;
        --arg.argc;
        return result;
    }
};

template<typename V>
struct ArgvNextArgument<const char*, V> {
    ALWAYS_INLINE const char* operator()(V arg) const
    {
        if (arg.argc == 0)
            return "";

        auto result = *arg.argv++;
        --arg.argc;
        return result;
    }
};

template<typename V>
struct ArgvNextArgument<const wchar_t*, V> {
    ALWAYS_INLINE const wchar_t* operator()(V arg) const
    {
        if (arg.argc == 0)
            return L"";

        return L"";
    }
};

template<typename V>
struct ArgvNextArgument<int, V> {
    ALWAYS_INLINE int operator()(V arg) const
    {
        if (arg.argc == 0)
            return 0;

        auto result = *arg.argv++;
        --arg.argc;
        return atoi(result);
    }
};

template<typename V>
struct ArgvNextArgument<unsigned, V> {
    ALWAYS_INLINE unsigned operator()(V arg) const
    {
        if (arg.argc == 0)
            return 0;

        auto result = *arg.argv++;
        --arg.argc;
        return strtoul(result, nullptr, 10);
    }
};

template<typename V>
struct ArgvNextArgument<i64, V> {
    ALWAYS_INLINE i64 operator()(V arg) const
    {
        if (arg.argc == 0)
            return 0;

        auto result = *arg.argv++;
        --arg.argc;
        return strtoll(result, nullptr, 10);
    }
};

template<typename V>
struct ArgvNextArgument<u64, V> {
    ALWAYS_INLINE u64 operator()(V arg) const
    {
        if (arg.argc == 0)
            return 0;

        auto result = *arg.argv++;
        --arg.argc;
        return strtoull(result, nullptr, 10);
    }
};

template<typename V>
struct ArgvNextArgument<double, V> {
    ALWAYS_INLINE double operator()(V arg) const
    {
        if (arg.argc == 0)
            return 0;

        auto result = *arg.argv++;
        --arg.argc;
        return strtod(result, nullptr);
    }
};

template<typename V>
struct ArgvNextArgument<int*, V> {
    ALWAYS_INLINE int* operator()(V) const
    {
        VERIFY_NOT_REACHED();
        return nullptr;
    }
};

struct ArgvWithCount {
    char**& argv;
    int& argc;
};

static String handle_escapes(const char* string)
{
    StringBuilder builder;
    for (auto c = *string; c; c = *++string) {
        if (c == '\\') {
            if (string[1]) {
                switch (c = *++string) {
                case '\\':
                case '"':
                    builder.append(c);
                    break;
                case 'a':
                    builder.append('\a');
                    break;
                case 'b':
                    builder.append('\b');
                    break;
                case 'c':
                    return builder.build();
                case 'e':
                    builder.append('\e');
                    break;
                case 'f':
                    builder.append('\f');
                    break;
                case 'n':
                    builder.append('\n');
                    break;
                case 'r':
                    builder.append('\r');
                    break;
                case 't':
                    builder.append('\t');
                    break;
                case 'v':
                    builder.append('\v');
                    break;
                case 'x':
                    fail("Unsupported escape '\\x'");
                case 'u':
                    fail("Unsupported escape '\\u'");
                case 'U':
                    fail("Unsupported escape '\\U'");
                default:
                    builder.append(c);
                }
            } else {
                builder.append(c);
            }
        } else {
            builder.append(c);
        }
    }

    return builder.build();
}

ErrorOr<int> serenity_main(Main::Arguments arguments)
{
    if (arguments.argc < 2)
        return Error::from_errno(EINVAL);

    auto argc = arguments.argc;
    auto argv = arguments.argv;

    ++argv;
    String format = handle_escapes(*(argv++));
    auto format_string = format.characters();

    argc -= 2;

    ArgvWithCount arg { argv, argc };

    auto putch = [](auto*, auto ch) {
        putchar(ch);
    };

    auto previous_argc = 0;
    do {
        previous_argc = argc;
        PrintfImplementation::printf_internal<decltype(putch), PrintfImpl, ArgvWithCount, ArgvNextArgument, char>(putch, nullptr, format_string, arg);
    } while (argc && previous_argc != argc);

    return 0;
}