rapidproto-build 0.1.0-alpha.2

Generates RapidProto's Rust decoders for Protobuf schemas in a build script, without protoc.
Documentation
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
#include "rapidproto/parser.hpp"

#include <cctype>
#include <charconv>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <locale>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <variant>
#include <vector>

#include "rapidproto/ast.hpp"
#include "rapidproto/combinators.hpp"
#include "rapidproto/lexer.hpp"
#include "rapidproto/range.hpp"
#include "rapidproto/result.hpp"
#include "rapidproto/scalar.hpp"

// The parser is combinator-centric: each grammar production is an expression built
// from the Range/Result combinators (alt/seq/opt/many/delimited/preceded/
// separated_list), with the semantic action carried by map(). Concrete functions
// appear only at the recursion points (value <-> message-literal/list <-> field),
// because a combinator value cannot reference itself; they build and run a
// combinator that names the others.
//
// Number parsing never fails on a value-range issue: an integer literal that exceeds 64-bit range
// can only be a double-typed option written in integer form, so it becomes a double; float
// over/underflow saturates to +/-inf or 0. Genuinely malformed literals are rejected by the lexer and
// never reach here. Out-of-range values matter only for correctness on invalid input; the
// conversion is always memory-safe.

namespace rapidproto {
namespace {

// --- recursion-depth guard --------------------------------------------------
// Schema parsing is recursive descent over nested messages/groups/extends and nested option-literal
// aggregates, both unbounded in the input. A pathologically nested hand-written schema would
// overflow the stack, so cap the recursion depth and fail cleanly instead. The safety floor is
// unconditional: the parser must never crash, even on input protoc would reject. The cap is well
// above any real schema (real nesting is single digits) yet kept low enough to stay within a small
// thread stack -- the combinator frames are heavy, so it is deliberately conservative.
constexpr int kMaxParseDepth = 50;

// Recursion depth for the active parse, as a function-local thread_local: kept out of namespace scope,
// and per-thread so concurrent parses on different threads don't interfere. Balanced by DepthGuard.
int& parse_depth() {
    thread_local int depth = 0;
    return depth;
}

// RAII depth counter: increments on construction, decrements on every return (success or failure), so
// the count tracks live nesting even across the combinators' backtracking.
class DepthGuard {
public:
    DepthGuard() : m_within(++parse_depth() <= kMaxParseDepth) {}
    ~DepthGuard() { --parse_depth(); }
    DepthGuard(const DepthGuard&) = delete;
    DepthGuard& operator=(const DepthGuard&) = delete;
    DepthGuard(DepthGuard&&) = delete;
    DepthGuard& operator=(DepthGuard&&) = delete;
    [[nodiscard]] bool within_limit() const { return m_within; }

private:
    bool m_within;
};

// A committed ("fatal") too-deeply-nested parse error at the current position; fatal so the
// backtracking combinators propagate it instead of trying sibling alternatives.
//
// Offset 0, not the token's byte_offset: a parser reports failures RELATIVE to the range it was
// given (see combinators.hpp), and every caller checks the depth before consuming anything, so the
// offending token is that range's first. The sequential combinators lift it on the way out. Storing
// a byte offset here put a byte count where the resolver reads a token index, which landed the
// diagnostic in the wrong column and, on a large file, past EOF.
Error too_deep() {
    Error error{0, "maximum nesting depth exceeded"};
    error.fatal = true;
    return error;
}

// --- token matchers ---------------------------------------------------------

bool is_keyword(TokenKind k) {
    return k >= TokenKind::KwSyntax && k <= TokenKind::KwNan;
}

// A name position accepts an identifier or a keyword (proto allows keywords as
// names — e.g. a field named `message`).
bool is_name_token(const Token& t) {
    return t.kind == TokenKind::Identifier || is_keyword(t.kind);
}

// Match one token of the given kind; produces the Token.
auto kind(TokenKind k) {
    return one([k](const Token& t) { return t.kind == k; });
}

auto name_token() {
    return one([](const Token& t) { return is_name_token(t); });
}

auto sign_token() {
    return one(
        [](const Token& t) { return t.kind == TokenKind::Minus || t.kind == TokenKind::Plus; });
}

auto number_token() {
    return one([](const Token& t) {
        return t.kind == TokenKind::IntLiteral || t.kind == TokenKind::FloatLiteral ||
               t.kind == TokenKind::KwInf || t.kind == TokenKind::KwNan;
    });
}

// --- numeric value interpretation (infallible; see file header) ------------

constexpr int kDecimalBase = 10;
constexpr int kHexBase = 16;
constexpr int kOctalBase = 8;
constexpr unsigned kInt64SignBitShift = 63;

OptionValue make_float(std::string_view text, bool negative);

// Split an integer literal into (base, digits without the 0x/0 prefix).
std::pair<int, std::string_view> split_int_literal(std::string_view text) {
    if (text.size() >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) {
        return {kHexBase, text.substr(2)};
    }
    if (text.size() > 1 && text[0] == '0') {
        return {kOctalBase, text.substr(1)};
    }
    return {kDecimalBase, text};
}

OptionValue make_int(std::string_view text, bool negative) {
    const auto [base, digits] = split_int_literal(text);
    std::uint64_t mag = 0;
    // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage): paired with size below
    const char* first = digits.data();
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): from_chars needs a range
    const char* last = first + digits.size();
    const auto ec = std::from_chars(first, last, mag, base).ec;
    if (ec == std::errc::result_out_of_range) {
        return make_float(text, negative);  // beyond uint64 -> a double-typed option value
    }

