aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/protobuf/src/google/protobuf/io/printer.h
blob: 8a2055ede00b05c34b91b1335e7d53fa722587ab (plain) (blame)
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
1153
1154
1155
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: kenton@google.com (Kenton Varda)
//  Based on original Protocol Buffers design by
//  Sanjay Ghemawat, Jeff Dean, and others.
//
// Utility class for writing text to a ZeroCopyOutputStream.

#ifndef GOOGLE_PROTOBUF_IO_PRINTER_H__
#define GOOGLE_PROTOBUF_IO_PRINTER_H__

#include <cstddef>
#include <functional>
#include <initializer_list>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

#include "y_absl/cleanup/cleanup.h"
#include "y_absl/container/flat_hash_map.h"
#include "y_absl/functional/function_ref.h"
#include "y_absl/log/absl_check.h"
#include "y_absl/meta/type_traits.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/string_view.h"
#include "y_absl/types/optional.h"
#include "y_absl/types/variant.h"
#include "google/protobuf/io/zero_copy_sink.h"


// Must be included last.
#include "google/protobuf/port_def.inc"

namespace google {
namespace protobuf {
namespace io {

// Records annotations about a Printer's output.
class PROTOBUF_EXPORT AnnotationCollector {
 public:
  // Annotation is a offset range and a payload pair. This payload's layout is
  // specific to derived types of AnnotationCollector.
  using Annotation = std::pair<std::pair<size_t, size_t>, TProtoStringType>;

  // The semantic meaning of an annotation. This enum mirrors
  // google.protobuf.GeneratedCodeInfo.Annotation.Semantic, and the enumerator values
  // should match it.
  enum Semantic {
    kNone = 0,
    kSet = 1,
    kAlias = 2,
  };

  virtual ~AnnotationCollector() = default;

  // Records that the bytes in file_path beginning with begin_offset and ending
  // before end_offset are associated with the SourceCodeInfo-style path.
  virtual void AddAnnotation(size_t begin_offset, size_t end_offset,
                             const TProtoStringType& file_path,
                             const std::vector<int>& path) = 0;

  virtual void AddAnnotation(size_t begin_offset, size_t end_offset,
                             const TProtoStringType& file_path,
                             const std::vector<int>& path,
                             y_absl::optional<Semantic> semantic) {
    AddAnnotation(begin_offset, end_offset, file_path, path);
  }

  // TODO(gerbens) I don't see why we need virtuals here. Just a vector of
  // range, payload pairs stored in a context should suffice.
  virtual void AddAnnotationNew(Annotation&) {}
};

// Records annotations about a Printer's output to a Protobuf message,
// assuming that it has a repeated submessage field named `annotation` with
// fields matching
//
// message ??? {
//   repeated int32 path = 1;
//   optional string source_file = 2;
//   optional int32 begin = 3;
//   optional int32 end = 4;
//   optional int32 semantic = 5;
// }
template <typename AnnotationProto>
class AnnotationProtoCollector : public AnnotationCollector {
 private:
  // Some users of this type use it with a proto that does not have a
  // "semantic" field. Therefore, we need to detect it with SFINAE.

  // go/ranked-overloads
  struct Rank0 {};
  struct Rank1 : Rank0 {};

  template <typename Proto>
  static auto SetSemantic(Proto* p, int semantic, Rank1)
      -> decltype(p->set_semantic(
          static_cast<typename Proto::Semantic>(semantic))) {
    return p->set_semantic(static_cast<typename Proto::Semantic>(semantic));
  }

  template <typename Proto>
  static void SetSemantic(Proto*, int, Rank0) {}

 public:
  explicit AnnotationProtoCollector(AnnotationProto* annotation_proto)
      : annotation_proto_(annotation_proto) {}

  void AddAnnotation(size_t begin_offset, size_t end_offset,
                     const TProtoStringType& file_path,
                     const std::vector<int>& path) override {
    AddAnnotation(begin_offset, end_offset, file_path, path, y_absl::nullopt);
  }

  void AddAnnotation(size_t begin_offset, size_t end_offset,
                     const TProtoStringType& file_path, const std::vector<int>& path,
                     y_absl::optional<Semantic> semantic) override {
    auto* annotation = annotation_proto_->add_annotation();
    for (int i = 0; i < path.size(); ++i) {
      annotation->add_path(path[i]);
    }
    annotation->set_source_file(file_path);
    annotation->set_begin(begin_offset);
    annotation->set_end(end_offset);

    if (semantic.has_value()) {
      SetSemantic(annotation, *semantic, Rank1{});
    }
  }

  void AddAnnotationNew(Annotation& a) override {
    auto* annotation = annotation_proto_->add_annotation();
    annotation->ParseFromString(a.second);
    annotation->set_begin(a.first.first);
    annotation->set_end(a.first.second);
  }

