You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1123 lines
35 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #import "GPBDescriptor_PackagePrivate.h"
  31. #import <objc/runtime.h>
  32. #import "GPBUtilities_PackagePrivate.h"
  33. #import "GPBWireFormat.h"
  34. #import "GPBMessage_PackagePrivate.h"
  35. // Direct access is use for speed, to avoid even internally declaring things
  36. // read/write, etc. The warning is enabled in the project to ensure code calling
  37. // protos can turn on -Wdirect-ivar-access without issues.
  38. #pragma clang diagnostic push
  39. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  40. // The addresses of these variables are used as keys for objc_getAssociatedObject.
  41. static const char kTextFormatExtraValueKey = 0;
  42. static const char kParentClassNameValueKey = 0;
  43. static const char kClassNameSuffixKey = 0;
  44. // Utility function to generate selectors on the fly.
  45. static SEL SelFromStrings(const char *prefix, const char *middle,
  46. const char *suffix, BOOL takesArg) {
  47. if (prefix == NULL && suffix == NULL && !takesArg) {
  48. return sel_getUid(middle);
  49. }
  50. const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0;
  51. const size_t middleLen = strlen(middle);
  52. const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0;
  53. size_t totalLen =
  54. prefixLen + middleLen + suffixLen + 1; // include space for null on end.
  55. if (takesArg) {
  56. totalLen += 1;
  57. }
  58. char buffer[totalLen];
  59. if (prefix != NULL) {
  60. memcpy(buffer, prefix, prefixLen);
  61. memcpy(buffer + prefixLen, middle, middleLen);
  62. buffer[prefixLen] = (char)toupper(buffer[prefixLen]);
  63. } else {
  64. memcpy(buffer, middle, middleLen);
  65. }
  66. if (suffix != NULL) {
  67. memcpy(buffer + prefixLen + middleLen, suffix, suffixLen);
  68. }
  69. if (takesArg) {
  70. buffer[totalLen - 2] = ':';
  71. }
  72. // Always null terminate it.
  73. buffer[totalLen - 1] = 0;
  74. SEL result = sel_getUid(buffer);
  75. return result;
  76. }
  77. static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
  78. NSArray *allMessageFields)
  79. __attribute__((ns_returns_retained));
  80. static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
  81. NSArray *allMessageFields) {
  82. NSMutableArray *result = [[NSMutableArray alloc] init];
  83. for (GPBFieldDescriptor *fieldDesc in allMessageFields) {
  84. if (fieldDesc->description_->hasIndex == hasIndex) {
  85. [result addObject:fieldDesc];
  86. }
  87. }
  88. return result;
  89. }
  90. @implementation GPBDescriptor {
  91. Class messageClass_;
  92. GPBFileDescriptor *file_;
  93. BOOL wireFormat_;
  94. }
  95. @synthesize messageClass = messageClass_;
  96. @synthesize fields = fields_;
  97. @synthesize oneofs = oneofs_;
  98. @synthesize extensionRanges = extensionRanges_;
  99. @synthesize extensionRangesCount = extensionRangesCount_;
  100. @synthesize file = file_;
  101. @synthesize wireFormat = wireFormat_;
  102. + (instancetype)
  103. allocDescriptorForClass:(Class)messageClass
  104. rootClass:(Class)rootClass
  105. file:(GPBFileDescriptor *)file
  106. fields:(void *)fieldDescriptions
  107. fieldCount:(uint32_t)fieldCount
  108. storageSize:(uint32_t)storageSize
  109. flags:(GPBDescriptorInitializationFlags)flags {
  110. // The rootClass is no longer used, but it is passed in to ensure it
  111. // was started up during initialization also.
  112. (void)rootClass;
  113. NSMutableArray *fields = nil;
  114. GPBFileSyntax syntax = file.syntax;
  115. BOOL fieldsIncludeDefault =
  116. (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0;
  117. void *desc;
  118. for (uint32_t i = 0; i < fieldCount; ++i) {
  119. if (fields == nil) {
  120. fields = [[NSMutableArray alloc] initWithCapacity:fieldCount];
  121. }
  122. // Need correctly typed pointer for array indexing below to work.
  123. if (fieldsIncludeDefault) {
  124. GPBMessageFieldDescriptionWithDefault *fieldDescWithDefault = fieldDescriptions;
  125. desc = &(fieldDescWithDefault[i]);
  126. } else {
  127. GPBMessageFieldDescription *fieldDesc = fieldDescriptions;
  128. desc = &(fieldDesc[i]);
  129. }
  130. GPBFieldDescriptor *fieldDescriptor =
  131. [[GPBFieldDescriptor alloc] initWithFieldDescription:desc
  132. includesDefault:fieldsIncludeDefault
  133. syntax:syntax];
  134. [fields addObject:fieldDescriptor];
  135. [fieldDescriptor release];
  136. }
  137. BOOL wireFormat = (flags & GPBDescriptorInitializationFlag_WireFormat) != 0;
  138. GPBDescriptor *descriptor = [[self alloc] initWithClass:messageClass
  139. file:file
  140. fields:fields
  141. storageSize:storageSize
  142. wireFormat:wireFormat];
  143. [fields release];
  144. return descriptor;
  145. }
  146. - (instancetype)initWithClass:(Class)messageClass
  147. file:(GPBFileDescriptor *)file
  148. fields:(NSArray *)fields
  149. storageSize:(uint32_t)storageSize
  150. wireFormat:(BOOL)wireFormat {
  151. if ((self = [super init])) {
  152. messageClass_ = messageClass;
  153. file_ = file;
  154. fields_ = [fields retain];
  155. storageSize_ = storageSize;
  156. wireFormat_ = wireFormat;
  157. }
  158. return self;
  159. }
  160. - (void)dealloc {
  161. [fields_ release];
  162. [oneofs_ release];
  163. [super dealloc];
  164. }
  165. - (void)setupOneofs:(const char **)oneofNames
  166. count:(uint32_t)count
  167. firstHasIndex:(int32_t)firstHasIndex {
  168. NSCAssert(firstHasIndex < 0, @"Should always be <0");
  169. NSMutableArray *oneofs = [[NSMutableArray alloc] initWithCapacity:count];
  170. for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) {
  171. const char *name = oneofNames[i];
  172. NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_);
  173. NSCAssert(fieldsForOneof.count > 0,
  174. @"No fields for this oneof? (%s:%d)", name, hasIndex);
  175. GPBOneofDescriptor *oneofDescriptor =
  176. [[GPBOneofDescriptor alloc] initWithName:name fields:fieldsForOneof];
  177. [oneofs addObject:oneofDescriptor];
  178. [oneofDescriptor release];
  179. [fieldsForOneof release];
  180. }
  181. oneofs_ = oneofs;
  182. }
  183. - (void)setupExtraTextInfo:(const char *)extraTextFormatInfo {
  184. // Extra info is a compile time option, so skip the work if not needed.
  185. if (extraTextFormatInfo) {
  186. NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo];
  187. for (GPBFieldDescriptor *fieldDescriptor in fields_) {
  188. if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) {
  189. objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey,
  190. extraInfoValue,
  191. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  192. }
  193. }
  194. }
  195. }
  196. - (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count {
  197. extensionRanges_ = ranges;
  198. extensionRangesCount_ = count;
  199. }
  200. - (void)setupContainingMessageClassName:(const char *)msgClassName {
  201. // Note: Only fetch the class here, can't send messages to it because
  202. // that could cause cycles back to this class within +initialize if
  203. // two messages have each other in fields (i.e. - they build a graph).
  204. NSAssert(objc_getClass(msgClassName), @"Class %s not defined", msgClassName);
  205. NSValue *parentNameValue = [NSValue valueWithPointer:msgClassName];
  206. objc_setAssociatedObject(self, &kParentClassNameValueKey,
  207. parentNameValue,
  208. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  209. }
  210. - (void)setupMessageClassNameSuffix:(NSString *)suffix {
  211. if (suffix.length) {
  212. objc_setAssociatedObject(self, &kClassNameSuffixKey,
  213. suffix,
  214. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  215. }
  216. }
  217. - (NSString *)name {
  218. return NSStringFromClass(messageClass_);
  219. }
  220. - (GPBDescriptor *)containingType {
  221. NSValue *parentNameValue =
  222. objc_getAssociatedObject(self, &kParentClassNameValueKey);
  223. if (!parentNameValue) {
  224. return nil;
  225. }
  226. const char *parentName = [parentNameValue pointerValue];
  227. Class parentClass = objc_getClass(parentName);
  228. NSAssert(parentClass, @"Class %s not defined", parentName);
  229. return [parentClass descriptor];
  230. }
  231. - (NSString *)fullName {
  232. NSString *className = NSStringFromClass(self.messageClass);
  233. GPBFileDescriptor *file = self.file;
  234. NSString *objcPrefix = file.objcPrefix;
  235. if (objcPrefix && ![className hasPrefix:objcPrefix]) {
  236. NSAssert(0,
  237. @"Class didn't have correct prefix? (%@ - %@)",
  238. className, objcPrefix);
  239. return nil;
  240. }
  241. GPBDescriptor *parent = self.containingType;
  242. NSString *name = nil;
  243. if (parent) {
  244. NSString *parentClassName = NSStringFromClass(parent.messageClass);
  245. // The generator will add _Class to avoid reserved words, drop it.
  246. NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey);
  247. if (suffix) {
  248. if (![parentClassName hasSuffix:suffix]) {
  249. NSAssert(0,
  250. @"ParentMessage class didn't have correct suffix? (%@ - %@)",
  251. className, suffix);
  252. return nil;
  253. }
  254. parentClassName =
  255. [parentClassName substringToIndex:(parentClassName.length - suffix.length)];
  256. }
  257. NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"];
  258. if (![className hasPrefix:parentPrefix]) {
  259. NSAssert(0,
  260. @"Class didn't have the correct parent name prefix? (%@ - %@)",
  261. parentPrefix, className);
  262. return nil;
  263. }
  264. name = [className substringFromIndex:parentPrefix.length];
  265. } else {
  266. name = [className substringFromIndex:objcPrefix.length];
  267. }
  268. // The generator will add _Class to avoid reserved words, drop it.
  269. NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey);
  270. if (suffix) {
  271. if (![name hasSuffix:suffix]) {
  272. NSAssert(0,
  273. @"Message class didn't have correct suffix? (%@ - %@)",
  274. name, suffix);
  275. return nil;
  276. }
  277. name = [name substringToIndex:(name.length - suffix.length)];
  278. }
  279. NSString *prefix = (parent != nil ? parent.fullName : file.package);
  280. NSString *result;
  281. if (prefix.length > 0) {
  282. result = [NSString stringWithFormat:@"%@.%@", prefix, name];
  283. } else {
  284. result = name;
  285. }
  286. return result;
  287. }
  288. - (id)copyWithZone:(NSZone *)zone {
  289. #pragma unused(zone)
  290. return [self retain];
  291. }
  292. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  293. for (GPBFieldDescriptor *descriptor in fields_) {
  294. if (GPBFieldNumber(descriptor) == fieldNumber) {
  295. return descriptor;
  296. }
  297. }
  298. return nil;
  299. }
  300. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  301. for (GPBFieldDescriptor *descriptor in fields_) {
  302. if ([descriptor.name isEqual:name]) {
  303. return descriptor;
  304. }
  305. }
  306. return nil;
  307. }
  308. - (GPBOneofDescriptor *)oneofWithName:(NSString *)name {
  309. for (GPBOneofDescriptor *descriptor in oneofs_) {
  310. if ([descriptor.name isEqual:name]) {
  311. return descriptor;
  312. }
  313. }
  314. return nil;
  315. }
  316. @end
  317. @implementation GPBFileDescriptor {
  318. NSString *package_;
  319. NSString *objcPrefix_;
  320. GPBFileSyntax syntax_;
  321. }
  322. @synthesize package = package_;
  323. @synthesize objcPrefix = objcPrefix_;
  324. @synthesize syntax = syntax_;
  325. - (instancetype)initWithPackage:(NSString *)package
  326. objcPrefix:(NSString *)objcPrefix
  327. syntax:(GPBFileSyntax)syntax {
  328. self = [super init];
  329. if (self) {
  330. package_ = [package copy];
  331. objcPrefix_ = [objcPrefix copy];
  332. syntax_ = syntax;
  333. }
  334. return self;
  335. }
  336. - (instancetype)initWithPackage:(NSString *)package
  337. syntax:(GPBFileSyntax)syntax {
  338. self = [super init];
  339. if (self) {
  340. package_ = [package copy];
  341. syntax_ = syntax;
  342. }
  343. return self;
  344. }
  345. - (void)dealloc {
  346. [package_ release];
  347. [objcPrefix_ release];
  348. [super dealloc];
  349. }
  350. @end
  351. @implementation GPBOneofDescriptor
  352. @synthesize fields = fields_;
  353. - (instancetype)initWithName:(const char *)name fields:(NSArray *)fields {
  354. self = [super init];
  355. if (self) {
  356. name_ = name;
  357. fields_ = [fields retain];
  358. for (GPBFieldDescriptor *fieldDesc in fields) {
  359. fieldDesc->containingOneof_ = self;
  360. }
  361. caseSel_ = SelFromStrings(NULL, name, "OneOfCase", NO);
  362. }
  363. return self;
  364. }
  365. - (void)dealloc {
  366. [fields_ release];
  367. [super dealloc];
  368. }
  369. - (NSString *)name {
  370. return (NSString * _Nonnull)@(name_);
  371. }
  372. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  373. for (GPBFieldDescriptor *descriptor in fields_) {
  374. if (GPBFieldNumber(descriptor) == fieldNumber) {
  375. return descriptor;
  376. }
  377. }
  378. return nil;
  379. }
  380. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  381. for (GPBFieldDescriptor *descriptor in fields_) {
  382. if ([descriptor.name isEqual:name]) {
  383. return descriptor;
  384. }
  385. }
  386. return nil;
  387. }
  388. @end
  389. uint32_t GPBFieldTag(GPBFieldDescriptor *self) {
  390. GPBMessageFieldDescription *description = self->description_;
  391. GPBWireFormat format;
  392. if ((description->flags & GPBFieldMapKeyMask) != 0) {
  393. // Maps are repeated messages on the wire.
  394. format = GPBWireFormatForType(GPBDataTypeMessage, NO);
  395. } else {
  396. format = GPBWireFormatForType(description->dataType,
  397. ((description->flags & GPBFieldPacked) != 0));
  398. }
  399. return GPBWireFormatMakeTag(description->number, format);
  400. }
  401. uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
  402. GPBMessageFieldDescription *description = self->description_;
  403. NSCAssert((description->flags & GPBFieldRepeated) != 0,
  404. @"Only valid on repeated fields");
  405. GPBWireFormat format =
  406. GPBWireFormatForType(description->dataType,
  407. ((description->flags & GPBFieldPacked) == 0));
  408. return GPBWireFormatMakeTag(description->number, format);
  409. }
  410. @implementation GPBFieldDescriptor {
  411. GPBGenericValue defaultValue_;
  412. // Message ivars
  413. Class msgClass_;
  414. // Enum ivars.
  415. // If protos are generated with GenerateEnumDescriptors on then it will
  416. // be a enumDescriptor, otherwise it will be a enumVerifier.
  417. union {
  418. GPBEnumDescriptor *enumDescriptor_;
  419. GPBEnumValidationFunc enumVerifier_;
  420. } enumHandling_;
  421. }
  422. @synthesize msgClass = msgClass_;
  423. @synthesize containingOneof = containingOneof_;
  424. - (instancetype)init {
  425. // Throw an exception if people attempt to not use the designated initializer.
  426. self = [super init];
  427. if (self != nil) {
  428. [self doesNotRecognizeSelector:_cmd];
  429. self = nil;
  430. }
  431. return self;
  432. }
  433. - (instancetype)initWithFieldDescription:(void *)description
  434. includesDefault:(BOOL)includesDefault
  435. syntax:(GPBFileSyntax)syntax {
  436. if ((self = [super init])) {
  437. GPBMessageFieldDescription *coreDesc;
  438. if (includesDefault) {
  439. coreDesc = &(((GPBMessageFieldDescriptionWithDefault *)description)->core);
  440. } else {
  441. coreDesc = description;
  442. }
  443. description_ = coreDesc;
  444. getSel_ = sel_getUid(coreDesc->name);
  445. setSel_ = SelFromStrings("set", coreDesc->name, NULL, YES);
  446. GPBDataType dataType = coreDesc->dataType;
  447. BOOL isMessage = GPBDataTypeIsMessage(dataType);
  448. BOOL isMapOrArray = GPBFieldIsMapOrArray(self);
  449. if (isMapOrArray) {
  450. // map<>/repeated fields get a *Count property (inplace of a has*) to
  451. // support checking if there are any entries without triggering
  452. // autocreation.
  453. hasOrCountSel_ = SelFromStrings(NULL, coreDesc->name, "_Count", NO);
  454. } else {
  455. // If there is a positive hasIndex, then:
  456. // - All fields types for proto2 messages get has* selectors.
  457. // - Only message fields for proto3 messages get has* selectors.
  458. // Note: the positive check is to handle oneOfs, we can't check
  459. // containingOneof_ because it isn't set until after initialization.
  460. if ((coreDesc->hasIndex >= 0) &&
  461. (coreDesc->hasIndex != GPBNoHasBit) &&
  462. ((syntax != GPBFileSyntaxProto3) || isMessage)) {
  463. hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO);
  464. setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES);
  465. }
  466. }
  467. // Extra type specific data.
  468. if (isMessage) {
  469. const char *className = coreDesc->dataTypeSpecific.className;
  470. // Note: Only fetch the class here, can't send messages to it because
  471. // that could cause cycles back to this class within +initialize if
  472. // two messages have each other in fields (i.e. - they build a graph).
  473. msgClass_ = objc_getClass(className);
  474. NSAssert(msgClass_, @"Class %s not defined", className);
  475. } else if (dataType == GPBDataTypeEnum) {
  476. if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) {
  477. enumHandling_.enumDescriptor_ =
  478. coreDesc->dataTypeSpecific.enumDescFunc();
  479. } else {
  480. enumHandling_.enumVerifier_ =
  481. coreDesc->dataTypeSpecific.enumVerifier;
  482. }
  483. }
  484. // Non map<>/repeated fields can have defaults in proto2 syntax.
  485. if (!isMapOrArray && includesDefault) {
  486. defaultValue_ = ((GPBMessageFieldDescriptionWithDefault *)description)->defaultValue;
  487. if (dataType == GPBDataTypeBytes) {
  488. // Data stored as a length prefixed (network byte order) c-string in
  489. // descriptor structure.
  490. const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData;
  491. if (bytes) {
  492. uint32_t length;
  493. memcpy(&length, bytes, sizeof(length));
  494. length = ntohl(length);
  495. bytes += sizeof(length);
  496. defaultValue_.valueData =
  497. [[NSData alloc] initWithBytes:bytes length:length];
  498. }
  499. }
  500. }
  501. }
  502. return self;
  503. }
  504. - (void)dealloc {
  505. if (description_->dataType == GPBDataTypeBytes &&
  506. !(description_->flags & GPBFieldRepeated)) {
  507. [defaultValue_.valueData release];
  508. }
  509. [super dealloc];
  510. }
  511. - (GPBDataType)dataType {
  512. return description_->dataType;
  513. }
  514. - (BOOL)hasDefaultValue {
  515. return (description_->flags & GPBFieldHasDefaultValue) != 0;
  516. }
  517. - (uint32_t)number {
  518. return description_->number;
  519. }
  520. - (NSString *)name {
  521. return (NSString * _Nonnull)@(description_->name);
  522. }
  523. - (BOOL)isRequired {
  524. return (description_->flags & GPBFieldRequired) != 0;
  525. }
  526. - (BOOL)isOptional {
  527. return (description_->flags & GPBFieldOptional) != 0;
  528. }
  529. - (GPBFieldType)fieldType {
  530. GPBFieldFlags flags = description_->flags;
  531. if ((flags & GPBFieldRepeated) != 0) {
  532. return GPBFieldTypeRepeated;
  533. } else if ((flags & GPBFieldMapKeyMask) != 0) {
  534. return GPBFieldTypeMap;
  535. } else {
  536. return GPBFieldTypeSingle;
  537. }
  538. }
  539. - (GPBDataType)mapKeyDataType {
  540. switch (description_->flags & GPBFieldMapKeyMask) {
  541. case GPBFieldMapKeyInt32:
  542. return GPBDataTypeInt32;
  543. case GPBFieldMapKeyInt64:
  544. return GPBDataTypeInt64;
  545. case GPBFieldMapKeyUInt32:
  546. return GPBDataTypeUInt32;
  547. case GPBFieldMapKeyUInt64:
  548. return GPBDataTypeUInt64;
  549. case GPBFieldMapKeySInt32:
  550. return GPBDataTypeSInt32;
  551. case GPBFieldMapKeySInt64:
  552. return GPBDataTypeSInt64;
  553. case GPBFieldMapKeyFixed32:
  554. return GPBDataTypeFixed32;
  555. case GPBFieldMapKeyFixed64:
  556. return GPBDataTypeFixed64;
  557. case GPBFieldMapKeySFixed32:
  558. return GPBDataTypeSFixed32;
  559. case GPBFieldMapKeySFixed64:
  560. return GPBDataTypeSFixed64;
  561. case GPBFieldMapKeyBool:
  562. return GPBDataTypeBool;
  563. case GPBFieldMapKeyString:
  564. return GPBDataTypeString;
  565. default:
  566. NSAssert(0, @"Not a map type");
  567. return GPBDataTypeInt32; // For lack of anything better.
  568. }
  569. }
  570. - (BOOL)isPackable {
  571. return (description_->flags & GPBFieldPacked) != 0;
  572. }
  573. - (BOOL)isValidEnumValue:(int32_t)value {
  574. NSAssert(description_->dataType == GPBDataTypeEnum,
  575. @"Field Must be of type GPBDataTypeEnum");
  576. if (description_->flags & GPBFieldHasEnumDescriptor) {
  577. return enumHandling_.enumDescriptor_.enumVerifier(value);
  578. } else {
  579. return enumHandling_.enumVerifier_(value);
  580. }
  581. }
  582. - (GPBEnumDescriptor *)enumDescriptor {
  583. if (description_->flags & GPBFieldHasEnumDescriptor) {
  584. return enumHandling_.enumDescriptor_;
  585. } else {
  586. return nil;
  587. }
  588. }
  589. - (GPBGenericValue)defaultValue {
  590. // Depends on the fact that defaultValue_ is initialized either to "0/nil" or
  591. // to an actual defaultValue in our initializer.
  592. GPBGenericValue value = defaultValue_;
  593. if (!(description_->flags & GPBFieldRepeated)) {
  594. // We special handle data and strings. If they are nil, we replace them
  595. // with empty string/empty data.
  596. GPBDataType type = description_->dataType;
  597. if (type == GPBDataTypeBytes && value.valueData == nil) {
  598. value.valueData = GPBEmptyNSData();
  599. } else if (type == GPBDataTypeString && value.valueString == nil) {
  600. value.valueString = @"";
  601. }
  602. }
  603. return value;
  604. }
  605. - (NSString *)textFormatName {
  606. if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
  607. NSValue *extraInfoValue =
  608. objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
  609. // Support can be left out at generation time.
  610. if (!extraInfoValue) {
  611. return nil;
  612. }
  613. const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
  614. return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self),
  615. self.name);
  616. }
  617. // The logic here has to match SetCommonFieldVariables() from
  618. // objectivec_field.cc in the proto compiler.
  619. NSString *name = self.name;
  620. NSUInteger len = [name length];
  621. // Remove the "_p" added to reserved names.
  622. if ([name hasSuffix:@"_p"]) {
  623. name = [name substringToIndex:(len - 2)];
  624. len = [name length];
  625. }
  626. // Remove "Array" from the end for repeated fields.
  627. if (((description_->flags & GPBFieldRepeated) != 0) &&
  628. [name hasSuffix:@"Array"]) {
  629. name = [name substringToIndex:(len - 5)];
  630. len = [name length];
  631. }
  632. // Groups vs. other fields.
  633. if (description_->dataType == GPBDataTypeGroup) {
  634. // Just capitalize the first letter.
  635. unichar firstChar = [name characterAtIndex:0];
  636. if (firstChar >= 'a' && firstChar <= 'z') {
  637. NSString *firstCharString =
  638. [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
  639. NSString *result =
  640. [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
  641. withString:firstCharString];
  642. return result;
  643. }
  644. return name;
  645. } else {
  646. // Undo the CamelCase.
  647. NSMutableString *result = [NSMutableString stringWithCapacity:len];
  648. for (uint32_t i = 0; i < len; i++) {
  649. unichar c = [name characterAtIndex:i];
  650. if (c >= 'A' && c <= 'Z') {
  651. if (i > 0) {
  652. [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')];
  653. } else {
  654. [result appendFormat:@"%C", c];
  655. }
  656. } else {
  657. [result appendFormat:@"%C", c];
  658. }
  659. }
  660. return result;
  661. }
  662. }
  663. @end
  664. @implementation GPBEnumDescriptor {
  665. NSString *name_;
  666. // valueNames_ is a single c string with all of the value names appended
  667. // together, each null terminated. -calcValueNameOffsets fills in
  668. // nameOffsets_ with the offsets to allow quicker access to the individual
  669. // names.
  670. const char *valueNames_;
  671. const int32_t *values_;
  672. GPBEnumValidationFunc enumVerifier_;
  673. const uint8_t *extraTextFormatInfo_;
  674. uint32_t *nameOffsets_;
  675. uint32_t valueCount_;
  676. }
  677. @synthesize name = name_;
  678. @synthesize enumVerifier = enumVerifier_;
  679. + (instancetype)
  680. allocDescriptorForName:(NSString *)name
  681. valueNames:(const char *)valueNames
  682. values:(const int32_t *)values
  683. count:(uint32_t)valueCount
  684. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  685. GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name
  686. valueNames:valueNames
  687. values:values
  688. count:valueCount
  689. enumVerifier:enumVerifier];
  690. return descriptor;
  691. }
  692. + (instancetype)
  693. allocDescriptorForName:(NSString *)name
  694. valueNames:(const char *)valueNames
  695. values:(const int32_t *)values
  696. count:(uint32_t)valueCount
  697. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  698. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  699. // Call the common case.
  700. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name
  701. valueNames:valueNames
  702. values:values
  703. count:valueCount
  704. enumVerifier:enumVerifier];
  705. // Set the extra info.
  706. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo;
  707. return descriptor;
  708. }
  709. - (instancetype)initWithName:(NSString *)name
  710. valueNames:(const char *)valueNames
  711. values:(const int32_t *)values
  712. count:(uint32_t)valueCount
  713. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  714. if ((self = [super init])) {
  715. name_ = [name copy];
  716. valueNames_ = valueNames;
  717. values_ = values;
  718. valueCount_ = valueCount;
  719. enumVerifier_ = enumVerifier;
  720. }
  721. return self;
  722. }
  723. - (void)dealloc {
  724. [name_ release];
  725. if (nameOffsets_) free(nameOffsets_);
  726. [super dealloc];
  727. }
  728. - (void)calcValueNameOffsets {
  729. @synchronized(self) {
  730. if (nameOffsets_ != NULL) {
  731. return;
  732. }
  733. uint32_t *offsets = malloc(valueCount_ * sizeof(uint32_t));
  734. if (!offsets) return;
  735. const char *scan = valueNames_;
  736. for (uint32_t i = 0; i < valueCount_; ++i) {
  737. offsets[i] = (uint32_t)(scan - valueNames_);
  738. while (*scan != '\0') ++scan;
  739. ++scan; // Step over the null.
  740. }
  741. nameOffsets_ = offsets;
  742. }
  743. }
  744. - (NSString *)enumNameForValue:(int32_t)number {
  745. for (uint32_t i = 0; i < valueCount_; ++i) {
  746. if (values_[i] == number) {
  747. return [self getEnumNameForIndex:i];
  748. }
  749. }
  750. return nil;
  751. }
  752. - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name {
  753. // Must have the prefix.
  754. NSUInteger prefixLen = name_.length + 1;
  755. if ((name.length <= prefixLen) || ![name hasPrefix:name_] ||
  756. ([name characterAtIndex:prefixLen - 1] != '_')) {
  757. return NO;
  758. }
  759. // Skip over the prefix.
  760. const char *nameAsCStr = [name UTF8String];
  761. nameAsCStr += prefixLen;
  762. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  763. if (nameOffsets_ == NULL) return NO;
  764. // Find it.
  765. for (uint32_t i = 0; i < valueCount_; ++i) {
  766. const char *valueName = valueNames_ + nameOffsets_[i];
  767. if (strcmp(nameAsCStr, valueName) == 0) {
  768. if (outValue) {
  769. *outValue = values_[i];
  770. }
  771. return YES;
  772. }
  773. }
  774. return NO;
  775. }
  776. - (BOOL)getValue:(int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName {
  777. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  778. if (nameOffsets_ == NULL) return NO;
  779. for (uint32_t i = 0; i < valueCount_; ++i) {
  780. NSString *valueTextFormatName = [self getEnumTextFormatNameForIndex:i];
  781. if ([valueTextFormatName isEqual:textFormatName]) {
  782. if (outValue) {
  783. *outValue = values_[i];
  784. }
  785. return YES;
  786. }
  787. }
  788. return NO;
  789. }
  790. - (NSString *)textFormatNameForValue:(int32_t)number {
  791. // Find the EnumValue descriptor and its index.
  792. BOOL foundIt = NO;
  793. uint32_t valueDescriptorIndex;
  794. for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_;
  795. ++valueDescriptorIndex) {
  796. if (values_[valueDescriptorIndex] == number) {
  797. foundIt = YES;
  798. break;
  799. }
  800. }
  801. if (!foundIt) {
  802. return nil;
  803. }
  804. return [self getEnumTextFormatNameForIndex:valueDescriptorIndex];
  805. }
  806. - (uint32_t)enumNameCount {
  807. return valueCount_;
  808. }
  809. - (NSString *)getEnumNameForIndex:(uint32_t)index {
  810. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  811. if (nameOffsets_ == NULL) return nil;
  812. if (index >= valueCount_) {
  813. return nil;
  814. }
  815. const char *valueName = valueNames_ + nameOffsets_[index];
  816. NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName];
  817. return fullName;
  818. }
  819. - (NSString *)getEnumTextFormatNameForIndex:(uint32_t)index {
  820. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  821. if (nameOffsets_ == NULL) return nil;
  822. if (index >= valueCount_) {
  823. return nil;
  824. }
  825. NSString *result = nil;
  826. // Naming adds an underscore between enum name and value name, skip that also.
  827. const char *valueName = valueNames_ + nameOffsets_[index];
  828. NSString *shortName = @(valueName);
  829. // See if it is in the map of special format handling.
  830. if (extraTextFormatInfo_) {
  831. result = GPBDecodeTextFormatName(extraTextFormatInfo_,
  832. (int32_t)index, shortName);
  833. }
  834. // Logic here needs to match what objectivec_enum.cc does in the proto
  835. // compiler.
  836. if (result == nil) {
  837. NSUInteger len = [shortName length];
  838. NSMutableString *worker = [NSMutableString stringWithCapacity:len];
  839. for (NSUInteger i = 0; i < len; i++) {
  840. unichar c = [shortName characterAtIndex:i];
  841. if (i > 0 && c >= 'A' && c <= 'Z') {
  842. [worker appendString:@"_"];
  843. }
  844. [worker appendFormat:@"%c", toupper((char)c)];
  845. }
  846. result = worker;
  847. }
  848. return result;
  849. }
  850. @end
  851. @implementation GPBExtensionDescriptor {
  852. GPBGenericValue defaultValue_;
  853. }
  854. @synthesize containingMessageClass = containingMessageClass_;
  855. - (instancetype)initWithExtensionDescription:
  856. (GPBExtensionDescription *)description {
  857. if ((self = [super init])) {
  858. description_ = description;
  859. #if defined(DEBUG) && DEBUG
  860. const char *className = description->messageOrGroupClassName;
  861. if (className) {
  862. NSAssert(objc_lookUpClass(className) != Nil,
  863. @"Class %s not defined", className);
  864. }
  865. #endif
  866. if (description->extendedClass) {
  867. Class containingClass = objc_lookUpClass(description->extendedClass);
  868. NSAssert(containingClass, @"Class %s not defined",
  869. description->extendedClass);
  870. containingMessageClass_ = containingClass;
  871. }
  872. GPBDataType type = description_->dataType;
  873. if (type == GPBDataTypeBytes) {
  874. // Data stored as a length prefixed c-string in descriptor records.
  875. const uint8_t *bytes =
  876. (const uint8_t *)description->defaultValue.valueData;
  877. if (bytes) {
  878. uint32_t length;
  879. memcpy(&length, bytes, sizeof(length));
  880. // The length is stored in network byte order.
  881. length = ntohl(length);
  882. bytes += sizeof(length);
  883. defaultValue_.valueData =
  884. [[NSData alloc] initWithBytes:bytes length:length];
  885. }
  886. } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) {
  887. // The default is looked up in -defaultValue instead since extensions
  888. // aren't common, we avoid the hit startup hit and it avoid initialization
  889. // order issues.
  890. } else {
  891. defaultValue_ = description->defaultValue;
  892. }
  893. }
  894. return self;
  895. }
  896. - (void)dealloc {
  897. if ((description_->dataType == GPBDataTypeBytes) &&
  898. !GPBExtensionIsRepeated(description_)) {
  899. [defaultValue_.valueData release];
  900. }
  901. [super dealloc];
  902. }
  903. - (instancetype)copyWithZone:(NSZone *)zone {
  904. #pragma unused(zone)
  905. // Immutable.
  906. return [self retain];
  907. }
  908. - (NSString *)singletonName {
  909. return (NSString * _Nonnull)@(description_->singletonName);
  910. }
  911. - (const char *)singletonNameC {
  912. return description_->singletonName;
  913. }
  914. - (uint32_t)fieldNumber {
  915. return description_->fieldNumber;
  916. }
  917. - (GPBDataType)dataType {
  918. return description_->dataType;
  919. }
  920. - (GPBWireFormat)wireType {
  921. return GPBWireFormatForType(description_->dataType,
  922. GPBExtensionIsPacked(description_));
  923. }
  924. - (GPBWireFormat)alternateWireType {
  925. NSAssert(GPBExtensionIsRepeated(description_),
  926. @"Only valid on repeated extensions");
  927. return GPBWireFormatForType(description_->dataType,
  928. !GPBExtensionIsPacked(description_));
  929. }
  930. - (BOOL)isRepeated {
  931. return GPBExtensionIsRepeated(description_);
  932. }
  933. - (BOOL)isPackable {
  934. return GPBExtensionIsPacked(description_);
  935. }
  936. - (Class)msgClass {
  937. return objc_getClass(description_->messageOrGroupClassName);
  938. }
  939. - (GPBEnumDescriptor *)enumDescriptor {
  940. if (description_->dataType == GPBDataTypeEnum) {
  941. GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc();
  942. return enumDescriptor;
  943. }
  944. return nil;
  945. }
  946. - (id)defaultValue {
  947. if (GPBExtensionIsRepeated(description_)) {
  948. return nil;
  949. }
  950. switch (description_->dataType) {
  951. case GPBDataTypeBool:
  952. return @(defaultValue_.valueBool);
  953. case GPBDataTypeFloat:
  954. return @(defaultValue_.valueFloat);
  955. case GPBDataTypeDouble:
  956. return @(defaultValue_.valueDouble);
  957. case GPBDataTypeInt32:
  958. case GPBDataTypeSInt32:
  959. case GPBDataTypeEnum:
  960. case GPBDataTypeSFixed32:
  961. return @(defaultValue_.valueInt32);
  962. case GPBDataTypeInt64:
  963. case GPBDataTypeSInt64:
  964. case GPBDataTypeSFixed64:
  965. return @(defaultValue_.valueInt64);
  966. case GPBDataTypeUInt32:
  967. case GPBDataTypeFixed32:
  968. return @(defaultValue_.valueUInt32);
  969. case GPBDataTypeUInt64:
  970. case GPBDataTypeFixed64:
  971. return @(defaultValue_.valueUInt64);
  972. case GPBDataTypeBytes:
  973. // Like message fields, the default is zero length data.
  974. return (defaultValue_.valueData ? defaultValue_.valueData
  975. : GPBEmptyNSData());
  976. case GPBDataTypeString:
  977. // Like message fields, the default is zero length string.
  978. return (defaultValue_.valueString ? defaultValue_.valueString : @"");
  979. case GPBDataTypeGroup:
  980. case GPBDataTypeMessage:
  981. return nil;
  982. }
  983. }
  984. - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other {
  985. int32_t selfNumber = description_->fieldNumber;
  986. int32_t otherNumber = other->description_->fieldNumber;
  987. if (selfNumber < otherNumber) {
  988. return NSOrderedAscending;
  989. } else if (selfNumber == otherNumber) {
  990. return NSOrderedSame;
  991. } else {
  992. return NSOrderedDescending;
  993. }
  994. }
  995. @end
  996. #pragma clang diagnostic pop