-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathjs_generator.cc
3939 lines (3586 loc) · 141 KB
/
js_generator.cc
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
// 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.
#include <assert.h>
#include "generator/well_known_types_embed.h"
#include <google/protobuf/compiler/scc.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/stubs/strutil.h>
#include <algorithm>
#include <limits>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "generator/js_generator.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace js {
// Sorted list of JavaScript keywords. These cannot be used as names. If they
// appear, we prefix them with "pb_".
const char* kKeyword[] = {
"abstract", "boolean", "break", "byte", "case",
"catch", "char", "class", "const", "continue",
"debugger", "default", "delete", "do", "double",
"else", "enum", "export", "extends", "false",
"final", "finally", "float", "for", "function",
"goto", "if", "implements", "import", "in",
"instanceof", "int", "interface", "long", "native",
"new", "null", "package", "private", "protected",
"public", "return", "short", "static", "super",
"switch", "synchronized", "this", "throw", "throws",
"transient", "try", "typeof", "var", "void",
"volatile", "while", "with",
};
static const int kNumKeyword = sizeof(kKeyword) / sizeof(char*);
namespace {
// The mode of operation for bytes fields. Historically JSPB always carried
// bytes as JS {string}, containing base64 content by convention. With binary
// and proto3 serialization the new convention is to represent it as binary
// data in Uint8Array. See b/26173701 for background on the migration.
enum BytesMode {
BYTES_DEFAULT, // Default type for getBytesField to return.
BYTES_B64, // Explicitly coerce to base64 string where needed.
BYTES_U8, // Explicitly coerce to Uint8Array where needed.
};
bool IsReserved(const std::string& ident) {
for (int i = 0; i < kNumKeyword; i++) {
if (ident == kKeyword[i]) {
return true;
}
}
return false;
}
std::string GetSnakeFilename(const std::string& filename) {
std::string snake_name = filename;
ReplaceCharacters(&snake_name, "/", '_');
return snake_name;
}
// Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
// file foo/bar/baz.js.
std::string GetJSFilename(const GeneratorOptions& options,
const std::string& filename) {
return StripProto(filename) + options.GetFileNameExtension();
}
// Given a filename like foo/bar/baz.proto, returns the root directory
// path ../../
std::string GetRootPath(const std::string& from_filename,
const std::string& to_filename) {
if (to_filename.find("google/protobuf") == 0) {
// Well-known types (.proto files in the google/protobuf directory) are
// assumed to come from the 'google-protobuf' npm package. We may want to
// generalize this exception later by letting others put generated code in
// their own npm packages.
return "google-protobuf/";
}
size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
if (slashes == 0) {
return "./";
}
std::string result = "";
for (size_t i = 0; i < slashes; i++) {
result += "../";
}
return result;
}
// Returns the alias we assign to the module of the given .proto filename
// when importing.
std::string ModuleAlias(const std::string& filename) {
// This scheme could technically cause problems if a file includes any 2 of:
// foo/bar_baz.proto
// foo_bar_baz.proto
// foo_bar/baz.proto
//
// We'll worry about this problem if/when we actually see it. This name isn't
// exposed to users so we can change it later if we need to.
std::string basename = StripProto(filename);
ReplaceCharacters(&basename, "-", '$');
ReplaceCharacters(&basename, "/", '_');
ReplaceCharacters(&basename, ".", '_');
return basename + "_pb";
}
// Returns the fully normalized JavaScript namespace for the given
// file descriptor's package.
std::string GetNamespace(const GeneratorOptions& options,
const FileDescriptor* file) {
if (!options.namespace_prefix.empty()) {
return options.namespace_prefix;
} else if (!file->package().empty()) {
return "proto." + file->package();
} else {
return "proto";
}
}
// Returns the name of the message with a leading dot and taking into account
// nesting, for example ".OuterMessage.InnerMessage", or returns empty if
// descriptor is null. This function does not handle namespacing, only message
// nesting.
std::string GetNestedMessageName(const Descriptor* descriptor) {
if (descriptor == NULL) {
return "";
}
std::string result =
StripPrefixString(descriptor->full_name(), descriptor->file()->package());
// Add a leading dot if one is not already present.
if (!result.empty() && result[0] != '.') {
result = "." + result;
}
return result;
}
// Returns the path prefix for a message or enumeration that
// lives under the given file and containing type.
std::string GetPrefix(const GeneratorOptions& options,
const FileDescriptor* file_descriptor,
const Descriptor* containing_type) {
std::string prefix = GetNamespace(options, file_descriptor) +
GetNestedMessageName(containing_type);
if (!prefix.empty()) {
prefix += ".";
}
return prefix;
}
// Returns the fully normalized JavaScript path prefix for the given
// message descriptor.
std::string GetMessagePathPrefix(const GeneratorOptions& options,
const Descriptor* descriptor) {
return GetPrefix(options, descriptor->file(), descriptor->containing_type());
}
// Returns the fully normalized JavaScript path for the given
// message descriptor.
std::string GetMessagePath(const GeneratorOptions& options,
const Descriptor* descriptor) {
return GetMessagePathPrefix(options, descriptor) + descriptor->name();
}
// Returns the fully normalized JavaScript path prefix for the given
// enumeration descriptor.
std::string GetEnumPathPrefix(const GeneratorOptions& options,
const EnumDescriptor* enum_descriptor) {
return GetPrefix(options, enum_descriptor->file(),
enum_descriptor->containing_type());
}
// Returns the fully normalized JavaScript path for the given
// enumeration descriptor.
std::string GetEnumPath(const GeneratorOptions& options,
const EnumDescriptor* enum_descriptor) {
return GetEnumPathPrefix(options, enum_descriptor) + enum_descriptor->name();
}
std::string MaybeCrossFileRef(const GeneratorOptions& options,
const FileDescriptor* from_file,
const Descriptor* to_message) {
if ((options.import_style == GeneratorOptions::kImportCommonJs ||
options.import_style == GeneratorOptions::kImportCommonJsStrict) &&
from_file != to_message->file()) {
// Cross-file ref in CommonJS needs to use the module alias instead of
// the global name.
return ModuleAlias(to_message->file()->name()) +
GetNestedMessageName(to_message->containing_type()) + "." +
to_message->name();
} else {
// Within a single file we use a full name.
return GetMessagePath(options, to_message);
}
}
std::string SubmessageTypeRef(const GeneratorOptions& options,
const FieldDescriptor* field) {
GOOGLE_CHECK(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE);
return MaybeCrossFileRef(options, field->file(), field->message_type());
}
// - Object field name: LOWER_UNDERSCORE -> LOWER_CAMEL, except for group fields
// (UPPER_CAMEL -> LOWER_CAMEL), with "List" (or "Map") appended if appropriate,
// and with reserved words triggering a "pb_" prefix.
// - Getters/setters: LOWER_UNDERSCORE -> UPPER_CAMEL, except for group fields
// (use the name directly), then append "List" if appropriate, then append "$"
// if resulting name is equal to a reserved word.
// - Enums: just uppercase.
// Locale-independent version of ToLower that deals only with ASCII A-Z.
char ToLowerASCII(char c) {
if (c >= 'A' && c <= 'Z') {
return (c - 'A') + 'a';
} else {
return c;
}
}
std::vector<std::string> ParseLowerUnderscore(const std::string& input) {
std::vector<std::string> words;
std::string running = "";
for (auto c : input) {
if (c == '_') {
if (!running.empty()) {
words.push_back(running);
running.clear();
}
} else {
running += ToLowerASCII(c);
}
}
if (!running.empty()) {
words.push_back(running);
}
return words;
}
std::vector<std::string> ParseUpperCamel(const std::string& input) {
std::vector<std::string> words;
std::string running = "";
for (auto c : input) {
if (c >= 'A' && c <= 'Z' && !running.empty()) {
words.push_back(running);
running.clear();
}
running += ToLowerASCII(c);
}
if (!running.empty()) {
words.push_back(running);
}
return words;
}
std::string ToLowerCamel(const std::vector<std::string>& words) {
std::string result;
auto first = true;
for (auto word : words) {
if (first && (word[0] >= 'A' && word[0] <= 'Z')) {
word[0] = (word[0] - 'A') + 'a';
} else if (!first && (word[0] >= 'a' && word[0] <= 'z')) {
word[0] = (word[0] - 'a') + 'A';
}
result += word;
first = false;
}
return result;
}
std::string ToUpperCamel(const std::vector<std::string>& words) {
std::string result;
for (auto word : words) {
if (word[0] >= 'a' && word[0] <= 'z') {
word[0] = (word[0] - 'a') + 'A';
}
result += word;
}
return result;
}
// Based on code from descriptor.cc (Thanks Kenton!)
// Uppercases the entire string, turning ValueName into
// VALUENAME.
std::string ToEnumCase(const std::string& input) {
std::string result;
result.reserve(input.size());
for (auto c : input) {
if ('a' <= c && c <= 'z') {
result.push_back(c - 'a' + 'A');
} else {
result.push_back(c);
}
}
return result;
}
std::string ToLower(const std::string& input) {
std::string result;
result.reserve(input.size());
for (auto c : input) {
if ('A' <= c && c <= 'Z') {
result.push_back(c - 'A' + 'a');
} else {
result.push_back(c);
}
}
return result;
}
// When we're generating one output file per SCC, this is the filename
// that top-level extensions should go in.
// e.g. one proto file (test.proto):
// package a;
// extends Foo {
// ...
// }
// If "with_filename" equals true, the extension filename will be
// "proto.a_test_extensions.js", otherwise will be "proto.a.js"
std::string GetExtensionFileName(const GeneratorOptions& options,
const FileDescriptor* file,
bool with_filename) {
std::string snake_name = StripProto(GetSnakeFilename(file->name()));
return options.output_dir + "/" + ToLower(GetNamespace(options, file)) +
(with_filename ? ("_" + snake_name + "_extensions") : "") +
options.GetFileNameExtension();
}
// When we're generating one output file per SCC, this is the filename
// that all messages in the SCC should go in.
// If with_package equals true, filename will have package prefix,
// If the filename length is longer than 200, the filename will be the
// SCC's proto filename with suffix "_long_sccs_(index)" (if with_package equals
// true it still has package prefix)
std::string GetMessagesFileName(const GeneratorOptions& options, const SCC* scc,
bool with_package) {
static std::map<const Descriptor*, std::string>* long_name_dict =
new std::map<const Descriptor*, std::string>();
std::string package_base =
with_package
? ToLower(GetNamespace(options, scc->GetRepresentative()->file()) +
"_")
: "";
std::string filename_base = "";
std::vector<std::string> all_message_names;
for (auto one_desc : scc->descriptors) {
if (one_desc->containing_type() == nullptr) {
all_message_names.push_back(ToLower(one_desc->name()));
}
}
sort(all_message_names.begin(), all_message_names.end());
for (auto one_message : all_message_names) {
if (!filename_base.empty()) {
filename_base += "_";
}
filename_base += one_message;
}
if (filename_base.size() + package_base.size() > 200) {
if ((*long_name_dict).find(scc->GetRepresentative()) ==
(*long_name_dict).end()) {
std::string snake_name = StripProto(
GetSnakeFilename(scc->GetRepresentative()->file()->name()));
(*long_name_dict)[scc->GetRepresentative()] =
StrCat(snake_name, "_long_sccs_",
static_cast<uint64_t>((*long_name_dict).size()));
}
filename_base = (*long_name_dict)[scc->GetRepresentative()];
}
return options.output_dir + "/" + package_base + filename_base +
options.GetFileNameExtension();
}
// When we're generating one output file per type name, this is the filename
// that a top-level enum should go in.
// If with_package equals true, filename will have package prefix.
std::string GetEnumFileName(const GeneratorOptions& options,
const EnumDescriptor* desc, bool with_package) {
return options.output_dir + "/" +
(with_package ? ToLower(GetNamespace(options, desc->file()) + "_")
: "") +
ToLower(desc->name()) + options.GetFileNameExtension();
}
// Returns the message/response ID, if set.
std::string GetMessageId(const Descriptor* desc) { return std::string(); }
bool IgnoreExtensionField(const FieldDescriptor* field) {
// Exclude descriptor extensions from output "to avoid clutter" (from original
// codegen).
if (!field->is_extension()) return false;
const FileDescriptor* file = field->containing_type()->file();
return file->name() == "net/proto2/proto/descriptor.proto" ||
file->name() == "google/protobuf/descriptor.proto";
}
// Used inside Google only -- do not remove.
bool IsResponse(const Descriptor* desc) { return false; }
bool IgnoreField(const FieldDescriptor* field) {
return IgnoreExtensionField(field);
}
// Do we ignore this message type?
bool IgnoreMessage(const Descriptor* d) { return d->options().map_entry(); }
// Does JSPB ignore this entire oneof? True only if all fields are ignored.
bool IgnoreOneof(const OneofDescriptor* oneof) {
if (oneof->is_synthetic()) return true;
for (int i = 0; i < oneof->field_count(); i++) {
if (!IgnoreField(oneof->field(i))) {
return false;
}
}
return true;
}
std::string JSIdent(const GeneratorOptions& options,
const FieldDescriptor* field, bool is_upper_camel,
bool is_map, bool drop_list) {
std::string result;
if (field->type() == FieldDescriptor::TYPE_GROUP) {
result = is_upper_camel
? ToUpperCamel(ParseUpperCamel(field->message_type()->name()))
: ToLowerCamel(ParseUpperCamel(field->message_type()->name()));
} else {
result = is_upper_camel ? ToUpperCamel(ParseLowerUnderscore(field->name()))
: ToLowerCamel(ParseLowerUnderscore(field->name()));
}
if (is_map || field->is_map()) {
// JSPB-style or proto3-style map.
result += "Map";
} else if (!drop_list && field->is_repeated()) {
// Repeated field.
result += "List";
}
return result;
}
std::string JSObjectFieldName(const GeneratorOptions& options,
const FieldDescriptor* field) {
std::string name = JSIdent(options, field,
/* is_upper_camel = */ false,
/* is_map = */ false,
/* drop_list = */ false);
if (IsReserved(name)) {
name = "pb_" + name;
}
return name;
}
std::string JSByteGetterSuffix(BytesMode bytes_mode) {
switch (bytes_mode) {
case BYTES_DEFAULT:
return "";
case BYTES_B64:
return "B64";
case BYTES_U8:
return "U8";
default:
assert(false);
}
return "";
}
// Returns the field name as a capitalized portion of a getter/setter method
// name, e.g. MyField for .getMyField().
std::string JSGetterName(const GeneratorOptions& options,
const FieldDescriptor* field,
BytesMode bytes_mode = BYTES_DEFAULT,
bool drop_list = false) {
std::string name = JSIdent(options, field,
/* is_upper_camel = */ true,
/* is_map = */ false, drop_list);
if (field->type() == FieldDescriptor::TYPE_BYTES) {
std::string suffix = JSByteGetterSuffix(bytes_mode);
if (!suffix.empty()) {
name += "_as" + suffix;
}
}
if (name == "Extension" || name == "JsPbMessageId") {
// Avoid conflicts with base-class names.
name += "$";
}
return name;
}
std::string JSOneofName(const OneofDescriptor* oneof) {
return ToUpperCamel(ParseLowerUnderscore(oneof->name()));
}
// Returns the index corresponding to this field in the JSPB array (underlying
// data storage array).
std::string JSFieldIndex(const FieldDescriptor* field) {
// Determine whether this field is a member of a group. Group fields are a bit
// wonky: their "containing type" is a message type created just for the
// group, and that type's parent type has a field with the group-message type
// as its message type and TYPE_GROUP as its field type. For such fields, the
// index we use is relative to the field number of the group submessage field.
// For all other fields, we just use the field number.
const Descriptor* containing_type = field->containing_type();
const Descriptor* parent_type = containing_type->containing_type();
if (parent_type != NULL) {
for (int i = 0; i < parent_type->field_count(); i++) {
if (parent_type->field(i)->type() == FieldDescriptor::TYPE_GROUP &&
parent_type->field(i)->message_type() == containing_type) {
return StrCat(field->number() - parent_type->field(i)->number());
}
}
}
return StrCat(field->number());
}
std::string JSOneofIndex(const OneofDescriptor* oneof) {
int index = -1;
for (int i = 0; i < oneof->containing_type()->oneof_decl_count(); i++) {
const OneofDescriptor* o = oneof->containing_type()->oneof_decl(i);
if (o->is_synthetic()) continue;
// If at least one field in this oneof is not JSPB-ignored, count the oneof.
for (int j = 0; j < o->field_count(); j++) {
const FieldDescriptor* f = o->field(j);
if (!IgnoreField(f)) {
index++;
break; // inner loop
}
}
if (o == oneof) {
break;
}
}
return StrCat(index);
}
// Decodes a codepoint in \x0000 -- \xFFFF.
uint16_t DecodeUTF8Codepoint(uint8_t* bytes, size_t* length) {
if (*length == 0) {
return 0;
}
size_t expected = 0;
if ((*bytes & 0x80) == 0) {
expected = 1;
} else if ((*bytes & 0xe0) == 0xc0) {
expected = 2;
} else if ((*bytes & 0xf0) == 0xe0) {
expected = 3;
} else {
// Too long -- don't accept.
*length = 0;
return 0;
}
if (*length < expected) {
// Not enough bytes -- don't accept.
*length = 0;
return 0;
}
*length = expected;
switch (expected) {
case 1:
return bytes[0];
case 2:
return ((bytes[0] & 0x1F) << 6) | ((bytes[1] & 0x3F) << 0);
case 3:
return ((bytes[0] & 0x0F) << 12) | ((bytes[1] & 0x3F) << 6) |
((bytes[2] & 0x3F) << 0);
default:
return 0;
}
}
// Escapes the contents of a string to be included within double-quotes ("") in
// JavaScript. The input data should be a UTF-8 encoded C++ string of chars.
// Returns false if |out| was truncated because |in| contained invalid UTF-8 or
// codepoints outside the BMP.
// TODO(b/115551870): Support codepoints outside the BMP.
bool EscapeJSString(const std::string& in, std::string* out) {
size_t decoded = 0;
for (size_t i = 0; i < in.size(); i += decoded) {
uint16_t codepoint = 0;
// Decode the next UTF-8 codepoint.
size_t have_bytes = in.size() - i;
uint8_t bytes[3] = {
static_cast<uint8_t>(in[i]),
static_cast<uint8_t>(((i + 1) < in.size()) ? in[i + 1] : 0),
static_cast<uint8_t>(((i + 2) < in.size()) ? in[i + 2] : 0),
};
codepoint = DecodeUTF8Codepoint(bytes, &have_bytes);
if (have_bytes == 0) {
return false;
}
decoded = have_bytes;
switch (codepoint) {
case '\'':
*out += "\\x27";
break;
case '"':
*out += "\\x22";
break;
case '<':
*out += "\\x3c";
break;
case '=':
*out += "\\x3d";
break;
case '>':
*out += "\\x3e";
break;
case '&':
*out += "\\x26";
break;
case '\b':
*out += "\\b";
break;
case '\t':
*out += "\\t";
break;
case '\n':
*out += "\\n";
break;
case '\f':
*out += "\\f";
break;
case '\r':
*out += "\\r";
break;
case '\\':
*out += "\\\\";
break;
default:
// TODO(b/115551870): Once we're supporting codepoints outside the BMP,
// use a single Unicode codepoint escape if the output language is
// ECMAScript 2015 or above. Otherwise, use a surrogate pair.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals
if (codepoint >= 0x20 && codepoint <= 0x7e) {
*out += static_cast<char>(codepoint);
} else if (codepoint >= 0x100) {
*out += StringPrintf("\\u%04x", codepoint);
} else {
*out += StringPrintf("\\x%02x", codepoint);
}
break;
}
}
return true;
}
std::string EscapeBase64(const std::string& in) {
static const char* kAlphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string result;
for (size_t i = 0; i < in.size(); i += 3) {
int value = (in[i] << 16) | (((i + 1) < in.size()) ? (in[i + 1] << 8) : 0) |
(((i + 2) < in.size()) ? (in[i + 2] << 0) : 0);
result += kAlphabet[(value >> 18) & 0x3f];
result += kAlphabet[(value >> 12) & 0x3f];
if ((i + 1) < in.size()) {
result += kAlphabet[(value >> 6) & 0x3f];
} else {
result += '=';
}
if ((i + 2) < in.size()) {
result += kAlphabet[(value >> 0) & 0x3f];
} else {
result += '=';
}
}
return result;
}
// Post-process the result of SimpleFtoa/SimpleDtoa to *exactly* match the
// original codegen's formatting (which is just .toString() on java.lang.Double
// or java.lang.Float).
std::string PostProcessFloat(std::string result) {
// If inf, -inf or nan, replace with +Infinity, -Infinity or NaN.
if (result == "inf") {
return "Infinity";
} else if (result == "-inf") {
return "-Infinity";
} else if (result == "nan") {
return "NaN";
}
// If scientific notation (e.g., "1e10"), (i) capitalize the "e", (ii)
// ensure that the mantissa (portion prior to the "e") has at least one
// fractional digit (after the decimal point), and (iii) strip any unnecessary
// leading zeroes and/or '+' signs from the exponent.
std::string::size_type exp_pos = result.find('e');
if (exp_pos != std::string::npos) {
std::string mantissa = result.substr(0, exp_pos);
std::string exponent = result.substr(exp_pos + 1);
// Add ".0" to mantissa if no fractional part exists.
if (mantissa.find('.') == std::string::npos) {
mantissa += ".0";
}
// Strip the sign off the exponent and store as |exp_neg|.
bool exp_neg = false;
if (!exponent.empty() && exponent[0] == '+') {
exponent = exponent.substr(1);
} else if (!exponent.empty() && exponent[0] == '-') {
exp_neg = true;
exponent = exponent.substr(1);
}
// Strip any leading zeroes off the exponent.
while (exponent.size() > 1 && exponent[0] == '0') {
exponent = exponent.substr(1);
}
return mantissa + "E" + std::string(exp_neg ? "-" : "") + exponent;
}
// Otherwise, this is an ordinary decimal number. Append ".0" if result has no
// decimal/fractional part in order to match output of original codegen.
if (result.find('.') == std::string::npos) {
result += ".0";
}
return result;
}
std::string FloatToString(float value) {
std::string result = SimpleFtoa(value);
return PostProcessFloat(result);
}
std::string DoubleToString(double value) {
std::string result = SimpleDtoa(value);
return PostProcessFloat(result);
}
bool InRealOneof(const FieldDescriptor* field) {
return field->containing_oneof() &&
!field->containing_oneof()->is_synthetic();
}
// Return true if this is an integral field that should be represented as string
// in JS.
bool IsIntegralFieldWithStringJSType(const FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT64:
case FieldDescriptor::CPPTYPE_UINT64:
// The default value of JSType is JS_NORMAL, which behaves the same as
// JS_NUMBER.
return field->options().jstype() == FieldOptions::JS_STRING;
default:
return false;
}
}
std::string MaybeNumberString(const FieldDescriptor* field,
const std::string& orig) {
return IsIntegralFieldWithStringJSType(field) ? ("\"" + orig + "\"") : orig;
}
std::string JSFieldDefault(const FieldDescriptor* field) {
if (field->is_repeated()) {
return "[]";
}
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return MaybeNumberString(field, StrCat(field->default_value_int32()));
case FieldDescriptor::CPPTYPE_UINT32:
// The original codegen is in Java, and Java protobufs store unsigned
// integer values as signed integer values. In order to exactly match the
// output, we need to reinterpret as base-2 signed. Ugh.
return MaybeNumberString(
field, StrCat(static_cast<int32_t>(field->default_value_uint32())));
case FieldDescriptor::CPPTYPE_INT64:
return MaybeNumberString(field, StrCat(field->default_value_int64()));
case FieldDescriptor::CPPTYPE_UINT64:
// See above note for uint32 -- reinterpreting as signed.
return MaybeNumberString(
field, StrCat(static_cast<int64_t>(field->default_value_uint64())));
case FieldDescriptor::CPPTYPE_ENUM:
return StrCat(field->default_value_enum()->number());
case FieldDescriptor::CPPTYPE_BOOL:
return field->default_value_bool() ? "true" : "false";
case FieldDescriptor::CPPTYPE_FLOAT:
return FloatToString(field->default_value_float());
case FieldDescriptor::CPPTYPE_DOUBLE:
return DoubleToString(field->default_value_double());
case FieldDescriptor::CPPTYPE_STRING:
if (field->type() == FieldDescriptor::TYPE_STRING) {
std::string out;
bool is_valid = EscapeJSString(field->default_value_string(), &out);
if (!is_valid) {
// TODO(b/115551870): Decide whether this should be a hard error.
GOOGLE_LOG(WARNING)
<< "The default value for field " << field->full_name()
<< " was truncated since it contained invalid UTF-8 or"
" codepoints outside the basic multilingual plane.";
}
return "\"" + out + "\"";
} else { // Bytes
return "\"" + EscapeBase64(field->default_value_string()) + "\"";
}
case FieldDescriptor::CPPTYPE_MESSAGE:
return "null";
}
GOOGLE_LOG(FATAL) << "Shouldn't reach here.";
return "";
}
std::string ProtoTypeName(const GeneratorOptions& options,
const FieldDescriptor* field) {
switch (field->type()) {
case FieldDescriptor::TYPE_BOOL:
return "bool";
case FieldDescriptor::TYPE_INT32:
return "int32";
case FieldDescriptor::TYPE_UINT32:
return "uint32";
case FieldDescriptor::TYPE_SINT32:
return "sint32";
case FieldDescriptor::TYPE_FIXED32:
return "fixed32";
case FieldDescriptor::TYPE_SFIXED32:
return "sfixed32";
case FieldDescriptor::TYPE_INT64:
return "int64";
case FieldDescriptor::TYPE_UINT64:
return "uint64";
case FieldDescriptor::TYPE_SINT64:
return "sint64";
case FieldDescriptor::TYPE_FIXED64:
return "fixed64";
case FieldDescriptor::TYPE_SFIXED64:
return "sfixed64";
case FieldDescriptor::TYPE_FLOAT:
return "float";
case FieldDescriptor::TYPE_DOUBLE:
return "double";
case FieldDescriptor::TYPE_STRING:
return "string";
case FieldDescriptor::TYPE_BYTES:
return "bytes";
case FieldDescriptor::TYPE_GROUP:
return GetMessagePath(options, field->message_type());
case FieldDescriptor::TYPE_ENUM:
return GetEnumPath(options, field->enum_type());
case FieldDescriptor::TYPE_MESSAGE:
return GetMessagePath(options, field->message_type());
default:
return "";
}
}
std::string JSIntegerTypeName(const FieldDescriptor* field) {
return IsIntegralFieldWithStringJSType(field) ? "string" : "number";
}
std::string JSStringTypeName(const GeneratorOptions& options,
const FieldDescriptor* field,
BytesMode bytes_mode) {
if (field->type() == FieldDescriptor::TYPE_BYTES) {
switch (bytes_mode) {
case BYTES_DEFAULT:
return "(string|Uint8Array)";
case BYTES_B64:
return "string";
case BYTES_U8:
return "Uint8Array";
default:
assert(false);
}
}
return "string";
}
std::string JSTypeName(const GeneratorOptions& options,
const FieldDescriptor* field, BytesMode bytes_mode) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_BOOL:
return "boolean";
case FieldDescriptor::CPPTYPE_INT32:
return JSIntegerTypeName(field);
case FieldDescriptor::CPPTYPE_INT64:
return JSIntegerTypeName(field);
case FieldDescriptor::CPPTYPE_UINT32:
return JSIntegerTypeName(field);
case FieldDescriptor::CPPTYPE_UINT64:
return JSIntegerTypeName(field);
case FieldDescriptor::CPPTYPE_FLOAT:
return "number";
case FieldDescriptor::CPPTYPE_DOUBLE:
return "number";
case FieldDescriptor::CPPTYPE_STRING:
return JSStringTypeName(options, field, bytes_mode);
case FieldDescriptor::CPPTYPE_ENUM:
return GetEnumPath(options, field->enum_type());
case FieldDescriptor::CPPTYPE_MESSAGE:
return GetMessagePath(options, field->message_type());
default:
return "";
}
}
// Used inside Google only -- do not remove.
bool UseBrokenPresenceSemantics(const GeneratorOptions& options,
const FieldDescriptor* field) {
return false;
}
// Returns true for fields that return "null" from accessors when they are
// unset. This should normally only be true for non-repeated submessages, but we
// have legacy users who relied on old behavior where accessors behaved this
// way.
bool ReturnsNullWhenUnset(const GeneratorOptions& options,
const FieldDescriptor* field) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
field->is_optional()) {
return true;
}
// TODO(haberman): remove this case and unconditionally return false.
return UseBrokenPresenceSemantics(options, field) && !field->is_repeated() &&
!field->has_default_value();
}
// In a sane world, this would be the same as ReturnsNullWhenUnset(). But in
// the status quo, some fields declare that they never return null/undefined
// even though they actually do:
// * required fields
// * optional enum fields
// * proto3 primitive fields.
bool DeclaredReturnTypeIsNullable(const GeneratorOptions& options,
const FieldDescriptor* field) {
if (field->is_required() || field->type() == FieldDescriptor::TYPE_ENUM) {
return false;
}
if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 &&
field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
return false;
}
return ReturnsNullWhenUnset(options, field);
}
bool SetterAcceptsUndefined(const GeneratorOptions& options,
const FieldDescriptor* field) {
if (ReturnsNullWhenUnset(options, field)) {
return true;
}
// Broken presence semantics always accepts undefined for setters.
return UseBrokenPresenceSemantics(options, field);
}