 private:
  AnnotationProto* annotation_proto_;
};

// A source code printer for assisting in code generation.
//
// This type implements a simple templating language for substiting variables
// into static, user-provided strings, and also tracks indentation
// automatically.
//
// The main entry-point for this type is the Emit function, which can be used
// thus:
//
//   Printer p(output);
//   p.Emit({{"class", my_class_name}}, R"cc(
//     class $class$ {
//      public:
//       $class$(int x) : x_(x) {}
//      private:
//       int x_;
//     };
//   )cc");
//
// Substitutions are of the form $var$, which is looked up in the map passed in
// as the first argument. The variable delimiter character, $, can be chosen to
// be something convenient for the target language. For example, in PHP, which
// makes heavy use of $, it can be made into something like # instead.
//
// A literal $ can be emitted by writing $$.
//
// Substitutions may contain spaces around the name of the variable, which will
// be ignored for the purposes of looking up the variable to substitute in, but
// which will be reproduced in the output:
//
//   p.Emit({{"foo", "bar"}}, "$ foo $");
//
// emits the string " bar ". If the substituted-in variable is the empty string,
// then the surrounding spaces are *not* printed:
//
//   p.Emit({{"xzy", xyz}}, "$xyz $Thing");
//
// If xyz is "Foo", this will become "Foo Thing", but if it is "", this becomes
// "Thing", rather than " Thing". This helps minimize awkward whitespace in the
// output.
//
// The value may be any type that can be stringified with `y_absl::StrCat`:
//
//   p.Emit({{"num", 5}}, "x = $num$;");
//
// If a variable is referenced in the format string that is missing, the program
// will crash. Callers must statically know that every variable reference is
// valid, and MUST NOT pass user-provided strings directly into Emit().
//
// Substitutions can be configured to "chomp" a single character after them, to
// help make indentation work out. This can be configured by passing a
// two-argument io::Printer::Value into Emit's substitution map:
//
//   p.Emit({{"var", io::Printer::Value{var_decl, ";"}}}, R"cc(
//     class $class$ {
//      public:
//       $var$;
//     };
//   )cc");
//
// This will delete the ; after $var$, regardless of whether it was an empty
// declaration or not. It will also intelligently attempt to clean up
// empty lines that follow, if it was on an empty line; this promotes cleaner
// formatting of the output.
//
// Any number of different characters can be potentially skipped, but only one
// will actually be skipped. For example, callback substitutions (see below) use
// ";," by default as their "chomping set".
//
// # Callback Substitution
//
// Instead of passing a string into Emit(), it is possible to pass in a callback
// as a variable mapping. This will take indentation into account, which allows
// factoring out parts of a formatting string while ensuring braces are
// balanced:
//
//   p.Emit(
//     {{"methods", [&] {
//       p.Emit(R"cc(
//         int Bar() {
//            return 42;
//         }
//       )cc");
//     }}},
//     R"cc(
//       class Foo {
//        public:
//         $methods$;
//       };
//     )cc"
//   );
//
// This emits
//
//   class Foo {
//    public:
//     int Bar() {
//       return 42;
//     }
//   };
//
// # Comments
//
// It may be desirable to place comments in a raw string that are stripped out
// before printing. The prefix for Printer-ignored comments can be configured
// in Options. By default, this is `//~`.
//
//   p.Emit(R"cc(
//     // Will be printed in the output.
//     //~ Won't be.
//   )cc");
//
// # Lookup Frames
//
// If many calls to Emit() use the same set of variables, they can be stored
// in a *variable lookup frame*, like so:
//
//   auto vars = p.WithVars({{"class_name", my_class_name}});
//   p.Emit(R"cc(
//     class $class_name$ {
//      public:
//       $class_name$(int x);
//       // Etc.
//     };
//   )cc");
//
// WithVars() returns an RAII object that will "pop" the lookup frame on scope
// exit, ensuring that the variables remain local. There are a few different
// overloads of WithVars(); it accepts a map type, like y_absl::flat_hash_map,
// either by-value (which will cause the Printer to store a copy), or by
// pointer (which will cause the Printer to store a pointer, potentially
// avoiding a copy.)
//
// p.Emit(vars, "..."); is effectively syntax sugar for
//
//  { auto v = p.WithVars(vars); p.Emit("..."); }
//
// NOTE: callbacks are *not* allowed with WithVars; callbacks should be local
// to a specific Emit() call.
//
// # Annotations
//
// If Printer is given an AnnotationCollector, it will use it to record which
// spans of generated code correspond to user-indicated descriptors. There are
// a few different ways of indicating when to emit annotations.
//
// The WithAnnotations() function is like WithVars(), but accepts maps with
// string keys and descriptor values. It adds an annotation variable frame and
// returns an RAII object that pops the frame.
//
// There are two different ways to annotate code. In the first, when
// substituting a variable, if there is an annotation with the same name, then
// the resulting expanded value's span will be annotated with that annotation.
// For example:
//
//   auto v = p.WithVars({{"class_name", my_class_name}});
//   auto a = p.WithAnnotations({{"class_name", message_descriptor}});
//   p.Emit(R"cc(
//     class $class_name$ {
//      public:
//       $class_name$(int x);
//       // Etc.
//     };
//   )cc");
//
// The span corresponding to whatever $class_name$ expands to will be annotated
// as having come from message_descriptor.
//
// For convenience, this can be done with a single WithVars(), using the special
// three-argument form:
//
//   auto v = p.WithVars({{"class_name", my_class_name, message_descriptor}});
//   p.Emit(R"cc(
//     class $class_name$ {
//      public:
//       $class_name$(int x);
//       // Etc.
//     };
//   )cc");
//
//
// Alternatively, a range may be given explicitly:
//
//   auto a = p.WithAnnotations({{"my_desc", message_descriptor}});
//   p.Emit(R"cc(
//     $_start$my_desc$
//     class Foo {
//       // Etc.
//     };
//     $_end$my_desc$
//   )cc");
//
// The special $_start$ and $_end$ variables indicate the start and end of an
// annotated span, which is annotated with the variable that follows. This
// form can produce somewhat unreadable format strings and is not recommended.
//
// Note that whitespace after a $_start$ and before an $_end$ is not printed.
//
// # Indentation
//
// Printer tracks an indentation amount to add to each new line, independent
// from indentation in an Emit() call's literal. The amount of indentation to
// add is controlled by the WithIndent() function:
//
//   p.Emit("class $class_name$ {");
//   {
//     auto indent = p.WithIndent();
//     p.Emit(R"cc(
//       public:
//        $class_name$(int x);
//     )cc");
//   }
//   p.Emit("};");
//
// This will automatically add one level of indentation to all code in scope of
// `indent`, which is an RAII object much like the return value of `WithVars()`.
//
// # Old API
// TODO(b/242326974): Delete this documentation.
//
// Printer supports an older-style API that is in the process of being
// re-written. The old documentation is reproduced here until all use-cases are
// handled.
//
// This simple utility class assists in code generation.  It basically
// allows the caller to define a set of variables and then output some
// text with variable substitutions.  Example usage:
//
//   Printer printer(output, '$');
//   map<string, string> vars;
//   vars["name"] = "Bob";
//   printer.Print(vars, "My name is $name$.");
//
// The above writes "My name is Bob." to the output stream.
//
// Printer aggressively enforces correct usage, crashing (with assert failures)
// in the case of undefined variables in debug builds. This helps greatly in
// debugging code which uses it.
//
// If a Printer is constructed with an AnnotationCollector, it will provide it
// with annotations that connect the Printer's output to paths that can identify
// various descriptors.  In the above example, if person_ is a descriptor that
// identifies Bob, we can associate the output string "My name is Bob." with
// a source path pointing to that descriptor with:
//
//   printer.Annotate("name", person_);
//
// The AnnotationCollector will be sent an annotation linking the output range
// covering "Bob" to the logical path provided by person_.  Tools may use
// this association to (for example) link "Bob" in the output back to the
// source file that defined the person_ descriptor identifying Bob.
//
// Annotate can only examine variables substituted during the last call to
// Print.  It is invalid to refer to a variable that was used multiple times
// in a single Print call.
//
// In full generality, one may specify a range of output text using a beginning
// substitution variable and an ending variable.  The resulting annotation will
// span from the first character of the substituted value for the beginning
// variable to the last character of the substituted value for the ending
// variable.  For example, the Annotate call above is equivalent to this one:
//
//   printer.Annotate("name", "name", person_);
//
// This is useful if multiple variables combine to form a single span of output
// that should be annotated with the same source path.  For example:
//
//   Printer printer(output, '$');
//   map<string, string> vars;
//   vars["first"] = "Alice";
//   vars["last"] = "Smith";
//   printer.Print(vars, "My name is $first$ $last$.");
//   printer.Annotate("first", "last", person_);
//
// This code would associate the span covering "Alice Smith" in the output with
// the person_ descriptor.
//
// Note that the beginning variable must come before (or overlap with, in the
// case of zero-sized substitution values) the ending variable.
//
// It is also sometimes useful to use variables with zero-sized values as
// markers.  This avoids issues with multiple references to the same variable
// and also allows annotation ranges to span literal text from the Print
// templates:
//
//   Printer printer(output, '$');
//   map<string, string> vars;
//   vars["foo"] = "bar";
//   vars["function"] = "call";
//   vars["mark"] = "";
//   printer.Print(vars, "$function$($foo$,$foo$)$mark$");
//   printer.Annotate("function", "mark", call_);
//
// This code associates the span covering "call(bar,bar)" in the output with the
// call_ descriptor.
class PROTOBUF_EXPORT Printer {
 private:
  // This type exists to work around an absl type that has not yet been
  // released.
  struct SourceLocation {
    static SourceLocation current() { return {}; }
    y_absl::string_view file_name() { return "<unknown>"; }
    int line() { return 0; }
  };

