@@ -354,21 +354,26 @@ function toJsType(field) {
354
354
return type ;
355
355
}
356
356
357
- function isOptional ( type , field ) {
358
-
359
- // Figure out if a field is explicitly marked optional, depending on the proto syntax (proto2 vs proto3)
360
- // If the syntax has not been recorded in the AST, proto2 semantics will be the default
357
+ function syntaxForType ( type ) {
361
358
362
359
var syntax = null ;
363
360
var namespace = type ;
364
361
365
362
while ( syntax === null && namespace !== null ) {
366
363
if ( namespace . options != null && "syntax" in namespace . options )
367
- syntax = namespace . options [ "syntax" ]
364
+ syntax = namespace . options [ "syntax" ] ;
368
365
else
369
- namespace = namespace . parent
366
+ namespace = namespace . parent ;
370
367
}
371
368
369
+ if ( syntax === "proto3" )
370
+ return "proto3" ;
371
+ else
372
+ return "proto2" ;
373
+ }
374
+
375
+ function isOptional ( field , syntax ) {
376
+
372
377
if ( syntax === "proto3" )
373
378
return field . proto3Optional
374
379
else
@@ -377,6 +382,8 @@ function isOptional(type, field) {
377
382
378
383
function buildType ( ref , type ) {
379
384
385
+ var syntax = syntaxForType ( type ) ;
386
+
380
387
if ( config . comments ) {
381
388
var typeDef = [
382
389
"Properties of " + aOrAn ( type . name ) + "." ,
@@ -392,7 +399,7 @@ function buildType(ref, type) {
392
399
// New behaviour - fields explicitly marked as optional and members of a one-of are nullable
393
400
// Maps and repeated fields are not explicitly optional, they default to empty instances
394
401
if ( config [ "force-optional" ] ) {
395
- if ( isOptional ( type , field ) || field . partOf ) {
402
+ if ( isOptional ( field , syntax ) || field . partOf ) {
396
403
jsType = jsType + "|null|undefined" ;
397
404
nullable = true ;
398
405
}
@@ -435,7 +442,7 @@ function buildType(ref, type) {
435
442
// New behaviour - fields explicitly marked as optional and members of a one-of are nullable
436
443
// Maps and repeated fields are not explicitly optional, they default to empty instances
437
444
if ( config [ "force-optional" ] ) {
438
- if ( isOptional ( type , field ) || field . partOf )
445
+ if ( isOptional ( field , syntax ) || field . partOf )
439
446
jsType = jsType + "|null|undefined" ;
440
447
}
441
448
// Old behaviour - field.optional is true for all fields in proto3
@@ -457,7 +464,7 @@ function buildType(ref, type) {
457
464
// New behaviour sets a null default when the optional keyword is used explicitly
458
465
// Old behaviour considers all proto3 fields optional and uses the null-defaults config flag
459
466
var nullDefault = config [ "force-optional" ]
460
- ? isOptional ( type , field )
467
+ ? isOptional ( field , syntax )
461
468
: field . optional && config [ "null-defaults" ] ;
462
469
if ( field . repeated )
463
470
push ( escapeName ( type . name ) + ".prototype" + prop + " = $util.emptyArray;" ) ; // overwritten in constructor
0 commit comments