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.

1100 lines
34 KiB

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 @(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 = *((uint32_t *)bytes);
  493. length = ntohl(length);
  494. bytes += sizeof(length);
  495. defaultValue_.valueData =
  496. [[NSData alloc] initWithBytes:bytes length:length];
  497. }
  498. }
  499. }
  500. }
  501. return self;
  502. }
  503. - (void)dealloc {
  504. if (description_->dataType == GPBDataTypeBytes &&
  505. !(description_->flags & GPBFieldRepeated)) {
  506. [defaultValue_.valueData release];
  507. }
  508. [super dealloc];
  509. }
  510. - (GPBDataType)dataType {
  511. return description_->dataType;
  512. }
  513. - (BOOL)hasDefaultValue {
  514. return (description_->flags & GPBFieldHasDefaultValue) != 0;
  515. }
  516. - (uint32_t)number {
  517. return description_->number;
  518. }
  519. - (NSString *)name {
  520. return @(description_->name);
  521. }
  522. - (BOOL)isRequired {
  523. return (description_->flags & GPBFieldRequired) != 0;
  524. }
  525. - (BOOL)isOptional {
  526. return (description_->flags & GPBFieldOptional) != 0;
  527. }
  528. - (GPBFieldType)fieldType {
  529. GPBFieldFlags flags = description_->flags;
  530. if ((flags & GPBFieldRepeated) != 0) {
  531. return GPBFieldTypeRepeated;
  532. } else if ((flags & GPBFieldMapKeyMask) != 0) {
  533. return GPBFieldTypeMap;
  534. } else {
  535. return GPBFieldTypeSingle;
  536. }
  537. }
  538. - (GPBDataType)mapKeyDataType {
  539. switch (description_->flags & GPBFieldMapKeyMask) {
  540. case GPBFieldMapKeyInt32:
  541. return GPBDataTypeInt32;
  542. case GPBFieldMapKeyInt64:
  543. return GPBDataTypeInt64;
  544. case GPBFieldMapKeyUInt32:
  545. return GPBDataTypeUInt32;
  546. case GPBFieldMapKeyUInt64:
  547. return GPBDataTypeUInt64;
  548. case GPBFieldMapKeySInt32:
  549. return GPBDataTypeSInt32;
  550. case GPBFieldMapKeySInt64:
  551. return GPBDataTypeSInt64;
  552. case GPBFieldMapKeyFixed32:
  553. return GPBDataTypeFixed32;
  554. case GPBFieldMapKeyFixed64:
  555. return GPBDataTypeFixed64;
  556. case GPBFieldMapKeySFixed32:
  557. return GPBDataTypeSFixed32;
  558. case GPBFieldMapKeySFixed64:
  559. return GPBDataTypeSFixed64;
  560. case GPBFieldMapKeyBool:
  561. return GPBDataTypeBool;
  562. case GPBFieldMapKeyString:
  563. return GPBDataTypeString;
  564. default:
  565. NSAssert(0, @"Not a map type");
  566. return GPBDataTypeInt32; // For lack of anything better.
  567. }
  568. }
  569. - (BOOL)isPackable {
  570. return (description_->flags & GPBFieldPacked) != 0;
  571. }
  572. - (BOOL)isValidEnumValue:(int32_t)value {
  573. NSAssert(description_->dataType == GPBDataTypeEnum,
  574. @"Field Must be of type GPBDataTypeEnum");
  575. if (description_->flags & GPBFieldHasEnumDescriptor) {
  576. return enumHandling_.enumDescriptor_.enumVerifier(value);
  577. } else {
  578. return enumHandling_.enumVerifier_(value);
  579. }
  580. }
  581. - (GPBEnumDescriptor *)enumDescriptor {
  582. if (description_->flags & GPBFieldHasEnumDescriptor) {
  583. return enumHandling_.enumDescriptor_;
  584. } else {
  585. return nil;
  586. }
  587. }
  588. - (GPBGenericValue)defaultValue {
  589. // Depends on the fact that defaultValue_ is initialized either to "0/nil" or
  590. // to an actual defaultValue in our initializer.
  591. GPBGenericValue value = defaultValue_;
  592. if (!(description_->flags & GPBFieldRepeated)) {
  593. // We special handle data and strings. If they are nil, we replace them
  594. // with empty string/empty data.
  595. GPBDataType type = description_->dataType;
  596. if (type == GPBDataTypeBytes && value.valueData == nil) {
  597. value.valueData = GPBEmptyNSData();
  598. } else if (type == GPBDataTypeString && value.valueString == nil) {
  599. value.valueString = @"";
  600. }
  601. }
  602. return value;
  603. }
  604. - (NSString *)textFormatName {
  605. if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
  606. NSValue *extraInfoValue =
  607. objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
  608. // Support can be left out at generation time.
  609. if (!extraInfoValue) {
  610. return nil;
  611. }
  612. const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
  613. return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self),
  614. self.name);
  615. }
  616. // The logic here has to match SetCommonFieldVariables() from
  617. // objectivec_field.cc in the proto compiler.
  618. NSString *name = self.name;
  619. NSUInteger len = [name length];
  620. // Remove the "_p" added to reserved names.
  621. if ([name hasSuffix:@"_p"]) {
  622. name = [name substringToIndex:(len - 2)];
  623. len = [name length];
  624. }
  625. // Remove "Array" from the end for repeated fields.
  626. if (((description_->flags & GPBFieldRepeated) != 0) &&
  627. [name hasSuffix:@"Array"]) {
  628. name = [name substringToIndex:(len - 5)];
  629. len = [name length];
  630. }
  631. // Groups vs. other fields.
  632. if (description_->dataType == GPBDataTypeGroup) {
  633. // Just capitalize the first letter.
  634. unichar firstChar = [name characterAtIndex:0];
  635. if (firstChar >= 'a' && firstChar <= 'z') {
  636. NSString *firstCharString =
  637. [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
  638. NSString *result =
  639. [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
  640. withString:firstCharString];
  641. return result;
  642. }
  643. return name;
  644. } else {
  645. // Undo the CamelCase.
  646. NSMutableString *result = [NSMutableString stringWithCapacity:len];
  647. for (uint32_t i = 0; i < len; i++) {
  648. unichar c = [name characterAtIndex:i];
  649. if (c >= 'A' && c <= 'Z') {
  650. if (i > 0) {
  651. [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')];
  652. } else {
  653. [result appendFormat:@"%C", c];
  654. }
  655. } else {
  656. [result appendFormat:@"%C", c];
  657. }
  658. }
  659. return result;
  660. }
  661. }
  662. @end
  663. @implementation GPBEnumDescriptor {
  664. NSString *name_;
  665. // valueNames_ is a single c string with all of the value names appended
  666. // together, each null terminated. -calcValueNameOffsets fills in
  667. // nameOffsets_ with the offsets to allow quicker access to the individual
  668. // names.
  669. const char *valueNames_;
  670. const int32_t *values_;
  671. GPBEnumValidationFunc enumVerifier_;
  672. const uint8_t *extraTextFormatInfo_;
  673. uint32_t *nameOffsets_;
  674. uint32_t valueCount_;
  675. }
  676. @synthesize name = name_;
  677. @synthesize enumVerifier = enumVerifier_;
  678. + (instancetype)
  679. allocDescriptorForName:(NSString *)name
  680. valueNames:(const char *)valueNames
  681. values:(const int32_t *)values
  682. count:(uint32_t)valueCount
  683. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  684. GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name
  685. valueNames:valueNames
  686. values:values
  687. count:valueCount
  688. enumVerifier:enumVerifier];
  689. return descriptor;
  690. }
  691. + (instancetype)
  692. allocDescriptorForName:(NSString *)name
  693. valueNames:(const char *)valueNames
  694. values:(const int32_t *)values
  695. count:(uint32_t)valueCount
  696. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  697. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  698. // Call the common case.
  699. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name
  700. valueNames:valueNames
  701. values:values
  702. count:valueCount
  703. enumVerifier:enumVerifier];
  704. // Set the extra info.
  705. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo;
  706. return descriptor;
  707. }
  708. - (instancetype)initWithName:(NSString *)name
  709. valueNames:(const char *)valueNames
  710. values:(const int32_t *)values
  711. count:(uint32_t)valueCount
  712. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  713. if ((self = [super init])) {
  714. name_ = [name copy];
  715. valueNames_ = valueNames;
  716. values_ = values;
  717. valueCount_ = valueCount;
  718. enumVerifier_ = enumVerifier;
  719. }
  720. return self;
  721. }
  722. - (void)dealloc {
  723. [name_ release];
  724. if (nameOffsets_) free(nameOffsets_);
  725. [super dealloc];
  726. }
  727. - (void)calcValueNameOffsets {
  728. @synchronized(self) {
  729. if (nameOffsets_ != NULL) {
  730. return;
  731. }
  732. uint32_t *offsets = malloc(valueCount_ * sizeof(uint32_t));
  733. const char *scan = valueNames_;
  734. for (uint32_t i = 0; i < valueCount_; ++i) {
  735. offsets[i] = (uint32_t)(scan - valueNames_);
  736. while (*scan != '\0') ++scan;
  737. ++scan; // Step over the null.
  738. }
  739. nameOffsets_ = offsets;
  740. }
  741. }
  742. - (NSString *)enumNameForValue:(int32_t)number {
  743. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  744. for (uint32_t i = 0; i < valueCount_; ++i) {
  745. if (values_[i] == number) {
  746. const char *valueName = valueNames_ + nameOffsets_[i];
  747. NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName];
  748. return fullName;
  749. }
  750. }
  751. return nil;
  752. }
  753. - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name {
  754. // Must have the prefix.
  755. NSUInteger prefixLen = name_.length + 1;
  756. if ((name.length <= prefixLen) || ![name hasPrefix:name_] ||
  757. ([name characterAtIndex:prefixLen - 1] != '_')) {
  758. return NO;
  759. }
  760. // Skip over the prefix.
  761. const char *nameAsCStr = [name UTF8String];
  762. nameAsCStr += prefixLen;
  763. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  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. for (uint32_t i = 0; i < valueCount_; ++i) {
  779. int32_t value = values_[i];
  780. NSString *valueTextFormatName = [self textFormatNameForValue:value];
  781. if ([valueTextFormatName isEqual:textFormatName]) {
  782. if (outValue) {
  783. *outValue = value;
  784. }
  785. return YES;
  786. }
  787. }
  788. return NO;
  789. }
  790. - (NSString *)textFormatNameForValue:(int32_t)number {
  791. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  792. // Find the EnumValue descriptor and its index.
  793. BOOL foundIt = NO;
  794. uint32_t valueDescriptorIndex;
  795. for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_;
  796. ++valueDescriptorIndex) {
  797. if (values_[valueDescriptorIndex] == number) {
  798. foundIt = YES;
  799. break;
  800. }
  801. }
  802. if (!foundIt) {
  803. return nil;
  804. }
  805. NSString *result = nil;
  806. // Naming adds an underscore between enum name and value name, skip that also.
  807. const char *valueName = valueNames_ + nameOffsets_[valueDescriptorIndex];
  808. NSString *shortName = @(valueName);
  809. // See if it is in the map of special format handling.
  810. if (extraTextFormatInfo_) {
  811. result = GPBDecodeTextFormatName(extraTextFormatInfo_,
  812. (int32_t)valueDescriptorIndex, shortName);
  813. }
  814. // Logic here needs to match what objectivec_enum.cc does in the proto
  815. // compiler.
  816. if (result == nil) {
  817. NSUInteger len = [shortName length];
  818. NSMutableString *worker = [NSMutableString stringWithCapacity:len];
  819. for (NSUInteger i = 0; i < len; i++) {
  820. unichar c = [shortName characterAtIndex:i];
  821. if (i > 0 && c >= 'A' && c <= 'Z') {
  822. [worker appendString:@"_"];
  823. }
  824. [worker appendFormat:@"%c", toupper((char)c)];
  825. }
  826. result = worker;
  827. }
  828. return result;
  829. }
  830. @end
  831. @implementation GPBExtensionDescriptor {
  832. GPBGenericValue defaultValue_;
  833. }
  834. @synthesize containingMessageClass = containingMessageClass_;
  835. - (instancetype)initWithExtensionDescription:
  836. (GPBExtensionDescription *)description {
  837. if ((self = [super init])) {
  838. description_ = description;
  839. #if defined(DEBUG) && DEBUG
  840. const char *className = description->messageOrGroupClassName;
  841. if (className) {
  842. NSAssert(objc_lookUpClass(className) != Nil,
  843. @"Class %s not defined", className);
  844. }
  845. #endif
  846. if (description->extendedClass) {
  847. Class containingClass = objc_lookUpClass(description->extendedClass);
  848. NSAssert(containingClass, @"Class %s not defined",
  849. description->extendedClass);
  850. containingMessageClass_ = containingClass;
  851. }
  852. GPBDataType type = description_->dataType;
  853. if (type == GPBDataTypeBytes) {
  854. // Data stored as a length prefixed c-string in descriptor records.
  855. const uint8_t *bytes =
  856. (const uint8_t *)description->defaultValue.valueData;
  857. if (bytes) {
  858. uint32_t length = *((uint32_t *)bytes);
  859. // The length is stored in network byte order.
  860. length = ntohl(length);
  861. bytes += sizeof(length);
  862. defaultValue_.valueData =
  863. [[NSData alloc] initWithBytes:bytes length:length];
  864. }
  865. } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) {
  866. // The default is looked up in -defaultValue instead since extensions
  867. // aren't common, we avoid the hit startup hit and it avoid initialization
  868. // order issues.
  869. } else {
  870. defaultValue_ = description->defaultValue;
  871. }
  872. }
  873. return self;
  874. }
  875. - (void)dealloc {
  876. if ((description_->dataType == GPBDataTypeBytes) &&
  877. !GPBExtensionIsRepeated(description_)) {
  878. [defaultValue_.valueData release];
  879. }
  880. [super dealloc];
  881. }
  882. - (instancetype)copyWithZone:(NSZone *)zone {
  883. #pragma unused(zone)
  884. // Immutable.
  885. return [self retain];
  886. }
  887. - (NSString *)singletonName {
  888. return @(description_->singletonName);
  889. }
  890. - (const char *)singletonNameC {
  891. return description_->singletonName;
  892. }
  893. - (uint32_t)fieldNumber {
  894. return description_->fieldNumber;
  895. }
  896. - (GPBDataType)dataType {
  897. return description_->dataType;
  898. }
  899. - (GPBWireFormat)wireType {
  900. return GPBWireFormatForType(description_->dataType,
  901. GPBExtensionIsPacked(description_));
  902. }
  903. - (GPBWireFormat)alternateWireType {
  904. NSAssert(GPBExtensionIsRepeated(description_),
  905. @"Only valid on repeated extensions");
  906. return GPBWireFormatForType(description_->dataType,
  907. !GPBExtensionIsPacked(description_));
  908. }
  909. - (BOOL)isRepeated {
  910. return GPBExtensionIsRepeated(description_);
  911. }
  912. - (BOOL)isPackable {
  913. return GPBExtensionIsPacked(description_);
  914. }
  915. - (Class)msgClass {
  916. return objc_getClass(description_->messageOrGroupClassName);
  917. }
  918. - (GPBEnumDescriptor *)enumDescriptor {
  919. if (description_->dataType == GPBDataTypeEnum) {
  920. GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc();
  921. return enumDescriptor;
  922. }
  923. return nil;
  924. }
  925. - (id)defaultValue {
  926. if (GPBExtensionIsRepeated(description_)) {
  927. return nil;
  928. }
  929. switch (description_->dataType) {
  930. case GPBDataTypeBool:
  931. return @(defaultValue_.valueBool);
  932. case GPBDataTypeFloat:
  933. return @(defaultValue_.valueFloat);
  934. case GPBDataTypeDouble:
  935. return @(defaultValue_.valueDouble);
  936. case GPBDataTypeInt32:
  937. case GPBDataTypeSInt32:
  938. case GPBDataTypeEnum:
  939. case GPBDataTypeSFixed32:
  940. return @(defaultValue_.valueInt32);
  941. case GPBDataTypeInt64:
  942. case GPBDataTypeSInt64:
  943. case GPBDataTypeSFixed64:
  944. return @(defaultValue_.valueInt64);
  945. case GPBDataTypeUInt32:
  946. case GPBDataTypeFixed32:
  947. return @(defaultValue_.valueUInt32);
  948. case GPBDataTypeUInt64:
  949. case GPBDataTypeFixed64:
  950. return @(defaultValue_.valueUInt64);
  951. case GPBDataTypeBytes:
  952. // Like message fields, the default is zero length data.
  953. return (defaultValue_.valueData ? defaultValue_.valueData
  954. : GPBEmptyNSData());
  955. case GPBDataTypeString:
  956. // Like message fields, the default is zero length string.
  957. return (defaultValue_.valueString ? defaultValue_.valueString : @"");
  958. case GPBDataTypeGroup:
  959. case GPBDataTypeMessage:
  960. return nil;
  961. }
  962. }
  963. - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other {
  964. int32_t selfNumber = description_->fieldNumber;
  965. int32_t otherNumber = other->description_->fieldNumber;
  966. if (selfNumber < otherNumber) {
  967. return NSOrderedAscending;
  968. } else if (selfNumber == otherNumber) {
  969. return NSOrderedSame;
  970. } else {
  971. return NSOrderedDescending;
  972. }
  973. }
  974. @end
  975. #pragma clang diagnostic pop