  struct AnnotationRecord;

 public:
  static constexpr char kDefaultVariableDelimiter = '$';
  static constexpr y_absl::string_view kProtocCodegenTrace =
      "PROTOC_CODEGEN_TRACE";

  // Sink type for constructing substitutions to pass to WithVars() and Emit().
  class Sub;

  // Options for controlling how the output of a Printer is formatted.
  struct Options {
    Options() = default;
    Options(const Options&) = default;
    Options(Options&&) = default;
    Options(char variable_delimiter, AnnotationCollector* annotation_collector)
        : variable_delimiter(variable_delimiter),
          annotation_collector(annotation_collector) {}

    // The delimiter for variable substitutions, e.g. $foo$.
    char variable_delimiter = kDefaultVariableDelimiter;
    // An optional listener the Printer calls whenever it emits a source
    // annotation; may be null.
    AnnotationCollector* annotation_collector = nullptr;
    // The "comment start" token for the language being generated. This is used
    // to allow the Printer to emit debugging annotations in the source code
    // output.
    y_absl::string_view comment_start = "//";
    // The token for beginning comments that are discarded by Printer's internal
    // formatter.
    y_absl::string_view ignored_comment_start = "//~";
    // The number of spaces that a single level of indentation adds by default;
    // this is the amount that WithIndent() increases indentation by.
    size_t spaces_per_indent = 2;
    // Whether to emit a "codegen trace" for calls to Emit(). If true, each call
    // to Emit() will print a comment indicating where in the source of the
    // compiler the Emit() call occurred.
    //
    // If disengaged, defaults to whether or not the environment variable
    // `PROTOC_CODEGEN_TRACE` is set.
    y_absl::optional<bool> enable_codegen_trace = y_absl::nullopt;
  };