    if (negative) {
        const std::uint64_t int64_min_magnitude = std::uint64_t{1} << kInt64SignBitShift;
        if (mag > int64_min_magnitude) {
            return make_float(text, negative);  // beyond int64 -> a double-typed option value
        }
        return OptionValue{mag == int64_min_magnitude ? INT64_MIN
                                                      : -static_cast<std::int64_t>(mag)};
    }
    return OptionValue{mag};
}

// `text` is a lexer-validated float token; it is also reached by an over-2^64 integer literal,
// including hex form -- protoc-invalid input, where the two stdlibs legitimately differ (libc++
// accumulates the 0x form and strtod reads a hex float; libstdc++ stops at the 'x' and yields
// 0; any finite value is acceptable there). ONE parse for every platform: an istringstream
// pinned to the classic ("C") locale. That IS locale-proof -- both libstdc++ and libc++
// implement num_get's float conversion via strtod_l with their cached C locale, so no host
// setlocale can reach it -- where floating-point from_chars is unavailable on Apple's shipped
// libc++ (upstream only since LLVM 20, and availability-gated on macOS). What is NOT portable
// is the failbit: libc++ raises it whenever strtod reports ERANGE, which glibc/BSD also do for
// representable SUBNORMALS -- while storing the correctly rounded value regardless (measured on
// macOS CI: trusting fail() flattened a valid "5e-324" to 0). So the value is read and the flag
// is consulted only for OVERFLOW, where libstdc++ stores max() with failbit (its LWG-23
// resolution -- the deviation) rather than the inf that [facet.num.get.virtuals] otherwise
// implies and libc++ stores; `v >= max()` catches both. Underflow stores 0 -- with failbit on
// libc++, without on libstdc++ -- correct either way. Bit-exact edges incl. the subnormal are
// pinned in test_parser_options, which every CI platform runs.
OptionValue make_float(std::string_view text, bool negative) {
    std::istringstream stream{std::string(text)};
    stream.imbue(std::locale::classic());
    double v = 0;
    stream >> v;
    if (stream.fail() && v >= std::numeric_limits<double>::max()) {
        v = HUGE_VAL;  // overflow saturates to +inf (the token carries no sign)
    }
    if (negative) {
        v = -v;
    }
    return OptionValue{v};
}

// ScalarValue = ["-"|"+"] (intLit | floatLit | inf | nan)  ->  OptionValue
OptionValue interpret_number(const std::optional<Token>& sign, const Token& num) {
    const bool negative = sign.has_value() && sign->kind == TokenKind::Minus;
    if (num.kind == TokenKind::IntLiteral) {
        return make_int(num.text, negative);
    }
    if (num.kind == TokenKind::FloatLiteral) {
        return make_float(num.text, negative);
    }
    if (num.kind == TokenKind::KwInf) {
        return OptionValue{negative ? -HUGE_VAL : HUGE_VAL};
    }
    const double nan_value = std::nan("");  // the only remaining kind is KwNan
    return OptionValue{negative ? -nan_value : nan_value};
}

// --- recursive grammar points (forward decls) ------------------------------

Result<Parsed<OptionValue, Token>> parse_scalar(Range<Token> in);
Result<Parsed<MessageLiteral, Token>> parse_message_literal(Range<Token> in);
Result<Parsed<ListLiteral, Token>> parse_list_literal(Range<Token> in);
Result<Parsed<MessageLiteralField, Token>> parse_message_field(Range<Token> in);
Result<Parsed<OptionValue, Token>> parse_field_value(Range<Token> in);
Result<Parsed<std::vector<OptionNameComponent>, Token>> parse_option_name(Range<Token> in);

// --- combinator helpers (non-recursive grammar fragments) ------------------

// QualifiedIdent = name { "." name }  ->  dotted string
auto qualified_ident() {
    return map(seq(name_token(), many(preceded(kind(TokenKind::Dot), name_token()))),
               [](auto parts) {
                   std::string out(std::get<0>(parts).text);
                   for (const Token& t : std::get<1>(parts)) {
                       out += '.';
                       out.append(t.text);
                   }
                   return out;
               });
}

// FieldName = ident | "[" QualifiedIdent "]" | "[" QualifiedIdent "/" QualifiedIdent "]"
// Produces a MessageLiteralField with only the name fields set.
auto field_name() {
    return alt(map(name_token(),
                   [](const Token& t) {
                       MessageLiteralField f;
                       f.name = std::string(t.text);  // name_kind defaults to Simple
                       return f;
                   }),
               map(seq(kind(TokenKind::LBracket), qualified_ident(),
                       opt(preceded(kind(TokenKind::Slash), qualified_ident())),
                       kind(TokenKind::RBracket)),
                   [](auto parts) {
                       MessageLiteralField f;
                       auto& type = std::get<2>(parts);
                       if (type.has_value()) {  // [domain "/" type] -> Any type-URL
                           f.name_kind = MessageFieldNameKind::AnyTypeUrl;
                           f.name = std::move(std::get<1>(parts));
                           f.any_type = std::move(*type);
                       } else {
                           f.name_kind = MessageFieldNameKind::Extension;
                           f.name = std::move(std::get<1>(parts));
                       }
                       return f;
                   }));
}

// OptionNameComponent = ident | "(" [ "." ] QualifiedIdent ")"
auto option_name_component() {
    return alt(map(name_token(),
                   [](const Token& t) { return OptionNameComponent{std::string(t.text), false}; }),
               map(seq(kind(TokenKind::LParen), opt(kind(TokenKind::Dot)), qualified_ident(),
                       kind(TokenKind::RParen)),
                   [](auto parts) {
                       std::string name;
                       if (std::get<1>(parts).has_value()) {
                           name += '.';  // fully-qualified extension name, retained verbatim
                       }
                       name += std::get<2>(parts);
                       return OptionNameComponent{std::move(name), true};
                   }));
}

// MessageLiteral body: { MsgField [","|";"] }  ->  vector<MessageLiteralField>
auto message_body() {
    return map(many(seq(parse_message_field,
                        opt(alt(kind(TokenKind::Comma), kind(TokenKind::Semicolon))))),
               [](auto items) {
                   std::vector<MessageLiteralField> fields;
                   fields.reserve(items.size());
                   for (auto& item : items) {
                       fields.push_back(std::move(std::get<0>(item)));
                   }
                   return fields;
               });
}

// One compact option: Name "=" Value
auto compact_option() {
    return map(seq(parse_option_name, cut(kind(TokenKind::Equals)), cut(parse_value)),
               [](auto parts) {
                   Option opt;
                   opt.name = std::move(std::get<0>(parts));
                   opt.value = std::move(std::get<2>(parts));
                   return opt;
               });
}

// --- recursive grammar points (definitions) --------------------------------

// ScalarValue = signed number | StringLit | identifier
Result<Parsed<OptionValue, Token>> parse_scalar(Range<Token> in) {
    return alt(
        map(seq(opt(sign_token()), number_token()),
            [](auto parts) { return interpret_number(std::get<0>(parts), std::get<1>(parts)); }),
        map(kind(TokenKind::StringLiteral),
            [](Token t) { return OptionValue{std::move(t.str_value)}; }),
        map(name_token(),
            [](const Token& t) { return OptionValue{Identifier{std::string(t.text)}}; }))(in);
}

// OptionName = component { "." component }
Result<Parsed<std::vector<OptionNameComponent>, Token>> parse_option_name(Range<Token> in) {
    return map(
        seq(option_name_component(), many(preceded(kind(TokenKind::Dot), option_name_component()))),
        [](auto parts) {
            std::vector<OptionNameComponent> out;
            out.push_back(std::move(std::get<0>(parts)));
            for (auto& component : std::get<1>(parts)) {
                out.push_back(std::move(component));
            }
            return out;
        })(in);
}

// MsgField value: ":" Value | MessageLiteral | ListOfMessages (colon optional for the latter two)
Result<Parsed<OptionValue, Token>> parse_field_value(Range<Token> in) {
    return alt(
        preceded(kind(TokenKind::Colon), parse_value),
        map(parse_message_literal, [](MessageLiteral m) { return OptionValue{std::move(m)}; }),
        map(parse_list_literal, [](ListLiteral l) { return OptionValue{std::move(l)}; }))(in);
}

// MsgField = FieldName ( ":" Value | MessageValue )
Result<Parsed<MessageLiteralField, Token>> parse_message_field(Range<Token> in) {
    return map(seq(field_name(), parse_field_value), [](auto parts) {
        MessageLiteralField field = std::move(std::get<0>(parts));
        field.value = std::move(std::get<1>(parts));
        return field;
    })(in);
}

// MessageLiteral = "{" body "}" | "<" body ">"
Result<Parsed<MessageLiteral, Token>> parse_message_literal(Range<Token> in) {
    const DepthGuard guard;
    if (!guard.within_limit()) {
        return too_deep();
    }
    return alt(
        map(delimited(kind(TokenKind::LBrace), message_body(), cut(kind(TokenKind::RBrace))),
            [](std::vector<MessageLiteralField> f) { return MessageLiteral{std::move(f)}; }),
        map(delimited(kind(TokenKind::LAngle), message_body(), cut(kind(TokenKind::RAngle))),
            [](std::vector<MessageLiteralField> f) { return MessageLiteral{std::move(f)}; }))(in);
}

// ListLiteral = "[" [ Value { "," Value } ] "]"
Result<Parsed<ListLiteral, Token>> parse_list_literal(Range<Token> in) {
    const DepthGuard guard;
    if (!guard.within_limit()) {
        return too_deep();
    }
    return map(
        delimited(kind(TokenKind::LBracket), separated_list(parse_value, kind(TokenKind::Comma)),
                  cut(kind(TokenKind::RBracket))),
        [](std::vector<OptionValue> elems) { return ListLiteral{std::move(elems)}; })(in);
}

// --- enums ------------------------------------------------------------------

// Interpret a (sign-stripped) integer literal as an int32 enum/field number. Like the option
// helpers, this never fails: for valid input the literal is well-formed and in int32 range. An
// out-of-range magnitude (beyond uint64, or outside int32 once signed) silently yields an unspecified
// in-range value rather than erroring: a value-range concern for invalid input only, and
// memory-safe.
std::int32_t parse_int32(std::string_view text, bool negative) {
    const auto [base, digits] = split_int_literal(text);
    std::uint64_t mag = 0;
    // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage): paired with size below
    const char* first = digits.data();
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): from_chars needs a range
    const char* last = first + digits.size();
    std::from_chars(first, last, mag, base);
    // Negate in the unsigned domain, where wraparound is well-defined: negating the int64 cast
    // would be signed-overflow UB for a magnitude of exactly 2^63 (e.g. `-9223372036854775808`).
    const std::uint64_t value = negative ? std::uint64_t{0} - mag : mag;
    return static_cast<std::int32_t>(value);
}

