summaryrefslogtreecommitdiffstats
path: root/src/third-party/scnlib/include/scn/detail/parse_context.h
blob: 91d668754f4251666762efb03a37864f7798a10f (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
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
// Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file is a part of scnlib:
//     https://github.com/eliaskosunen/scnlib

#ifndef SCN_DETAIL_PARSE_CONTEXT_H
#define SCN_DETAIL_PARSE_CONTEXT_H

#include "../util/expected.h"
#include "locale.h"

namespace scn {
    SCN_BEGIN_NAMESPACE

    namespace detail {
        class parse_context_base {
        public:
            SCN_CONSTEXPR14 std::ptrdiff_t next_arg_id()
            {
                return m_next_arg_id >= 0 ? m_next_arg_id++ : 0;
            }
            SCN_CONSTEXPR14 bool check_arg_id(std::ptrdiff_t)
            {
                if (m_next_arg_id > 0) {
                    return false;
                }
                m_next_arg_id = -1;
                return true;
            }

        protected:
            parse_context_base() = default;

            std::ptrdiff_t m_next_arg_id{0};
        };
    }  // namespace detail

    SCN_CLANG_PUSH
    SCN_CLANG_IGNORE("-Wpadded")

    template <typename CharT>
    class basic_parse_context : public detail::parse_context_base {
    public:
        using char_type = CharT;
        using locale_type = basic_locale_ref<CharT>;
        using string_view_type = basic_string_view<char_type>;
        using iterator = typename string_view_type::iterator;

        constexpr basic_parse_context(basic_string_view<char_type> f,
                                      locale_type& loc)
            : m_str(f), m_locale(loc)
        {
        }

        /**
         * Returns `true`, if `next_char()` is a whitespace character according
         * to the static locale. This means, that `skip_range_whitespace()`
         * should be called on the source range.
         */
        bool should_skip_ws()
        {
            bool skip = false;
            while (*this && m_locale.get_static().is_space(next_char())) {
                skip = true;
                advance_char();
            }
            return skip;
        }
        /**
         * Returns `true`, if a character equal to `next_char()` should be read
         * from the source range.
         *
         * If `*this` currently points to an escaped
         * brace character `"{{"` or `"}}"`, skips the first brace, so that
         * after this function is called, `next_char()` returns the character
         * that should be read.
         */
        bool should_read_literal()
        {
            const auto brace = detail::ascii_widen<char_type>('{');
            if (next_char() != brace) {
                if (next_char() == detail::ascii_widen<char_type>('}')) {
                    advance_char();
                }
                return true;
            }
            if (SCN_UNLIKELY(m_str.size() > 1 &&
                             *(m_str.begin() + 1) == brace)) {
                advance_char();
                return true;
            }
            return false;
        }
        /**
         * Returns `true` if `ch` is equal to `next_char()`
         */
        SCN_NODISCARD constexpr bool check_literal(char_type ch) const
        {
            return ch == next_char();
        }
        /**
         * Returns `true` if the code units contained in `ch` are equal to the
         * code units starting from `pctx.begin()`. If `chars_left() <
         * ch.size()`, returns `false`.
         */
        SCN_NODISCARD SCN_CONSTEXPR14 bool check_literal(
            span<const char_type> ch) const
        {
            if (chars_left() < ch.size()) {
                return false;
            }
            for (size_t i = 0; i < ch.size(); ++i) {
                if (ch[i] != m_str[i]) {
                    return false;
                }
            }
            return true;
        }
        /**
         * Returns `true` if `cp` is equal to the value returned by `next_cp()`.
         * If `next_cp()` errored, returns that error
         * (`error::invalid_encoding`).
         */
        SCN_NODISCARD SCN_CONSTEXPR14 expected<bool> check_literal_cp(
            code_point cp) const
        {
            auto next = next_cp();
            if (!next) {
                return next.error();
            }
            return cp == next.value();
        }

        /**
         * Returns `true` if there are characters left in `*this`.
         */
        constexpr bool good() const
        {
            return !m_str.empty();
        }
        constexpr explicit operator bool() const
        {
            return good();
        }

        /**
         * Returns the next character (= code unit) in `*this`.
         * `good()` must be `true`.
         */
        constexpr char_type next_char() const
        {
            return m_str.front();
        }
        /**
         * Returns the next code point in `*this`.
         * If the code point is encoded incorrectly, returns
         * `error::invalid_encoding`.
         */
        SCN_NODISCARD SCN_CONSTEXPR14 expected<code_point> next_cp() const
        {
            code_point cp{};
            auto it = parse_code_point(m_str.begin(), m_str.end(), cp);
            if (!it) {
                return it.error();
            }
            return {cp};
        }

        /**
         * Returns the number of chars (= code units) left in `*this`.
         */
        constexpr std::size_t chars_left() const noexcept
        {
            return m_str.size();
        }
        /**
         * Returns the number of code points left in `*this`. If `*this`
         * contains invalid encoding, returns `error::invalid_encoding`.
         */
        SCN_NODISCARD SCN_CONSTEXPR14 expected<std::size_t> cp_left()
            const noexcept
        {
            auto d = code_point_distance(m_str.begin(), m_str.end());
            if (!d) {
                return d.error();
            }
            return {static_cast<std::size_t>(d.value())};
        }

        /**
         * Advances `*this` by `n` characters (= code units). `*this` must have
         * at least `n` characters left.
         */
        SCN_CONSTEXPR14 void advance_char(std::ptrdiff_t n = 1) noexcept
        {
            SCN_EXPECT(chars_left() >= static_cast<std::size_t>(n));
            m_str.remove_prefix(static_cast<std::size_t>(n));
        }
        /**
         * Advances `*this` by a single code point. If the code point is encoded
         * incorrectly, returns `error::invalid_encoding`.
         */
        SCN_NODISCARD SCN_CONSTEXPR14 error advance_cp() noexcept
        {
            code_point cp{};
            auto it = parse_code_point(m_str.begin(), m_str.end(), cp);
            if (!it) {
                return it.error();
            }
            m_str.remove_prefix(
                static_cast<size_t>(it.value() - m_str.begin()));
            return {};
        }

        /**
         * Returns `true`, if `*this` has over `n` characters (= code units)
         * left, so that `peek_char()` with the same `n` parameter can be
         * called.
         */
        constexpr bool can_peek_char(std::size_t n = 1) const noexcept
        {
            return chars_left() > n;
        }

        /**
         * Returns the character (= code unit) `n` characters past the current
         * character, so that `peek_char(0)` is equivalent to `next_char()`.
         * `n <= chars_left()` must be `true`.
         */
        SCN_CONSTEXPR14 char_type peek_char(std::size_t n = 1) const noexcept
        {
            SCN_EXPECT(n <= chars_left());
            return m_str[n];
        }
        /**
         * Returns the code point past the current code point (`next_cp()`).
         *
         * If there is no code point to peek (the current code point is the last
         * one in `*this`), returns `error::end_of_range`.
         * If `*this` contains invalid encoding, returns
         * `error::invalid_encoding`.
         */
        SCN_NODISCARD SCN_CONSTEXPR14 expected<code_point> peek_cp()
            const noexcept
        {
            if (m_str.size() < 2) {
                return error{error::end_of_range,
                             "End of format string, cannot peek"};
            }

            code_point cp{};
            auto it = parse_code_point(m_str.begin(), m_str.end(), cp);
            if (!it) {
                return it.error();
            }
            if (it.value() == m_str.end()) {
                return error{error::end_of_range,
                             "End of format string, cannot peek"};
            }

            it = parse_code_point(it.value(), m_str.end(), cp);
            if (!it) {
                return it.error();
            }
            return {cp};
        }

        SCN_CONSTEXPR14 iterator begin() const noexcept
        {
            return m_str.begin();
        }
        SCN_CONSTEXPR14 iterator end() const noexcept
        {
            return m_str.end();
        }

        /**
         * Returns `true`, if `next_char() == '{'`
         */
        SCN_CONSTEXPR14 bool check_arg_begin() const
        {
            SCN_EXPECT(good());
            return next_char() == detail::ascii_widen<char_type>('{');
        }
        /**
         * Returns `true`, if `next_char() == '}'`
         */
        SCN_CONSTEXPR14 bool check_arg_end() const
        {
            SCN_EXPECT(good());
            return next_char() == detail::ascii_widen<char_type>('}');
        }

        using parse_context_base::check_arg_id;
        SCN_CONSTEXPR14 void check_arg_id(basic_string_view<CharT>) {}

        SCN_CONSTEXPR14 void arg_begin() const noexcept {}
        SCN_CONSTEXPR14 void arg_end() const noexcept {}

        SCN_CONSTEXPR14 void arg_handled() const noexcept {}

        const locale_type& locale() const
        {
            return m_locale;
        }

        /**
         * Parse `*this` using `s`
         */
        template <typename Scanner>
        error parse(Scanner& s)
        {
            return s.parse(*this);
        }

        bool has_arg_id()
        {
            SCN_EXPECT(good());
            if (m_str.size() == 1) {
                return true;
            }
            if (m_str[1] == detail::ascii_widen<char_type>('}')) {
                advance_char();
                return false;
            }
            if (m_str[1] == detail::ascii_widen<char_type>(':')) {
                advance_char(2);
                return false;
            }
            return true;
        }
        expected<string_view_type> parse_arg_id()
        {
            SCN_EXPECT(good());
            advance_char();
            if (SCN_UNLIKELY(!good())) {
                return error(error::invalid_format_string,
                             "Unexpected end of format argument");
            }
            auto it = m_str.begin();
            for (std::ptrdiff_t i = 0; good(); ++i, (void)advance_char()) {
                if (check_arg_end()) {
                    return string_view_type{
                        it,
                        static_cast<typename string_view_type::size_type>(i)};
                }
                if (next_char() == detail::ascii_widen<char_type>(':')) {
                    advance_char();
                    return string_view_type{
                        it,
                        static_cast<typename string_view_type::size_type>(i)};
                }
            }
            return error(error::invalid_format_string,
                         "Unexpected end of format argument");
        }

    private:
        string_view_type m_str;
        locale_type& m_locale;
    };

    template <typename CharT>
    class basic_empty_parse_context : public detail::parse_context_base {
    public:
        using char_type = CharT;
        using locale_type = basic_locale_ref<char_type>;
        using string_view_type = basic_string_view<char_type>;

        constexpr basic_empty_parse_context(int args,
                                            locale_type& loc,
                                            bool localized = false)
            : m_locale(loc), m_args_left(args), m_localized(localized)
        {
        }

        SCN_CONSTEXPR14 bool should_skip_ws()
        {
            if (m_should_skip_ws) {
                m_should_skip_ws = false;
                return true;
            }
            return false;
        }
        constexpr bool should_read_literal() const
        {
            return false;
        }
        constexpr bool check_literal(char_type) const
        {
            return false;
        }
        constexpr bool check_literal(span<const char_type>) const
        {
            return false;
        }
        constexpr bool check_literal_cp(code_point) const
        {
            return false;
        }

        constexpr bool good() const
        {
            return m_args_left > 0;
        }
        constexpr explicit operator bool() const
        {
            return good();
        }

        SCN_CONSTEXPR14 void advance_char(std::ptrdiff_t = 1) const noexcept {}
        SCN_CONSTEXPR14 error advance_cp() const noexcept
        {
            return {};
        }

        char_type next_char() const
        {
            SCN_EXPECT(false);
            SCN_UNREACHABLE;
        }
        expected<std::pair<code_point, std::ptrdiff_t>> next_cp() const
        {
            SCN_EXPECT(false);
            SCN_UNREACHABLE;
        }

        std::size_t chars_left() const noexcept
        {
            SCN_EXPECT(false);
            SCN_UNREACHABLE;
        }
        std::size_t cp_left() const noexcept
        {
            SCN_EXPECT(false);
            SCN_UNREACHABLE;
        }

        constexpr bool can_peek_char() const noexcept
        {
            return false;
        }
        constexpr bool can_peek_cp() const noexcept
        {
            return false;
        }

        char_type peek_char(std::ptrdiff_t = 1) const noexcept
        {
            SCN_EXPECT(false);
            SCN_UNREACHABLE;
        }
        expected<code_point> peek_cp() const noexcept
        {
            SCN_EXPECT(false);
            SCN_UNREACHABLE;
        }

        constexpr bool check_arg_begin() const
        {
            return true;
        }
        constexpr bool check_arg_end() const
        {
            return true;
        }

        using parse_context_base::check_arg_id;
        SCN_CONSTEXPR14 void check_arg_id(basic_string_view<CharT>) {}

        SCN_CONSTEXPR14 void arg_begin() const noexcept {}
        SCN_CONSTEXPR14 void arg_end() const noexcept {}

        SCN_CONSTEXPR14 void arg_handled()
        {
            m_should_skip_ws = true;
            --m_args_left;
        }

        const locale_type& locale() const
        {
            return m_locale;
        }

        template <typename Scanner>
        SCN_CONSTEXPR14 error parse(Scanner& s) const
        {
            if (m_localized) {
                s.make_localized();
            }
            return {};
        }

        constexpr bool has_arg_id() const
        {
            return false;
        }
        SCN_CONSTEXPR14 expected<string_view_type> parse_arg_id() const
        {
            SCN_EXPECT(good());
            return string_view_type{};
        }

        void reset_args_left(int n)
        {
            m_args_left = n;
            parse_context_base::m_next_arg_id = 0;
            m_should_skip_ws = false;
        }

    private:
        locale_type& m_locale;
        int m_args_left;
        bool m_localized;
        bool m_should_skip_ws{false};
    };

    namespace detail {
        template <typename CharT>
        basic_parse_context<CharT> make_parse_context_impl(
            basic_string_view<CharT> f,
            basic_locale_ref<CharT>& loc,
            bool)
        {
            return {f, loc};
        }
        template <typename CharT>
        basic_empty_parse_context<CharT> make_parse_context_impl(
            int i,
            basic_locale_ref<CharT>& loc,
            bool localized)
        {
            return {i, loc, localized};
        }

        template <typename CharT>
        struct parse_context_template_for_format<basic_string_view<CharT>> {
            template <typename T>
            using type = basic_parse_context<T>;
        };
        template <>
        struct parse_context_template_for_format<int> {
            template <typename CharT>
            using type = basic_empty_parse_context<CharT>;
        };

        template <typename F, typename CharT>
        auto make_parse_context(F f,
                                basic_locale_ref<CharT>& locale,
                                bool localized)
            -> decltype(make_parse_context_impl(f, locale, localized))
        {
            return make_parse_context_impl(f, locale, localized);
        }
    }  // namespace detail

    template <typename F, typename CharT>
    auto make_parse_context(F f, basic_locale_ref<CharT>& locale)
        -> decltype(detail::make_parse_context_impl(f, locale, false))
    {
        return detail::make_parse_context_impl(f, locale, false);
    }

    SCN_CLANG_POP  // -Wpadded

        SCN_END_NAMESPACE
}  // namespace scn

#endif  // SCN_DETAIL_PARSE_CONTEXT_H