  // Constructs a new Printer with the default options to output to
  // `output`.
  explicit Printer(ZeroCopyOutputStream* output) : Printer(output, Options{}) {}

  // Constructs a new printer with the given set of options to output to
  // `output`.
  Printer(ZeroCopyOutputStream* output, Options options);

  // Old-style constructor. Avoid in preference to the two constructors above.
  //
  // Will eventually be marked as deprecated.
  Printer(ZeroCopyOutputStream* output, char variable_delimiter,
          AnnotationCollector* annotation_collector = nullptr)
      : Printer(output, Options{variable_delimiter, annotation_collector}) {}

  Printer(const Printer&) = delete;
  Printer& operator=(const Printer&) = delete;

  // Pushes a new variable lookup frame that stores `vars` by reference.
  //
  // Returns an RAII object that pops the lookup frame.
  template <typename Map>
  auto WithVars(const Map* vars);

  // Pushes a new variable lookup frame that stores `vars` by value.
  //
  // Returns an RAII object that pops the lookup frame.
  template <typename Map = y_absl::flat_hash_map<TProtoStringType, TProtoStringType>,
            typename = std::enable_if_t<!std::is_pointer<Map>::value>,
            // Prefer the more specific span impl if this could be turned into
            // a span.
            typename = std::enable_if_t<
                !std::is_convertible<Map, y_absl::Span<const Sub>>::value>>
  auto WithVars(Map&& vars);

  // Pushes a new variable lookup frame that stores `vars` by value.
  //
  // Returns an RAII object that pops the lookup frame.
  auto WithVars(y_absl::Span<const Sub> vars);

  // Looks up a variable set with WithVars().
  //
  // Will crash if:
  // - `var` is not present in the lookup frame table.
  // - `var` is a callback, rather than a string.
  y_absl::string_view LookupVar(y_absl::string_view var);

  // Pushes a new annotation lookup frame that stores `vars` by reference.
  //
  // Returns an RAII object that pops the lookup frame.
  template <typename Map>
  auto WithAnnotations(const Map* vars);

  // Pushes a new variable lookup frame that stores `vars` by value.
  //
  // When writing `WithAnnotations({...})`, this is the overload that will be
  // called, and it will synthesize an `y_absl::flat_hash_map`.
  //
  // Returns an RAII object that pops the lookup frame.
  template <typename Map = y_absl::flat_hash_map<TProtoStringType, AnnotationRecord>>
  auto WithAnnotations(Map&& vars);

  // Increases the indentation by `indent` spaces; when nullopt, increments
  // indentation by the configured default spaces_per_indent.
  //
  // Returns an RAII object that removes this indentation.
  auto WithIndent(y_absl::optional<size_t> indent = y_absl::nullopt) {
    size_t delta = indent.value_or(options_.spaces_per_indent);
    indent_ += delta;
    return y_absl::MakeCleanup([this, delta] { indent_ -= delta; });
  }

  // Emits formatted source code to the underlying output. See the class
  // documentation for more details.
  //
  // `format` MUST be a string constant.
  void Emit(y_absl::string_view format,
            SourceLocation loc = SourceLocation::current());

  // Emits formatted source code to the underlying output, injecting
  // additional variables as a lookup frame for just this call. See the class
  // documentation for more details.
  //
  // `format` MUST be a string constant.
  void Emit(y_absl::Span<const Sub> vars, y_absl::string_view format,
            SourceLocation loc = SourceLocation::current());