template <typename T>
std::vector<T> prepend(T first, std::vector<T> rest) {
    std::vector<T> out;
    out.reserve(rest.size() + 1);
    out.push_back(std::move(first));
    for (auto& item : rest) {
        out.push_back(std::move(item));
    }
    return out;
}

// ["-"] intLit  ->  int32
auto signed_int() {
    return map(seq(opt(kind(TokenKind::Minus)), kind(TokenKind::IntLiteral)), [](auto parts) {
        return parse_int32(std::get<1>(parts).text, std::get<0>(parts).has_value());
    });
}

// Range = ["-"] intLit [ "to" ( ["-"] intLit | "max" ) ]; `max` -> the given sentinel.
// Function boundary: reserved_range appears twice inside both parse_reserved and
// extension_range, so its signed_int/kind chain otherwise re-spells into every enclosing name.
Result<Parsed<NumberRange, Token>> reserved_range(Range<Token> in, std::int32_t max_sentinel) {
    auto bound =
        alt(map(kind(TokenKind::KwMax), [max_sentinel](const Token&) { return max_sentinel; }),
            signed_int());
    return map(seq(signed_int(), opt(preceded(kind(TokenKind::KwTo), bound))), [](auto parts) {
        NumberRange range;
        range.start = std::get<0>(parts);
        range.end = std::get<1>(parts).has_value() ? *std::get<1>(parts) : range.start;
        return range;
    })(in);
}
// The lambda-wrapped spelling that combinator call sites consume.
auto reserved_range(std::int32_t max_sentinel) {
    return [max_sentinel](Range<Token> in) { return reserved_range(in, max_sentinel); };
}

// A reserved name is a string literal (proto2/proto3) or an identifier (editions).
auto reserved_name() {
    return alt(map(kind(TokenKind::StringLiteral), [](Token t) { return std::move(t.str_value); }),
               map(name_token(), [](const Token& t) { return std::string(t.text); }));
}

// ReservedDecl = "reserved" ( Range {"," Range} | Name {"," Name} ) ";"
Result<Parsed<ReservedNode, Token>> parse_reserved(Range<Token> in, std::int32_t max_sentinel) {
    auto ranges = map(seq(reserved_range(max_sentinel),
                          many(preceded(kind(TokenKind::Comma), reserved_range(max_sentinel)))),
                      [](auto parts) {
                          ReservedNode node;
                          node.ranges =
                              prepend(std::move(std::get<0>(parts)), std::move(std::get<1>(parts)));
                          return node;
                      });
    auto names = map(seq(reserved_name(), many(preceded(kind(TokenKind::Comma), reserved_name()))),
                     [](auto parts) {
                         ReservedNode node;
                         node.names =
                             prepend(std::move(std::get<0>(parts)), std::move(std::get<1>(parts)));
                         return node;
                     });
    return delimited(kind(TokenKind::KwReserved), alt(ranges, names),
                     cut(kind(TokenKind::Semicolon)))(in);
}

// EnumValueDecl = ident "=" ["-"] intLit [ CompactOptions ] ";"
auto enum_value_decl() {
    return map(seq(name_token(), cut(kind(TokenKind::Equals)), cut(signed_int()),
                   opt(parse_compact_options), cut(kind(TokenKind::Semicolon))),
               [](auto parts) {
                   EnumValueNode value;
                   value.name = std::string(std::get<0>(parts).text);
                   value.number = std::get<2>(parts);
                   if (std::get<3>(parts).has_value()) {
                       value.options = std::move(*std::get<3>(parts));
                   }
                   return value;
               });
}

