aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/protobuf/src/google/protobuf/io/printer.cc
blob: 83ed7d1f69d2e61bdf902c1de5978f0c6a1b4173 (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
// 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.

#include <google/protobuf/io/printer.h>

#include <cctype>

#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/zero_copy_stream.h>

namespace google {
namespace protobuf {
namespace io {

Printer::Printer(ZeroCopyOutputStream* output, char variable_delimiter)
    : variable_delimiter_(variable_delimiter),
      output_(output),
      buffer_(NULL),
      buffer_size_(0),
      offset_(0),
      at_start_of_line_(true),
      failed_(false),
      annotation_collector_(NULL) {}

Printer::Printer(ZeroCopyOutputStream* output, char variable_delimiter,
                 AnnotationCollector* annotation_collector)
    : variable_delimiter_(variable_delimiter),
      output_(output),
      buffer_(NULL),
      buffer_size_(0),
      offset_(0),
      at_start_of_line_(true),
      failed_(false),
      annotation_collector_(annotation_collector) {}

Printer::~Printer() {
  // Only BackUp() if we have called Next() at least once and never failed.
  if (buffer_size_ > 0 && !failed_) {
    output_->BackUp(buffer_size_);
  }
}

bool Printer::GetSubstitutionRange(const char* varname,
                                   std::pair<size_t, size_t>* range) {
  std::map<TProtoStringType, std::pair<size_t, size_t> >::const_iterator iter =
      substitutions_.find(varname);
  if (iter == substitutions_.end()) {
    GOOGLE_LOG(DFATAL) << " Undefined variable in annotation: " << varname;
    return false;
  }
  if (iter->second.first > iter->second.second) {
    GOOGLE_LOG(DFATAL) << " Variable used for annotation used multiple times: "
                << varname;
    return false;
  }
  *range = iter->second;
  return true;
}

void Printer::Annotate(const char* begin_varname, const char* end_varname,
                       const TProtoStringType& file_path,
                       const std::vector<int>& path) {
  if (annotation_collector_ == NULL) {
    // Can't generate signatures with this Printer.
    return;
  }
  std::pair<size_t, size_t> begin, end;
  if (!GetSubstitutionRange(begin_varname, &begin) ||
      !GetSubstitutionRange(end_varname, &end)) {
    return;
  }
  if (begin.first > end.second) {
    GOOGLE_LOG(DFATAL) << "  Annotation has negative length from " << begin_varname
                << " to " << end_varname;
  } else {
    annotation_collector_->AddAnnotation(begin.first, end.second, file_path,
                                         path);
  }
}

void Printer::Print(const std::map<TProtoStringType, TProtoStringType>& variables,
                    const char* text) {
  int size = strlen(text);
  int pos = 0;  // The number of bytes we've written so far.
  substitutions_.clear();
  line_start_variables_.clear();

  for (int i = 0; i < size; i++) {
    if (text[i] == '\n') {
      // Saw newline.  If there is more text, we may need to insert an indent
      // here.  So, write what we have so far, including the '\n'.
      WriteRaw(text + pos, i - pos + 1);
      pos = i + 1;

      // Setting this true will cause the next WriteRaw() to insert an indent
      // first.
      at_start_of_line_ = true;
      line_start_variables_.clear();

    } else if (text[i] == variable_delimiter_) {
      // Saw the start of a variable name.

      // Write what we have so far.
      WriteRaw(text + pos, i - pos);
      pos = i + 1;

      // Find closing delimiter.
      const char* end = strchr(text + pos, variable_delimiter_);
      if (end == NULL) {
        GOOGLE_LOG(DFATAL) << " Unclosed variable name.";
        end = text + pos;
      }
      int endpos = end - text;

      TProtoStringType varname(text + pos, endpos - pos);
      if (varname.empty()) {
        // Two delimiters in a row reduce to a literal delimiter character.
        WriteRaw(&variable_delimiter_, 1);
      } else {
        // Replace with the variable's value.
        std::map<TProtoStringType, TProtoStringType>::const_iterator iter =
            variables.find(varname);
        if (iter == variables.end()) {
          GOOGLE_LOG(DFATAL) << " Undefined variable: " << varname;
        } else {
          if (at_start_of_line_ && iter->second.empty()) {
            line_start_variables_.push_back(varname);
          }
          WriteRaw(iter->second.data(), iter->second.size());
          std::pair<std::map<TProtoStringType, std::pair<size_t, size_t> >::iterator,
                    bool>
              inserted = substitutions_.insert(std::make_pair(
                  varname,
                  std::make_pair(offset_ - iter->second.size(), offset_)));
          if (!inserted.second) {
            // This variable was used multiple times.  Make its span have
            // negative length so we can detect it if it gets used in an
            // annotation.
            inserted.first->second = std::make_pair(1, 0);
          }
        }
      }

      // Advance past this variable.
      i = endpos;
      pos = endpos + 1;
    }
  }

  // Write the rest.
  WriteRaw(text + pos, size - pos);
}

void Printer::Indent() { indent_ += "  "; }

void Printer::Outdent() {
  if (indent_.empty()) {
    GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent().";
    return;
  }

  indent_.resize(indent_.size() - 2);
}

void Printer::PrintRaw(const TProtoStringType& data) {
  WriteRaw(data.data(), data.size());
}

void Printer::PrintRaw(const char* data) {
  if (failed_) return;
  WriteRaw(data, strlen(data));
}

void Printer::WriteRaw(const char* data, int size) {
  if (failed_) return;
  if (size == 0) return;

  if (at_start_of_line_ && (size > 0) && (data[0] != '\n')) {
    // Insert an indent.
    at_start_of_line_ = false;
    CopyToBuffer(indent_.data(), indent_.size());
    if (failed_) return;
    // Fix up empty variables (e.g., "{") that should be annotated as
    // coming after the indent.
    for (std::vector<TProtoStringType>::iterator i = line_start_variables_.begin();
         i != line_start_variables_.end(); ++i) {
      substitutions_[*i].first += indent_.size();
      substitutions_[*i].second += indent_.size();
    }
  }

  // If we're going to write any data, clear line_start_variables_, since
  // we've either updated them in the block above or they no longer refer to
  // the current line.
  line_start_variables_.clear();

  CopyToBuffer(data, size);
}

bool Printer::Next() {
  do {
    void* void_buffer;
    if (!output_->Next(&void_buffer, &buffer_size_)) {
      failed_ = true;
      return false;
    }
    buffer_ = reinterpret_cast<char*>(void_buffer);
  } while (buffer_size_ == 0);
  return true;
}

void Printer::CopyToBuffer(const char* data, int size) {
  if (failed_) return;
  if (size == 0) return;

  while (size > buffer_size_) {
    // Data exceeds space in the buffer.  Copy what we can and request a
    // new buffer.
    if (buffer_size_ > 0) {
      memcpy(buffer_, data, buffer_size_);
      offset_ += buffer_size_;
      data += buffer_size_;
      size -= buffer_size_;
    }
    void* void_buffer;
    failed_ = !output_->Next(&void_buffer, &buffer_size_);
    if (failed_) return;
    buffer_ = reinterpret_cast<char*>(void_buffer);
  }

  // Buffer is big enough to receive the data; copy it.
  memcpy(buffer_, data, size);
  buffer_ += size;
  buffer_size_ -= size;
  offset_ += size;
}

void Printer::IndentIfAtStart() {
  if (at_start_of_line_) {
    CopyToBuffer(indent_.data(), indent_.size());
    at_start_of_line_ = false;
  }
}

void Printer::FormatInternal(const std::vector<TProtoStringType>& args,
                             const std::map<TProtoStringType, TProtoStringType>& vars,
                             const char* format) {
  auto save = format;
  int arg_index = 0;
  std::vector<AnnotationCollector::Annotation> annotations;
  while (*format) {
    char c = *format++;
    switch (c) {
      case '$':
        format = WriteVariable(args, vars, format, &arg_index, &annotations);
        continue;
      case '\n':
        at_start_of_line_ = true;
        line_start_variables_.clear();
        break;
      default:
        IndentIfAtStart();
        break;
    }
    push_back(c);
  }
  if (arg_index != static_cast<int>(args.size())) {
    GOOGLE_LOG(FATAL) << " Unused arguments. " << save;
  }
  if (!annotations.empty()) {
    GOOGLE_LOG(FATAL) << " Annotation range is not-closed, expect $}$. " << save;
  }
}

const char* Printer::WriteVariable(
    const std::vector<TProtoStringType>& args,
    const std::map<TProtoStringType, TProtoStringType>& vars, const char* format,
    int* arg_index, std::vector<AnnotationCollector::Annotation>* annotations) {
  auto start = format;
  auto end = strchr(format, '$');
  if (!end) {
    GOOGLE_LOG(FATAL) << " Unclosed variable name.";
  }
  format = end + 1;
  if (end == start) {
    // "$$" is an escape for just '$'
    IndentIfAtStart();
    push_back('$');
    return format;
  }
  if (*start == '{') {
    GOOGLE_CHECK(std::isdigit(start[1]));
    GOOGLE_CHECK_EQ(end - start, 2);
    int idx = start[1] - '1';
    if (idx < 0 || static_cast<size_t>(idx) >= args.size()) {
      GOOGLE_LOG(FATAL) << "Annotation ${" << idx + 1 << "$ is out of bounds.";
    }
    if (idx > *arg_index) {
      GOOGLE_LOG(FATAL) << "Annotation arg must be in correct order as given. Expected"
                 << " ${" << (*arg_index) + 1 << "$ got ${" << idx + 1 << "$.";
    } else if (idx == *arg_index) {
      (*arg_index)++;
    }
    IndentIfAtStart();
    annotations->push_back({{offset_, 0}, args[idx]});
    return format;
  } else if (*start == '}') {
    GOOGLE_CHECK(annotations);
    if (annotations->empty()) {
      GOOGLE_LOG(FATAL) << "Unexpected end of annotation found.";
    }
    auto& a = annotations->back();
    a.first.second = offset_;
    if (annotation_collector_) annotation_collector_->AddAnnotationNew(a);
    annotations->pop_back();
    return format;
  }
  auto start_var = start;
  while (start_var < end && *start_var == ' ') start_var++;
  if (start_var == end) {
    GOOGLE_LOG(FATAL) << " Empty variable.";
  }
  auto end_var = end;
  while (start_var < end_var && *(end_var - 1) == ' ') end_var--;
  TProtoStringType var_name{
      start_var, static_cast<TProtoStringType::size_type>(end_var - start_var)};
  TProtoStringType sub;
  if (std::isdigit(var_name[0])) {
    GOOGLE_CHECK_EQ(var_name.size(), 1U);  // No need for multi-digits
    int idx = var_name[0] - '1';   // Start counting at 1
    GOOGLE_CHECK_GE(idx, 0);
    if (static_cast<size_t>(idx) >= args.size()) {
      GOOGLE_LOG(FATAL) << "Argument $" << idx + 1 << "$ is out of bounds.";
    }
    if (idx > *arg_index) {
      GOOGLE_LOG(FATAL) << "Arguments must be used in same order as given. Expected $"
                 << (*arg_index) + 1 << "$ got $" << idx + 1 << "$.";
    } else if (idx == *arg_index) {
      (*arg_index)++;
    }
    sub = args[idx];
  } else {
    auto it = vars.find(var_name);
    if (it == vars.end()) {
      GOOGLE_LOG(FATAL) << " Unknown variable: " << var_name << ".";
    }
    sub = it->second;
  }

  // By returning here in case of empty we also skip possible spaces inside
  // the $...$, i.e. "void$ dllexpor$ f();" -> "void f();" in the empty case.
  if (sub.empty()) return format;

  // We're going to write something non-empty so we need a possible indent.
  IndentIfAtStart();

  // Write the possible spaces in front.
  CopyToBuffer(start, start_var - start);
  // Write a non-empty substituted variable.
  CopyToBuffer(sub.c_str(), sub.size());
  // Finish off with writing possible trailing spaces.
  CopyToBuffer(end_var, end - end_var);
  return format;
}

}  // namespace io
}  // namespace protobuf
}  // namespace google