  // Write a string directly to the underlying output, performing no formatting
  // of any sort.
  void PrintRaw(y_absl::string_view data) { WriteRaw(data.data(), data.size()); }

  // Write a string directly to the underlying output, performing no formatting
  // of any sort.
  void WriteRaw(const char* data, size_t size);

  // True if any write to the underlying stream failed.  (We don't just
  // crash in this case because this is an I/O failure, not a programming
  // error.)
  bool failed() const { return failed_; }

  // -- Old-style API below; to be deprecated and removed. --
  // TODO(b/242326974): Deprecate these APIs.

  template <typename Map = y_absl::flat_hash_map<TProtoStringType, TProtoStringType>>
  void Print(const Map& vars, y_absl::string_view text);

  template <typename... Args>
  void Print(y_absl::string_view text, const Args&... args);

  // Link a substitution variable emitted by the last call to Print to the
  // object described by descriptor.
  template <typename SomeDescriptor>
  void Annotate(y_absl::string_view varname, const SomeDescriptor* descriptor) {
    Annotate(varname, varname, descriptor);
  }

  // Link the output range defined by the substitution variables as emitted by
  // the last call to Print to the object described by descriptor. The range
  // begins at begin_varname's value and ends after the last character of the
  // value substituted for end_varname.
  template <typename Desc>
  void Annotate(y_absl::string_view begin_varname, y_absl::string_view end_varname,
                const Desc* descriptor);

  // Link a substitution variable emitted by the last call to Print to the file
  // with path file_name.
  void Annotate(y_absl::string_view varname, y_absl::string_view file_name) {
    Annotate(varname, varname, file_name);
  }

  // Link the output range defined by the substitution variables as emitted by
  // the last call to Print to the file with path file_name. The range begins
  // at begin_varname's value and ends after the last character of the value
  // substituted for end_varname.
  void Annotate(y_absl::string_view begin_varname, y_absl::string_view end_varname,
                y_absl::string_view file_name) {
    if (options_.annotation_collector == nullptr) {
      return;
    }

    Annotate(begin_varname, end_varname, file_name, {});
  }

  // Indent text by `options.spaces_per_indent`; undone by Outdent().
  void Indent() { indent_ += options_.spaces_per_indent; }

  // Undoes a call to Indent().
  void Outdent();

  // FormatInternal is a helper function not meant to use directly, use
  // compiler::cpp::Formatter instead.
  template <typename Map = y_absl::flat_hash_map<TProtoStringType, TProtoStringType>>
  void FormatInternal(y_absl::Span<const TProtoStringType> args, const Map& vars,
                      y_absl::string_view format);

 private:
  struct PrintOptions;
  struct Format;

  // Helper type for wrapping a variable substitution expansion result.
  template <bool owned>
  struct ValueImpl;

  using ValueView = ValueImpl</*owned=*/false>;
  using Value = ValueImpl</*owned=*/true>;

  // Provide a helper to use heterogeneous lookup when it's available.
  template <typename...>
  using Void = void;

  template <typename Map, typename = void>
  struct HasHeteroLookup : std::false_type {};
  template <typename Map>
  struct HasHeteroLookup<Map, Void<decltype(std::declval<Map>().find(
                                  std::declval<y_absl::string_view>()))>>
      : std::true_type {};

  template <typename Map,
            typename = std::enable_if_t<HasHeteroLookup<Map>::value>>
  static y_absl::string_view ToStringKey(y_absl::string_view x) {
    return x;
  }

  template <typename Map,
            typename = std::enable_if_t<!HasHeteroLookup<Map>::value>>
  static TProtoStringType ToStringKey(y_absl::string_view x) {
    return TProtoStringType(x);
  }

  Format TokenizeFormat(y_absl::string_view format_string,
                        const PrintOptions& options);

  // Emit an annotation for the range defined by the given substitution
  // variables, as set by the most recent call to PrintImpl() that set
  // `use_substitution_map` to true.
  //
  // The range begins at the start of `begin_varname`'s value and ends after the
  // last byte of `end_varname`'s value.
  //
  // `begin_varname` and `end_varname may` refer to the same variable.
  void Annotate(y_absl::string_view begin_varname, y_absl::string_view end_varname,
                y_absl::string_view file_path, const std::vector<int>& path);

  // The core printing implementation. There are three public entry points,
  // which enable different slices of functionality that are controlled by the
  // `opts` argument.
  void PrintImpl(y_absl::string_view format, y_absl::Span<const TProtoStringType> args,
                 PrintOptions opts);

  // This is a private function only so that it can see PrintOptions.
  static bool Validate(bool cond, PrintOptions opts,
                       y_absl::FunctionRef<TProtoStringType()> message);
  static bool Validate(bool cond, PrintOptions opts, y_absl::string_view message);