// [ "export" | "local" ]  ->  optional<Visibility>
auto visibility_modifier() {
    return opt(alt(map(kind(TokenKind::KwExport), [](const Token&) { return Visibility::Export; }),
                   map(kind(TokenKind::KwLocal), [](const Token&) { return Visibility::Local; })));
}

// One enum body element. `option`/`reserved` are matched before a bare value so those
// keywords aren't mistaken for value names. monostate represents an empty ";".
using EnumElement = std::variant<EnumValueNode, Option, ReservedNode, std::monostate>;

auto enum_body() {
    return many(
        alt(map(parse_option_decl, [](Option o) { return EnumElement{std::move(o)}; }),
            map([](Range<Token> i) { return parse_reserved(i, kMaxEnumNumber); },
                [](ReservedNode r) { return EnumElement{std::move(r)}; }),
            map(enum_value_decl(), [](EnumValueNode v) { return EnumElement{std::move(v)}; }),
            map(kind(TokenKind::Semicolon),
                [](const Token&) { return EnumElement{std::monostate{}}; })));
}

EnumNode assemble_enum(std::string_view name, std::vector<EnumElement>& elements,
                       SyntaxLevel syntax) {
    EnumNode node;
    node.name = std::string(name);
    // proto2 enums are closed; proto3 and editions default open (editions refined by
    // the feature pass).
    node.openness = syntax == SyntaxLevel::Proto2 ? EnumOpenness::Closed : EnumOpenness::Open;
    for (auto& element : elements) {
        if (auto* value = std::get_if<EnumValueNode>(&element)) {
            node.values.push_back(std::move(*value));
        } else if (auto* option = std::get_if<Option>(&element)) {
            node.options.push_back(std::move(*option));
        } else if (auto* reserved = std::get_if<ReservedNode>(&element)) {
            node.reserved.push_back(std::move(*reserved));
        }
    }
    return node;
}

// --- fields / maps / oneofs -------------------------------------------------

// TypeName = [ "." ] name { "." name }  (a scalar keyword or a message/enum reference),
// stored as written; resolved later by the type-resolution pass.
auto type_name() {
    return map(seq(opt(kind(TokenKind::Dot)), qualified_ident()), [](auto parts) {
        std::string out;
        if (std::get<0>(parts).has_value()) {
            out += '.';
        }
        out += std::get<1>(parts);
        return out;
    });
}

// A field/map number: a positive int literal (no sign).
auto field_number() {
    return map(kind(TokenKind::IntLiteral),
               [](const Token& t) { return parse_int32(t.text, false); });
}

enum class Cardinality : std::uint8_t { Required, Optional, Repeated };

auto cardinality() {
    return alt(
        map(kind(TokenKind::KwRequired), [](const Token&) { return Cardinality::Required; }),
        map(kind(TokenKind::KwOptional), [](const Token&) { return Cardinality::Optional; }),
        map(kind(TokenKind::KwRepeated), [](const Token&) { return Cardinality::Repeated; }));
}

RepeatedEncoding default_repeated_encoding(std::string_view type, SyntaxLevel syntax) {
    if (!is_packable_scalar(type)) {
        return RepeatedEncoding::Expanded;  // string/bytes/message; enums refined by type
                                            // resolution
    }
    // proto3 + editions default packed (editions refined by the feature pass); proto2 expanded.
    return syntax == SyntaxLevel::Proto2 ? RepeatedEncoding::Expanded : RepeatedEncoding::Packed;
}

// Build a FieldNode, normalizing presence/repeated-encoding from cardinality + syntax.
// Explicit `[packed]` overrides and editions feature refinement happen in later passes.
FieldNode build_field(std::optional<Cardinality> card, std::string type, std::string_view name,
                      std::int32_t number, std::optional<std::vector<Option>> options,
                      SyntaxLevel syntax) {
    FieldNode field;
    field.name = std::string(name);
    field.type_name = std::move(type);
    field.number = number;
    if (options.has_value()) {
        field.options = std::move(*options);
    }
    if (card == Cardinality::Repeated) {
        field.is_repeated = true;
        field.repeated_encoding = default_repeated_encoding(field.type_name, syntax);
    } else if (card == Cardinality::Required) {
        field.presence = FieldPresence::Required;
    } else if (!card.has_value() && syntax == SyntaxLevel::Proto3) {
        // proto3, no keyword: scalars/enums are implicit; message-typed fields are
        // promoted to Explicit by the type-resolution pass.
        field.presence = FieldPresence::Implicit;
    } else {
        // explicit `optional`; proto2 no-keyword; editions default (refined by the feature pass).
        field.presence = FieldPresence::Explicit;
    }
    return field;
}

// One oneof field: TypeName ident "=" intLit [CompactOptions] ";" (always explicit presence).
// Function boundary: the type_name/field_number chain stays local instead of re-spelling into
// oneof_body's alt names.
Result<Parsed<FieldNode, Token>> oneof_field(Range<Token> in) {
    return map(seq(type_name(), name_token(), cut(kind(TokenKind::Equals)), cut(field_number()),
                   opt(parse_compact_options), cut(kind(TokenKind::Semicolon))),
               [](auto parts) {
                   FieldNode field;
                   field.type_name = std::move(std::get<0>(parts));
                   field.name = std::string(std::get<1>(parts).text);
                   field.offset = std::get<1>(parts).byte_offset;  // the field name token
                   field.number = std::get<3>(parts);
                   field.presence = FieldPresence::Explicit;
                   if (std::get<4>(parts).has_value()) {
                       field.options = std::move(*std::get<4>(parts));
                   }
                   return field;
               })(in);
}

// --- messages / groups / extend / file --------------------------------------
// The parsers below are combinator-based recursive descent over nested messages / groups / extend
// bodies. Recursion depth is bounded by the DepthGuard at each body/aggregate entry (see
// kMaxParseDepth): a pathologically nested schema fails cleanly instead of overflowing the stack.

std::string to_lower(std::string_view text) {
    std::string out(text);
    for (char& c : out) {
        c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
    }
    return out;
}

// Overload-set helper for std::visit.
template <typename... Fs>
struct overloaded : Fs... {
    using Fs::operator()...;
};
template <typename... Fs>
overloaded(Fs...) -> overloaded<Fs...>;

// A group yields both a synthesized message and an is_group field referencing it.
struct GroupDecl {
    FieldNode field;
    MessageNode message;
};

// An extend yields the ExtendNode plus any synthesized messages for groups in its body
// (which belong to the enclosing scope, not the ExtendNode).
struct ExtendBundle {
    ExtendNode node;
    std::vector<MessageNode> group_messages;
};

// Likewise for a oneof: protoc accepts `group` as a oneof member, and the synthesized message
// belongs to the ENCLOSING message (a oneof is not a scope), while the field joins the oneof.
struct OneofBundle {
    OneofNode node;
    std::vector<MessageNode> group_messages;
};

using OneofElement = std::variant<FieldNode, GroupDecl, Option>;

OneofBundle assemble_oneof(std::string_view name, std::vector<OneofElement>& elements) {
    OneofBundle bundle;
    bundle.node.name = std::string(name);
    for (auto& element : elements) {
        if (auto* field = std::get_if<FieldNode>(&element)) {
            bundle.node.fields.push_back(std::move(*field));
        } else if (auto* group = std::get_if<GroupDecl>(&element)) {
            bundle.node.fields.push_back(std::move(group->field));
            bundle.group_messages.push_back(std::move(group->message));
        } else if (auto* option = std::get_if<Option>(&element)) {
            bundle.node.options.push_back(std::move(*option));
        }
    }
    return bundle;
}

// A real struct, not a `using` alias: an alias would mangle as the spelled-out variant (~1 KB)
// inside every symbol that mentions MessageElement -- notably assemble_message's visitor lambdas,
// whose names embed the enclosing signature. The wrapper mangles as its 14-char name; visit()
// goes through the .v member.
struct MessageElement {
    std::variant<FieldNode, MapFieldNode, OneofBundle, EnumNode, MessageNode, ReservedNode,
                 ExtensionRangeNode, ExtendBundle, Option, GroupDecl, std::monostate>
        v;
};

// recursion (message body <-> nested message / group / extend)
Result<Parsed<std::vector<MessageElement>, Token>> message_body(Range<Token> in,
                                                                const ParseContext& ctx);
Result<Parsed<GroupDecl, Token>> parse_group(Range<Token> in, const ParseContext& ctx);
Result<Parsed<std::vector<OneofElement>, Token>> oneof_body(Range<Token> in,
                                                            const ParseContext& ctx);
Result<Parsed<OneofBundle, Token>> parse_oneof(Range<Token> in, const ParseContext& ctx);
Result<Parsed<ExtendBundle, Token>> parse_extend(Range<Token> in, const ParseContext& ctx);

// ExtensionRangeDecl = "extensions" Range { "," Range } [CompactOptions] ";"
// Function boundary: this was message_element's one combinator-typed branch, and its type chain
// (reserved_range -> signed_int -> kind) was re-spelled into every level of the enclosing alt's
// instantiation names.
Result<Parsed<ExtensionRangeNode, Token>> extension_range(Range<Token> in) {
    auto ranges =
        map(seq(reserved_range(kMaxMessageFieldNumber),
                many(preceded(kind(TokenKind::Comma), reserved_range(kMaxMessageFieldNumber)))),
            [](auto parts) {
                return prepend(std::move(std::get<0>(parts)), std::move(std::get<1>(parts)));
            });
    return map(seq(preceded(kind(TokenKind::KwExtensions), ranges), opt(parse_compact_options),
                   cut(kind(TokenKind::Semicolon))),
               [](auto parts) {
                   ExtensionRangeNode node;
                   node.ranges = std::move(std::get<0>(parts));
                   if (std::get<1>(parts).has_value()) {
                       node.options = std::move(*std::get<1>(parts));
                   }
                   return node;
               })(in);
}

MessageNode assemble_message(std::string_view name, std::vector<MessageElement>& elements) {
    MessageNode node;
    node.name = std::string(name);
    for (auto& element : elements) {
        std::visit(overloaded{[&](FieldNode& f) { node.fields.push_back(std::move(f)); },
                              [&](MapFieldNode& m) { node.map_fields.push_back(std::move(m)); },
                              [&](OneofBundle& b) {
                                  node.oneofs.push_back(std::move(b.node));
                                  for (auto& gm : b.group_messages) {
                                      node.nested_messages.push_back(std::move(gm));
                                  }
                              },
                              [&](EnumNode& e) { node.enums.push_back(std::move(e)); },
                              [&](MessageNode& m) { node.nested_messages.push_back(std::move(m)); },
                              [&](ReservedNode& r) { node.reserved.push_back(std::move(r)); },
                              [&](ExtensionRangeNode& x) {
                                  node.extension_ranges.push_back(std::move(x));
                              },
                              [&](ExtendBundle& b) {
                                  node.extends.push_back(std::move(b.node));
                                  for (auto& gm : b.group_messages) {
                                      node.nested_messages.push_back(std::move(gm));
                                  }
                              },
                              [&](Option& o) { node.options.push_back(std::move(o)); },
                              [&](GroupDecl& g) {
                                  node.fields.push_back(std::move(g.field));
                                  node.nested_messages.push_back(std::move(g.message));
                              },
                              [](std::monostate) {}},
                   element.v);
    }
    return node;
}

// OneofDecl = "oneof" ident "{" { OptionDecl | OneofFieldDecl | OneofGroupDecl } "}"
// The oneof forms are RESTRICTED versions of the message-scope ones: the spec subtracts the
// cardinality keywords from a oneof field's leading identifier, and OneofGroupDecl has no
// cardinality slot at all -- which is what oneof_element enforces.
// Internal, like parse_extend: it yields a bundle, because a `group` member synthesizes a message
// that belongs to the ENCLOSING message rather than to the oneof.
Result<Parsed<OneofBundle, Token>> parse_oneof(Range<Token> in, const ParseContext& ctx) {
    return map(
        seq(
            kind(TokenKind::KwOneof), cut(name_token()), cut(kind(TokenKind::LBrace)),
            [ctx](Range<Token> i) { return oneof_body(i, ctx); }, cut(kind(TokenKind::RBrace))),
        [](auto parts) { return assemble_oneof(std::get<1>(parts).text, std::get<3>(parts)); })(in);
}

// One oneof body element. A oneof member never carries a cardinality label -- the spec forbids it
// syntactically, and protoc says "Fields in oneofs must not have labels" -- which is why oneof_field
// has no `cardinality()` to match. The group branch has to refuse one explicitly, because
// parse_group accepts a label at message scope (where the spec in fact REQUIRES one).
Result<Parsed<OneofElement, Token>> oneof_element(Range<Token> in, const ParseContext& ctx) {
    if (!in.empty() &&
        (in.front().kind == TokenKind::KwRequired || in.front().kind == TokenKind::KwOptional ||
         in.front().kind == TokenKind::KwRepeated)) {
        // Offset 0 = "at the first token of `in`", the library's relative convention: `many` and
        // `seq` lift it by their own base as it propagates (see combinators.hpp). Fatal so the
        // enclosing `many` propagates it instead of quietly ending the body, which would report a
        // bare "unexpected input" at the same token and throw the diagnostic away.
        Error error{0, "a oneof member must not have a label (required/optional/repeated)"};
        error.fatal = true;
        return error;
    }
    // No empty-statement branch: the spec gives OneofElement no EmptyDecl alternative, unlike
    // MessageElement, and protoc agrees ("Expected type name."). An empty BODY is still accepted:
    // the grammar admits it (`{ OneofElement }` allows zero), and the spec's prose rule that "a
    // oneof must contain at least one field or group" is one we knowingly do not enforce -- a
    // semantic check that costs a schema nothing to get right and protoc already makes.
    return alt(map(parse_option_decl, [](Option o) { return OneofElement{std::move(o)}; }),
               map([ctx](Range<Token> i) { return parse_group(i, ctx); },
                   [](GroupDecl g) { return OneofElement{std::move(g)}; }),
               map(oneof_field, [](FieldNode f) { return OneofElement{std::move(f)}; }))(in);
}