  // Performs calls to `Validate()` to check that `index < current_arg_index`
  // and `index < args_len`, producing appropriate log lines if the checks fail,
  // and crashing if necessary.
  bool ValidateIndexLookupInBounds(size_t index, size_t current_arg_index,
                                   size_t args_len, PrintOptions opts);

  // Prints indentation if `at_start_of_line_` is true.
  void IndentIfAtStart();

  // Prints a codegen trace, for the given location in the compiler's source.
  void PrintCodegenTrace(y_absl::optional<SourceLocation> loc);

  // The core implementation for "fully-elaborated" variable definitions.
  auto WithDefs(y_absl::Span<const Sub> vars, bool allow_callbacks);

  // Returns the start and end of the value that was substituted in place of
  // the variable `varname` in the last call to PrintImpl() (with
  // `use_substitution_map` set), if such a variable was substituted exactly
  // once.
  y_absl::optional<std::pair<size_t, size_t>> GetSubstitutionRange(
      y_absl::string_view varname, PrintOptions opts);

  google::protobuf::io::zc_sink_internal::ZeroCopyStreamByteSink sink_;
  Options options_;
  size_t indent_ = 0;
  bool at_start_of_line_ = true;
  bool failed_ = false;

  std::vector<std::function<y_absl::optional<ValueView>(y_absl::string_view)>>
      var_lookups_;

  std::vector<
      std::function<y_absl::optional<AnnotationRecord>(y_absl::string_view)>>
      annotation_lookups_;

  // A map from variable name to [start, end) offsets in the output buffer.
  //
  // This stores the data looked up by GetSubstitutionRange().
  y_absl::flat_hash_map<TProtoStringType, std::pair<size_t, size_t>> substitutions_;
  // Keeps track of the keys in `substitutions_` that need to be updated when
  // indents are inserted. These are keys that refer to the beginning of the
  // current line.
  std::vector<TProtoStringType> line_start_variables_;
};

// Options for PrintImpl().
struct Printer::PrintOptions {
  // The callsite of the public entry-point. Only Emit() sets this.
  y_absl::optional<SourceLocation> loc;
  // If set, Validate() calls will not crash the program.
  bool checks_are_debug_only = false;
  // If set, the `substitutions_` map will be populated as variables are
  // substituted.
  bool use_substitution_map = false;
  // If set, the ${1$ and $}$ forms will be substituted. These are used for
  // a slightly janky annotation-insertion mechanism in FormatInternal, that
  // requires that passed-in substitution variables be serialized protos.
  bool use_curly_brace_substitutions = false;
  // If set, the $n$ forms will be substituted, pulling from the `args`
  // argument to PrintImpl().
  bool allow_digit_substitutions = true;
  // If set, when a variable substitution with spaces in it, such as $ var$,
  // is encountered, the spaces are stripped, so that it is as if it was
  // $var$. If $var$ substitutes to a non-empty string, the removed spaces are
  // printed around the substituted value.
  //
  // See the class documentation for more information on this behavior.
  bool strip_spaces_around_vars = true;
  // If set, leading whitespace will be stripped from the format string to
  // determine the "extraneous indentation" that is produced when the format
  // string is a C++ raw string. This is used to remove leading spaces from
  // a raw string that would otherwise result in erratic indentation in the
  // output.
  bool strip_raw_string_indentation = false;
  // If set, the annotation lookup frames are searched, per the annotation
  // semantics of Emit() described in the class documentation.
  bool use_annotation_frames = true;
};

// Helper type for wrapping a variable substitution expansion result.
template <bool owned>
struct Printer::ValueImpl {
 private:
  template <typename T>
  struct IsSubImpl : std::false_type {};
  template <bool a>
  struct IsSubImpl<ValueImpl<a>> : std::true_type {};

 public:
  using StringType = std::conditional_t<owned, TProtoStringType, y_absl::string_view>;
  // These callbacks return false if this is a recursive call.
  using Callback = std::function<bool()>;
  using StringOrCallback = y_absl::variant<StringType, Callback>;

  ValueImpl() = default;

  // This is a template to avoid colliding with the copy constructor below.
  template <typename Value,
            typename = std::enable_if_t<
                !IsSubImpl<y_absl::remove_cvref_t<Value>>::value>>
  ValueImpl(Value&& value)  // NOLINT
      : value(ToStringOrCallback(std::forward<Value>(value), Rank2{})) {
    if (y_absl::holds_alternative<Callback>(this->value)) {
      consume_after = ";,";
    }
  }

  // Copy ctor/assign allow interconversion of the two template parameters.
  template <bool that_owned>
  ValueImpl(const ValueImpl<that_owned>& that) {  // NOLINT
    *this = that;
  }

  template <bool that_owned>
  ValueImpl& operator=(const ValueImpl<that_owned>& that);

  const StringType* AsString() const {
    return y_absl::get_if<StringType>(&value);
  }

  const Callback* AsCallback() const { return y_absl::get_if<Callback>(&value); }

  StringOrCallback value;
  TProtoStringType consume_after;