Result<Parsed<std::vector<OneofElement>, Token>> oneof_body(Range<Token> in,
                                                            const ParseContext& ctx) {
    return many([ctx](Range<Token> i) { return oneof_element(i, ctx); })(in);
}

// One message body element. Keyword-led declarations come before parse_field, and group before
// field, per the alt-ordering contract (parse_field fatally commits after a leading keyword type).
// A plain function, not an `auto` combinator: this is a composition HUB, and returning the alt's
// type would re-spell the entire subtree's template name into every enclosing instantiation
// (megabyte symbols, gigabytes of .debug_str). The function boundary erases it.
Result<Parsed<MessageElement, Token>> message_element(Range<Token> in, const ParseContext& ctx) {
    return alt(
        map(parse_option_decl, [](Option o) { return MessageElement{std::move(o)}; }),
        map(parse_map_field, [](MapFieldNode m) { return MessageElement{std::move(m)}; }),
        map([ctx](Range<Token> i) { return parse_oneof(i, ctx); },
            [](OneofBundle b) { return MessageElement{std::move(b)}; }),
        map([](Range<Token> i) { return parse_reserved(i, kMaxMessageFieldNumber); },
            [](ReservedNode r) { return MessageElement{std::move(r)}; }),
        map(extension_range, [](ExtensionRangeNode x) { return MessageElement{std::move(x)}; }),
        map([ctx](Range<Token> i) { return parse_extend(i, ctx); },
            [](ExtendBundle b) { return MessageElement{std::move(b)}; }),
        map([ctx](Range<Token> i) { return parse_message(i, ctx); },
            [](MessageNode m) { return MessageElement{std::move(m)}; }),
        map([ctx](Range<Token> i) { return parse_enum(i, ctx); },
            [](EnumNode e) { return MessageElement{std::move(e)}; }),
        map([ctx](Range<Token> i) { return parse_group(i, ctx); },
            [](GroupDecl g) { return MessageElement{std::move(g)}; }),
        map([ctx](Range<Token> i) { return parse_field(i, ctx); },
            [](FieldNode f) { return MessageElement{std::move(f)}; }),
        map(kind(TokenKind::Semicolon),
            [](const Token&) { return MessageElement{std::monostate{}}; }))(in);
}

Result<Parsed<std::vector<MessageElement>, Token>> message_body(Range<Token> in,
                                                                const ParseContext& ctx) {
    const DepthGuard guard;
    if (!guard.within_limit()) {
        return too_deep();
    }
    return many([ctx](Range<Token> i) { return message_element(i, ctx); })(in);
}

// GroupDecl = [Cardinality] "group" Ident "=" intLit [CompactOptions] "{" { MessageElement } "}".
// The spec makes the cardinality MANDATORY at message/extend scope; accepting it as optional is a
// deliberate superset (protoc rejects the bare form). Inside a oneof there is none, and the caller
// enforces that. Also superset: the spec requires the group name to start uppercase.
// Synthesized into a nested message (named as written) + an is_group field (lowercased name).
Result<Parsed<GroupDecl, Token>> parse_group(Range<Token> in, const ParseContext& ctx) {
    const SyntaxLevel syntax = ctx.syntax_level;
    return map(
        seq(opt(cardinality()), preceded(kind(TokenKind::KwGroup), cut(name_token())),
            preceded(cut(kind(TokenKind::Equals)), cut(field_number())), opt(parse_compact_options),
            delimited(
                cut(kind(TokenKind::LBrace)),
                [ctx](Range<Token> i) { return message_body(i, ctx); },
                cut(kind(TokenKind::RBrace)))),
        [syntax](auto parts) {
            const std::string group_name(std::get<1>(parts).text);
            MessageNode message = assemble_message(group_name, std::get<4>(parts));
            FieldNode field =
                build_field(std::get<0>(parts), group_name, to_lower(group_name),
                            std::get<2>(parts), std::move(std::get<3>(parts)), syntax);
            field.offset = std::get<1>(parts).byte_offset;  // the group name token
            field.is_group = true;
            field.message_encoding = MessageEncoding::Delimited;
            return GroupDecl{std::move(field), std::move(message)};
        })(in);
}

// One extend body element: FieldDecl | GroupDecl | OptionDecl | ";".
using ExtendElement = std::variant<FieldNode, GroupDecl>;

// ExtensionElement = ExtensionFieldDecl | GroupDecl -- the ONLY element list in the grammar with
// neither OptionDecl nor EmptyDecl (message/enum/service/method/file carry both; oneof the first).
// That is deliberate on the spec's part, not an omission: ExtensionFieldDeclIdentifier subtracts
// only `optional`/`required`/`repeated`, NOT `option` -- which MessageFieldDeclIdentifier and
// OneofFieldDeclIdentifier both do subtract. So in an extend body `option` is a legal extension
// field TYPE name, and an OptionDecl branch here did worse than widen the grammar: it swallowed the
// grammar-legal `extend M { option x = 100; }` as an option declaration instead of a field.
// Function boundary for the same reason as message_element: a hub's type must not leak upward.
Result<Parsed<ExtendElement, Token>> extend_element(Range<Token> in, const ParseContext& ctx) {
    return alt(map([ctx](Range<Token> i) { return parse_group(i, ctx); },
                   [](GroupDecl g) { return ExtendElement{std::move(g)}; }),
               map([ctx](Range<Token> i) { return parse_field(i, ctx); },
                   [](FieldNode f) { return ExtendElement{std::move(f)}; }))(in);
}

// ExtensionDecl = "extend" ExtendedMessage "{" { ExtensionFieldDecl | GroupDecl } "}"
Result<Parsed<ExtendBundle, Token>> parse_extend(Range<Token> in, const ParseContext& ctx) {
    const std::size_t offset = in.empty() ? 0 : in.front().byte_offset;  // the `extend` keyword
    return map(
        seq(preceded(kind(TokenKind::KwExtend), cut(type_name())),
            delimited(cut(kind(TokenKind::LBrace)),
                      many([ctx](Range<Token> i) { return extend_element(i, ctx); }),
                      cut(kind(TokenKind::RBrace)))),
        [offset](auto parts) {
            ExtendBundle bundle;
            bundle.node.offset = offset;
            bundle.node.extendee_type_name = std::move(std::get<0>(parts));
            for (auto& element : std::get<1>(parts)) {
                std::visit(
                    overloaded{[&](FieldNode& f) { bundle.node.fields.push_back(std::move(f)); },
                               [&](GroupDecl& g) {
                                   bundle.node.fields.push_back(std::move(g.field));
                                   bundle.group_messages.push_back(std::move(g.message));
                               }},
                    element);
            }
            return bundle;
        })(in);
}

// --- file-level declarations ------------------------------------------------

struct PackageName {
    std::string name;
};

struct SyntaxInfo {
    SyntaxLevel level = SyntaxLevel::Proto2;
    std::string edition;
    std::size_t edition_offset = 0;  // the edition string token, for the unknown-edition diagnostic
};

// Consume a balanced { ... } block (tracking nesting); produce nothing. Used to skip `service`.
Result<Parsed<std::monostate, Token>> balanced_braces(Range<Token> in) {
    if (in.empty() || in.front().kind != TokenKind::LBrace) {
        return Error{0, "expected '{'"};
    }
    std::size_t depth = 0;
    for (std::size_t i = 0; i < in.size(); ++i) {
        if (in[i].kind == TokenKind::LBrace) {
            ++depth;
        } else if (in[i].kind == TokenKind::RBrace && --depth == 0) {
            return Parsed<std::monostate, Token>{in.subspan(i + 1), std::monostate{}};
        }
    }
    return Error{in.size(), "unterminated '{' block"};
}

// ImportDecl = "import" [ "weak" | "public" | "option" ] StringLit ";"
auto import_decl() {
    return map(seq(preceded(kind(TokenKind::KwImport),
                            opt(alt(kind(TokenKind::KwWeak), kind(TokenKind::KwPublic),
                                    kind(TokenKind::KwOption)))),
                   cut(kind(TokenKind::StringLiteral)), cut(kind(TokenKind::Semicolon))),
               [](auto parts) {
                   ImportNode node;
                   node.path = std::get<1>(parts).str_value;
                   if (std::get<0>(parts).has_value()) {
                       switch (std::get<0>(parts)->kind) {
                           case TokenKind::KwWeak:
                               node.kind = ImportKind::Weak;
                               break;
                           case TokenKind::KwPublic:
                               node.kind = ImportKind::Public;
                               break;
                           case TokenKind::KwOption:
                               node.kind = ImportKind::Option;
                               break;
                           default:
                               break;
                       }
                   }
                   return node;
               });
}

// PackageDecl = "package" QualifiedIdent ";"
auto package_decl() {
    return map(seq(preceded(kind(TokenKind::KwPackage), cut(qualified_ident())),
                   cut(kind(TokenKind::Semicolon))),
               [](auto parts) { return PackageName{std::move(std::get<0>(parts))}; });
}

// SkippedServiceDecl = "service" ident BalancedBraces  (consumed and DROPPED)
auto service_decl() {
    return map(seq(kind(TokenKind::KwService), cut(name_token()), cut(balanced_braces)),
               [](const auto&) { return std::monostate{}; });
}

// SyntaxDecl = "syntax" "=" StringLit ";" | "edition" "=" StringLit ";"
auto syntax_decl() {
    return alt(map(seq(preceded(kind(TokenKind::KwSyntax), cut(kind(TokenKind::Equals))),
                       cut(kind(TokenKind::StringLiteral)), cut(kind(TokenKind::Semicolon))),
                   [](auto parts) {
                       SyntaxInfo info;
                       info.level = std::get<1>(parts).str_value == "proto3" ? SyntaxLevel::Proto3
                                                                             : SyntaxLevel::Proto2;
                       return info;
                   }),
               map(seq(preceded(kind(TokenKind::KwEdition), cut(kind(TokenKind::Equals))),
                       cut(kind(TokenKind::StringLiteral)), cut(kind(TokenKind::Semicolon))),
                   [](auto parts) {
                       SyntaxInfo info;
                       info.level = SyntaxLevel::Edition;
                       info.edition = std::get<1>(parts).str_value;
                       info.edition_offset = std::get<1>(parts).byte_offset;
                       return info;
                   }));
}

using FileElement = std::variant<ImportNode, PackageName, Option, MessageNode, EnumNode,
                                 ExtendBundle, std::monostate>;

// Function boundary for the same reason as message_element: a hub's type must not leak upward.
Result<Parsed<FileElement, Token>> file_element(Range<Token> in, const ParseContext& ctx) {
    return alt(map(parse_option_decl, [](Option o) { return FileElement{std::move(o)}; }),
               map(import_decl(), [](ImportNode i) { return FileElement{std::move(i)}; }),
               map(package_decl(), [](PackageName p) { return FileElement{std::move(p)}; }),
               map(service_decl(), [](std::monostate) { return FileElement{std::monostate{}}; }),
               map([ctx](Range<Token> i) { return parse_extend(i, ctx); },
                   [](ExtendBundle b) { return FileElement{std::move(b)}; }),
               map([ctx](Range<Token> i) { return parse_message(i, ctx); },
                   [](MessageNode m) { return FileElement{std::move(m)}; }),
               map([ctx](Range<Token> i) { return parse_enum(i, ctx); },
                   [](EnumNode e) { return FileElement{std::move(e)}; }),
               map(kind(TokenKind::Semicolon),
                   [](const Token&) { return FileElement{std::monostate{}}; }))(in);
}

void apply_file_element(FileNode& file, FileElement& element) {
    std::visit(overloaded{[&](ImportNode& i) { file.imports.push_back(std::move(i)); },
                          [&](PackageName& p) { file.package = std::move(p.name); },
                          [&](Option& o) { file.options.push_back(std::move(o)); },
                          [&](MessageNode& m) { file.messages.push_back(std::move(m)); },
                          [&](EnumNode& e) { file.enums.push_back(std::move(e)); },
                          [&](ExtendBundle& b) {
                              file.extends.push_back(std::move(b.node));
                              for (auto& gm : b.group_messages) {
                                  file.messages.push_back(std::move(gm));
                              }
                          },
                          [](std::monostate) {}},
               element);
}

}  // namespace

// OptionValue = ScalarValue | MessageLiteral | ListLiteral
Result<Parsed<OptionValue, Token>> parse_value(Range<Token> in) {
    return alt(
        map(parse_message_literal, [](MessageLiteral m) { return OptionValue{std::move(m)}; }),
        map(parse_list_literal, [](ListLiteral l) { return OptionValue{std::move(l)}; }),
        parse_scalar)(in);
}