 private:
  // go/ranked-overloads
  struct Rank0 {};
  struct Rank1 : Rank0 {};
  struct Rank2 : Rank1 {};

  // Dummy template for delayed instantiation, which is required for the
  // static assert below to kick in only when this function is called when it
  // shouldn't.
  //
  // This is done to produce a better error message than the "candidate does
  // not match" SFINAE errors.
  template <typename Cb, typename = decltype(std::declval<Cb&&>()())>
  StringOrCallback ToStringOrCallback(Cb&& cb, Rank2);

  // Separate from the AlphaNum overload to avoid copies when taking strings
  // by value when in `owned` mode.
  StringOrCallback ToStringOrCallback(StringType s, Rank1) { return s; }

  StringOrCallback ToStringOrCallback(const y_absl::AlphaNum& s, Rank0) {
    return StringType(s.Piece());
  }
};

template <bool owned>
template <bool that_owned>
Printer::ValueImpl<owned>& Printer::ValueImpl<owned>::operator=(
    const ValueImpl<that_owned>& that) {
  // Cast to void* is required, since this and that may potentially be of
  // different types (due to the `that_owned` parameter).
  if (static_cast<const void*>(this) == static_cast<const void*>(&that)) {
    return *this;
  }

  using ThatStringType = typename ValueImpl<that_owned>::StringType;

  if (auto* str = y_absl::get_if<ThatStringType>(&that.value)) {
    value = StringType(*str);
  } else {
    value = y_absl::get<Callback>(that.value);
  }

  consume_after = that.consume_after;
  return *this;
}

template <bool owned>
template <typename Cb, typename /*Sfinae*/>
auto Printer::ValueImpl<owned>::ToStringOrCallback(Cb&& cb, Rank2)
    -> StringOrCallback {
  return Callback(
      [cb = std::forward<Cb>(cb), is_called = false]() mutable -> bool {
        if (is_called) {
          // Catch whether or not this function is being called recursively.
          return false;
        }
        is_called = true;
        cb();
        is_called = false;
        return true;
      });
}

struct Printer::AnnotationRecord {
  std::vector<int> path;
  TProtoStringType file_path;
  y_absl::optional<AnnotationCollector::Semantic> semantic;

  // AnnotationRecord's constructors are *not* marked as explicit,
  // specifically so that it is possible to construct a
  // map<string, AnnotationRecord> by writing
  //
  // {{"foo", my_cool_descriptor}, {"bar", "file.proto"}}

  template <
      typename String,
      std::enable_if_t<std::is_convertible<const String&, TProtoStringType>::value,
                       int> = 0>
  AnnotationRecord(  // NOLINT(google-explicit-constructor)
      const String& file_path,
      y_absl::optional<AnnotationCollector::Semantic> semantic = y_absl::nullopt)
      : file_path(file_path), semantic(semantic) {}

  template <typename Desc,
            // This SFINAE clause excludes char* from matching this
            // constructor.
            std::enable_if_t<std::is_class<Desc>::value, int> = 0>
  AnnotationRecord(  // NOLINT(google-explicit-constructor)
      const Desc* desc,
      y_absl::optional<AnnotationCollector::Semantic> semantic = y_absl::nullopt)
      : file_path(desc->file()->name()), semantic(semantic) {
    desc->GetLocationPath(&path);
  }
};

class Printer::Sub {
 public:
  template <typename Value>
  Sub(TProtoStringType key, Value&& value)
      : key_(std::move(key)),
        value_(std::forward<Value>(value)),
        annotation_(y_absl::nullopt) {}

  Sub AnnotatedAs(AnnotationRecord annotation) && {
    annotation_ = std::move(annotation);
    return std::move(*this);
  }

  Sub WithSuffix(TProtoStringType sub_suffix) && {
    value_.consume_after = std::move(sub_suffix);
    return std::move(*this);
  }

  y_absl::string_view key() const { return key_; }

  y_absl::string_view value() const {
    const auto* str = value_.AsString();
    Y_ABSL_CHECK(str != nullptr)
        << "could not find " << key() << "; found callback instead";
    return *str;
  }

 private:
  friend class Printer;