// OptionDecl = "option" OptionName "=" OptionValue ";"
Result<Parsed<Option, Token>> parse_option_decl(Range<Token> in) {
    return map(seq(kind(TokenKind::KwOption), cut(parse_option_name), cut(kind(TokenKind::Equals)),
                   cut(parse_value), cut(kind(TokenKind::Semicolon))),
               [](auto parts) {
                   Option opt;
                   opt.name = std::move(std::get<1>(parts));
                   opt.value = std::move(std::get<3>(parts));
                   return opt;
               })(in);
}

// CompactOptions = "[" Option { "," Option } "]"
Result<Parsed<std::vector<Option>, Token>> parse_compact_options(Range<Token> in) {
    return delimited(kind(TokenKind::LBracket),
                     separated_list(compact_option(), kind(TokenKind::Comma)),
                     cut(kind(TokenKind::RBracket)))(in);
}

// EnumDecl = [ "export" | "local" ] "enum" ident "{" { EnumElement } "}"
Result<Parsed<EnumNode, Token>> parse_enum(Range<Token> in, const ParseContext& ctx) {
    const SyntaxLevel syntax = ctx.syntax_level;
    return map(seq(visibility_modifier(), kind(TokenKind::KwEnum), cut(name_token()),
                   cut(kind(TokenKind::LBrace)), enum_body(), cut(kind(TokenKind::RBrace))),
               [syntax](auto parts) {
                   EnumNode node =
                       assemble_enum(std::get<2>(parts).text, std::get<4>(parts), syntax);
                   if (std::get<0>(parts).has_value()) {
                       node.visibility = *std::get<0>(parts);
                   }
                   return node;
               })(in);
}

// FieldDecl = [Cardinality] TypeName ident "=" intLit [CompactOptions] ";". The "= number"
// is folded into one tuple slot with preceded() so each element below is meaningful.
//
// ORDERING CONTRACT: parse_field consumes a leading keyword as a type name, then commits (cut)
// at "=". So in any enclosing alt it MUST come AFTER every keyword-led declaration (option, map,
// oneof, reserved, extensions, extend, message, enum, group). A `group` is byte-for-byte a field
// up to "= number", so group MUST be tried before field. (See enum_body for the same discipline.)
Result<Parsed<FieldNode, Token>> parse_field(Range<Token> in, const ParseContext& ctx) {
    const SyntaxLevel syntax = ctx.syntax_level;
    return map(seq(opt(cardinality()), type_name(), name_token(),
                   preceded(cut(kind(TokenKind::Equals)), cut(field_number())),
                   opt(parse_compact_options), cut(kind(TokenKind::Semicolon))),
               [syntax](auto parts) {
                   FieldNode field = build_field(std::get<0>(parts), std::move(std::get<1>(parts)),
                                                 std::get<2>(parts).text, std::get<3>(parts),
                                                 std::move(std::get<4>(parts)), syntax);
                   field.offset = std::get<2>(parts).byte_offset;  // the field name token
                   return field;
               })(in);
}

// MapFieldDecl = "map" "<" KeyType "," TypeName ">" ident "=" intLit [CompactOptions] ";". Each
// punctuation token is folded into the preceding meaningful element via preceded(). KeyType is
// parsed as an arbitrary type_name (not the spec's restricted integral/bool/string set); key-type
// validity is checked later in analysis (resolve_map), not here; the parser does no semantic
// checks.
Result<Parsed<MapFieldNode, Token>> parse_map_field(Range<Token> in) {
    return map(seq(preceded(seq(kind(TokenKind::KwMap), cut(kind(TokenKind::LAngle))),
                            cut(type_name())),                                   // key
                   preceded(cut(kind(TokenKind::Comma)), cut(type_name())),      // value
                   preceded(cut(kind(TokenKind::RAngle)), cut(name_token())),    // name
                   preceded(cut(kind(TokenKind::Equals)), cut(field_number())),  // number
                   opt(parse_compact_options), cut(kind(TokenKind::Semicolon))),
               [](auto parts) {
                   MapFieldNode node;
                   node.key_type = std::move(std::get<0>(parts));
                   node.value_type = std::move(std::get<1>(parts));
                   node.name = std::string(std::get<2>(parts).text);
                   node.offset = std::get<2>(parts).byte_offset;  // the field name token
                   node.number = std::get<3>(parts);
                   if (std::get<4>(parts).has_value()) {
                       node.options = std::move(*std::get<4>(parts));
                   }
                   return node;
               })(in);
}

// MessageDecl = [ "export"|"local" ] "message" ident "{" { MessageElement } "}"
Result<Parsed<MessageNode, Token>> parse_message(Range<Token> in, const ParseContext& ctx) {
    return map(seq(visibility_modifier(), kind(TokenKind::KwMessage), cut(name_token()),
                   delimited(
                       cut(kind(TokenKind::LBrace)),
                       [ctx](Range<Token> i) { return message_body(i, ctx); },
                       cut(kind(TokenKind::RBrace)))),
               [](auto parts) {
                   MessageNode node = assemble_message(std::get<2>(parts).text, std::get<3>(parts));
                   if (std::get<0>(parts).has_value()) {
                       node.visibility = *std::get<0>(parts);
                   }
                   return node;
               })(in);
}

// File = [ SyntaxDecl ] { FileElement }
Result<Parsed<FileNode, Token>> parse_file(Range<Token> in) {
    ParseContext ctx;  // absent syntax/edition decl => proto2
    std::string edition;
    std::size_t edition_offset = 0;
    Range<Token> rest = in;

    auto syntax = syntax_decl()(in);
    if (syntax.is_ok()) {
        ctx.syntax_level = syntax.value().value.level;
        edition = std::move(syntax.value().value.edition);
        edition_offset = syntax.value().value.edition_offset;
        rest = syntax.value().remaining;
    } else if (syntax.error().fatal) {
        return std::move(syntax.error());  // a malformed syntax/edition declaration
    }

    auto body = many([ctx](Range<Token> i) { return file_element(i, ctx); })(rest);
    if (!body) {
        Error e = std::move(body.error());
        e.byte_offset += static_cast<std::size_t>(rest.data() - in.data());
        return e;
    }

    FileNode file;
    file.syntax_level = ctx.syntax_level;
    file.edition = std::move(edition);
    file.edition_offset = edition_offset;
    for (auto& element : body.value().value) {
        apply_file_element(file, element);
    }
    return Parsed<FileNode, Token>{body.value().remaining, std::move(file)};
}

}  // namespace rapidproto