  TProtoStringType key_;
  Value value_;
  y_absl::optional<AnnotationRecord> annotation_;
};

template <typename Map>
auto Printer::WithVars(const Map* vars) {
  var_lookups_.emplace_back(
      [vars](y_absl::string_view var) -> y_absl::optional<ValueView> {
        auto it = vars->find(ToStringKey<Map>(var));
        if (it == vars->end()) {
          return y_absl::nullopt;
        }
        return ValueView(it->second);
      });
  return y_absl::MakeCleanup([this] { var_lookups_.pop_back(); });
}

template <typename Map, typename, typename /*Sfinae*/>
auto Printer::WithVars(Map&& vars) {
  var_lookups_.emplace_back(
      [vars = std::forward<Map>(vars)](
          y_absl::string_view var) -> y_absl::optional<ValueView> {
        auto it = vars.find(ToStringKey<Map>(var));
        if (it == vars.end()) {
          return y_absl::nullopt;
        }
        return ValueView(it->second);
      });
  return y_absl::MakeCleanup([this] { var_lookups_.pop_back(); });
}

template <typename Map>
auto Printer::WithAnnotations(const Map* vars) {
  annotation_lookups_.emplace_back(
      [vars](y_absl::string_view var) -> y_absl::optional<AnnotationRecord> {
        auto it = vars->find(ToStringKey<Map>(var));
        if (it == vars->end()) {
          return y_absl::nullopt;
        }
        return AnnotationRecord(it->second);
      });
  return y_absl::MakeCleanup([this] { annotation_lookups_.pop_back(); });
}

template <typename Map>
auto Printer::WithAnnotations(Map&& vars) {
  annotation_lookups_.emplace_back(
      [vars = std::forward<Map>(vars)](
          y_absl::string_view var) -> y_absl::optional<AnnotationRecord> {
        auto it = vars.find(ToStringKey<Map>(var));
        if (it == vars.end()) {
          return y_absl::nullopt;
        }
        return AnnotationRecord(it->second);
      });
  return y_absl::MakeCleanup([this] { annotation_lookups_.pop_back(); });
}

inline void Printer::Emit(y_absl::string_view format, SourceLocation loc) {
  Emit({}, format, loc);
}

template <typename Map>
void Printer::Print(const Map& vars, y_absl::string_view text) {
  PrintOptions opts;
  opts.checks_are_debug_only = true;
  opts.use_substitution_map = true;
  opts.allow_digit_substitutions = false;

  auto pop = WithVars(&vars);
  PrintImpl(text, {}, opts);
}

template <typename... Args>
void Printer::Print(y_absl::string_view text, const Args&... args) {
  static_assert(sizeof...(args) % 2 == 0, "");

  // Include an extra arg, since a zero-length array is ill-formed, and
  // MSVC complains.
  y_absl::string_view vars[] = {args..., ""};
  y_absl::flat_hash_map<y_absl::string_view, y_absl::string_view> map;
  map.reserve(sizeof...(args) / 2);
  for (size_t i = 0; i < sizeof...(args); i += 2) {
    map.emplace(vars[i], vars[i + 1]);
  }

  Print(map, text);
}

template <typename Desc>
void Printer::Annotate(y_absl::string_view begin_varname,
                       y_absl::string_view end_varname, const Desc* descriptor) {
  if (options_.annotation_collector == nullptr) {
    return;
  }

  std::vector<int> path;
  descriptor->GetLocationPath(&path);
  Annotate(begin_varname, end_varname, descriptor->file()->name(), path);
}

template <typename Map>
void Printer::FormatInternal(y_absl::Span<const TProtoStringType> args,
                             const Map& vars, y_absl::string_view format) {
  PrintOptions opts;
  opts.use_curly_brace_substitutions = true;
  opts.strip_spaces_around_vars = true;

  auto pop = WithVars(&vars);
  PrintImpl(format, args, opts);
}

inline auto Printer::WithDefs(y_absl::Span<const Sub> vars,
                              bool allow_callbacks) {
  y_absl::flat_hash_map<TProtoStringType, Value> var_map;
  var_map.reserve(vars.size());

  y_absl::flat_hash_map<TProtoStringType, AnnotationRecord> annotation_map;

  for (const auto& var : vars) {
    Y_ABSL_CHECK(allow_callbacks || var.value_.AsCallback() == nullptr)
        << "callback arguments are not permitted in this position";
    auto result = var_map.insert({var.key_, var.value_});
    Y_ABSL_CHECK(result.second)
        << "repeated variable in Emit() or WithVars() call: \"" << var.key_
        << "\"";
    if (var.annotation_.has_value()) {
      annotation_map.insert({var.key_, *var.annotation_});
    }
  }

  var_lookups_.emplace_back([map = std::move(var_map)](y_absl::string_view var)
                                -> y_absl::optional<ValueView> {
    auto it = map.find(var);
    if (it == map.end()) {
      return y_absl::nullopt;
    }
    return ValueView(it->second);
  });

  bool has_annotations = !annotation_map.empty();
  if (has_annotations) {
    annotation_lookups_.emplace_back(
        [map = std::move(annotation_map)](
            y_absl::string_view var) -> y_absl::optional<AnnotationRecord> {
          auto it = map.find(var);
          if (it == map.end()) {
            return y_absl::nullopt;
          }
          return it->second;
        });
  }

  return y_absl::MakeCleanup([this, has_annotations] {
    var_lookups_.pop_back();
    if (has_annotations) {
      annotation_lookups_.pop_back();
    }
  });
}

inline auto Printer::WithVars(y_absl::Span<const Sub> vars) {
  return WithDefs(vars, /*allow_callbacks=*/false);
}
}  // namespace io
}  // namespace protobuf
}  // namespace google

#include "google/protobuf/port_undef.inc"

#endif  // GOOGLE_PROTOBUF_IO_PRINTER_H__