GPBDescriptor.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. #import "google/protobuf/Descriptor.pbobjc.h"
  36. // The address of this variable is used as a key for obj_getAssociatedObject.
  37. static const char kTextFormatExtraValueKey = 0;
  38. // Utility function to generate selectors on the fly.
  39. static SEL SelFromStrings(const char *prefix, const char *middle,
  40. const char *suffix, BOOL takesArg) {
  41. if (prefix == NULL && suffix == NULL && !takesArg) {
  42. return sel_getUid(middle);
  43. }
  44. const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0;
  45. const size_t middleLen = strlen(middle);
  46. const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0;
  47. size_t totalLen =
  48. prefixLen + middleLen + suffixLen + 1; // include space for null on end.
  49. if (takesArg) {
  50. totalLen += 1;
  51. }
  52. char buffer[totalLen];
  53. if (prefix != NULL) {
  54. memcpy(buffer, prefix, prefixLen);
  55. memcpy(buffer + prefixLen, middle, middleLen);
  56. buffer[prefixLen] = (char)toupper(buffer[prefixLen]);
  57. } else {
  58. memcpy(buffer, middle, middleLen);
  59. }
  60. if (suffix != NULL) {
  61. memcpy(buffer + prefixLen + middleLen, suffix, suffixLen);
  62. }
  63. if (takesArg) {
  64. buffer[totalLen - 2] = ':';
  65. }
  66. // Always null terminate it.
  67. buffer[totalLen - 1] = 0;
  68. SEL result = sel_getUid(buffer);
  69. return result;
  70. }
  71. static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
  72. NSArray *allMessageFields)
  73. __attribute__((ns_returns_retained));
  74. static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
  75. NSArray *allMessageFields) {
  76. NSMutableArray *result = [[NSMutableArray alloc] init];
  77. for (GPBFieldDescriptor *fieldDesc in allMessageFields) {
  78. if (fieldDesc->description_->hasIndex == hasIndex) {
  79. [result addObject:fieldDesc];
  80. }
  81. }
  82. return result;
  83. }
  84. @implementation GPBDescriptor {
  85. Class messageClass_;
  86. NSArray *enums_;
  87. GPBFileDescriptor *file_;
  88. BOOL wireFormat_;
  89. }
  90. @synthesize messageClass = messageClass_;
  91. @synthesize fields = fields_;
  92. @synthesize oneofs = oneofs_;
  93. @synthesize enums = enums_;
  94. @synthesize extensionRanges = extensionRanges_;
  95. @synthesize extensionRangesCount = extensionRangesCount_;
  96. @synthesize file = file_;
  97. @synthesize wireFormat = wireFormat_;
  98. + (instancetype)
  99. allocDescriptorForClass:(Class)messageClass
  100. rootClass:(Class)rootClass
  101. file:(GPBFileDescriptor *)file
  102. fields:(GPBMessageFieldDescription *)fieldDescriptions
  103. fieldCount:(NSUInteger)fieldCount
  104. oneofs:(GPBMessageOneofDescription *)oneofDescriptions
  105. oneofCount:(NSUInteger)oneofCount
  106. enums:(GPBMessageEnumDescription *)enumDescriptions
  107. enumCount:(NSUInteger)enumCount
  108. ranges:(const GPBExtensionRange *)ranges
  109. rangeCount:(NSUInteger)rangeCount
  110. storageSize:(size_t)storageSize
  111. wireFormat:(BOOL)wireFormat {
  112. NSMutableArray *fields = nil;
  113. NSMutableArray *oneofs = nil;
  114. NSMutableArray *enums = nil;
  115. NSMutableArray *extensionRanges = nil;
  116. GPBFileSyntax syntax = file.syntax;
  117. for (NSUInteger i = 0; i < fieldCount; ++i) {
  118. if (fields == nil) {
  119. fields = [[NSMutableArray alloc] initWithCapacity:fieldCount];
  120. }
  121. GPBFieldDescriptor *fieldDescriptor = [[GPBFieldDescriptor alloc]
  122. initWithFieldDescription:&fieldDescriptions[i]
  123. rootClass:rootClass
  124. syntax:syntax];
  125. [fields addObject:fieldDescriptor];
  126. [fieldDescriptor release];
  127. }
  128. for (NSUInteger i = 0; i < oneofCount; ++i) {
  129. if (oneofs == nil) {
  130. oneofs = [[NSMutableArray alloc] initWithCapacity:oneofCount];
  131. }
  132. GPBMessageOneofDescription *oneofDescription = &oneofDescriptions[i];
  133. NSArray *fieldsForOneof =
  134. NewFieldsArrayForHasIndex(oneofDescription->index, fields);
  135. GPBOneofDescriptor *oneofDescriptor =
  136. [[GPBOneofDescriptor alloc] initWithOneofDescription:oneofDescription
  137. fields:fieldsForOneof];
  138. [oneofs addObject:oneofDescriptor];
  139. [oneofDescriptor release];
  140. [fieldsForOneof release];
  141. }
  142. for (NSUInteger i = 0; i < enumCount; ++i) {
  143. if (enums == nil) {
  144. enums = [[NSMutableArray alloc] initWithCapacity:enumCount];
  145. }
  146. GPBEnumDescriptor *enumDescriptor =
  147. enumDescriptions[i].enumDescriptorFunc();
  148. [enums addObject:enumDescriptor];
  149. }
  150. GPBDescriptor *descriptor = [[self alloc] initWithClass:messageClass
  151. file:file
  152. fields:fields
  153. oneofs:oneofs
  154. enums:enums
  155. extensionRanges:ranges
  156. extensionRangesCount:rangeCount
  157. storageSize:storageSize
  158. wireFormat:wireFormat];
  159. [fields release];
  160. [oneofs release];
  161. [enums release];
  162. [extensionRanges release];
  163. return descriptor;
  164. }
  165. + (instancetype)
  166. allocDescriptorForClass:(Class)messageClass
  167. rootClass:(Class)rootClass
  168. file:(GPBFileDescriptor *)file
  169. fields:(GPBMessageFieldDescription *)fieldDescriptions
  170. fieldCount:(NSUInteger)fieldCount
  171. oneofs:(GPBMessageOneofDescription *)oneofDescriptions
  172. oneofCount:(NSUInteger)oneofCount
  173. enums:(GPBMessageEnumDescription *)enumDescriptions
  174. enumCount:(NSUInteger)enumCount
  175. ranges:(const GPBExtensionRange *)ranges
  176. rangeCount:(NSUInteger)rangeCount
  177. storageSize:(size_t)storageSize
  178. wireFormat:(BOOL)wireFormat
  179. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  180. GPBDescriptor *descriptor = [self allocDescriptorForClass:messageClass
  181. rootClass:rootClass
  182. file:file
  183. fields:fieldDescriptions
  184. fieldCount:fieldCount
  185. oneofs:oneofDescriptions
  186. oneofCount:oneofCount
  187. enums:enumDescriptions
  188. enumCount:enumCount
  189. ranges:ranges
  190. rangeCount:rangeCount
  191. storageSize:storageSize
  192. wireFormat:wireFormat];
  193. // Extra info is a compile time option, so skip the work if not needed.
  194. if (extraTextFormatInfo) {
  195. NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo];
  196. for (GPBFieldDescriptor *fieldDescriptor in descriptor->fields_) {
  197. if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) {
  198. objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey,
  199. extraInfoValue,
  200. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  201. }
  202. }
  203. }
  204. return descriptor;
  205. }
  206. - (instancetype)initWithClass:(Class)messageClass
  207. file:(GPBFileDescriptor *)file
  208. fields:(NSArray *)fields
  209. oneofs:(NSArray *)oneofs
  210. enums:(NSArray *)enums
  211. extensionRanges:(const GPBExtensionRange *)extensionRanges
  212. extensionRangesCount:(NSUInteger)extensionRangesCount
  213. storageSize:(size_t)storageSize
  214. wireFormat:(BOOL)wireFormat {
  215. if ((self = [super init])) {
  216. messageClass_ = messageClass;
  217. file_ = file;
  218. fields_ = [fields retain];
  219. oneofs_ = [oneofs retain];
  220. enums_ = [enums retain];
  221. extensionRanges_ = extensionRanges;
  222. extensionRangesCount_ = extensionRangesCount;
  223. storageSize_ = storageSize;
  224. wireFormat_ = wireFormat;
  225. }
  226. return self;
  227. }
  228. - (void)dealloc {
  229. [fields_ release];
  230. [oneofs_ release];
  231. [enums_ release];
  232. [super dealloc];
  233. }
  234. - (NSString *)name {
  235. return NSStringFromClass(messageClass_);
  236. }
  237. - (id)copyWithZone:(NSZone *)zone {
  238. #pragma unused(zone)
  239. return [self retain];
  240. }
  241. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  242. for (GPBFieldDescriptor *descriptor in fields_) {
  243. if (GPBFieldNumber(descriptor) == fieldNumber) {
  244. return descriptor;
  245. }
  246. }
  247. return nil;
  248. }
  249. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  250. for (GPBFieldDescriptor *descriptor in fields_) {
  251. if ([descriptor.name isEqual:name]) {
  252. return descriptor;
  253. }
  254. }
  255. return nil;
  256. }
  257. - (GPBOneofDescriptor *)oneofWithName:(NSString *)name {
  258. for (GPBOneofDescriptor *descriptor in oneofs_) {
  259. if ([descriptor.name isEqual:name]) {
  260. return descriptor;
  261. }
  262. }
  263. return nil;
  264. }
  265. - (GPBEnumDescriptor *)enumWithName:(NSString *)name {
  266. for (GPBEnumDescriptor *descriptor in enums_) {
  267. if ([descriptor.name isEqual:name]) {
  268. return descriptor;
  269. }
  270. }
  271. return nil;
  272. }
  273. @end
  274. @implementation GPBFileDescriptor {
  275. NSString *package_;
  276. GPBFileSyntax syntax_;
  277. }
  278. @synthesize package = package_;
  279. @synthesize syntax = syntax_;
  280. - (instancetype)initWithPackage:(NSString *)package
  281. syntax:(GPBFileSyntax)syntax {
  282. self = [super init];
  283. if (self) {
  284. package_ = [package copy];
  285. syntax_ = syntax;
  286. }
  287. return self;
  288. }
  289. @end
  290. @implementation GPBOneofDescriptor
  291. @synthesize fields = fields_;
  292. - (instancetype)initWithOneofDescription:
  293. (GPBMessageOneofDescription *)oneofDescription
  294. fields:(NSArray *)fields {
  295. self = [super init];
  296. if (self) {
  297. NSAssert(oneofDescription->index < 0, @"Should always be <0");
  298. oneofDescription_ = oneofDescription;
  299. fields_ = [fields retain];
  300. for (GPBFieldDescriptor *fieldDesc in fields) {
  301. fieldDesc->containingOneof_ = self;
  302. }
  303. caseSel_ = SelFromStrings(NULL, oneofDescription->name, "OneOfCase", NO);
  304. }
  305. return self;
  306. }
  307. - (void)dealloc {
  308. [fields_ release];
  309. [super dealloc];
  310. }
  311. - (NSString *)name {
  312. return @(oneofDescription_->name);
  313. }
  314. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  315. for (GPBFieldDescriptor *descriptor in fields_) {
  316. if (GPBFieldNumber(descriptor) == fieldNumber) {
  317. return descriptor;
  318. }
  319. }
  320. return nil;
  321. }
  322. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  323. for (GPBFieldDescriptor *descriptor in fields_) {
  324. if ([descriptor.name isEqual:name]) {
  325. return descriptor;
  326. }
  327. }
  328. return nil;
  329. }
  330. @end
  331. uint32_t GPBFieldTag(GPBFieldDescriptor *self) {
  332. GPBMessageFieldDescription *description = self->description_;
  333. GPBWireFormat format;
  334. if ((description->flags & GPBFieldMapKeyMask) != 0) {
  335. // Maps are repeated messages on the wire.
  336. format = GPBWireFormatForType(GPBTypeMessage, NO);
  337. } else {
  338. format = GPBWireFormatForType(description->type,
  339. description->flags & GPBFieldPacked);
  340. }
  341. return GPBWireFormatMakeTag(description->number, format);
  342. }
  343. @implementation GPBFieldDescriptor {
  344. GPBValue defaultValue_;
  345. GPBFieldOptions *fieldOptions_;
  346. // Message ivars
  347. Class msgClass_;
  348. // Enum ivars.
  349. // If protos are generated with GenerateEnumDescriptors on then it will
  350. // be a enumDescriptor, otherwise it will be a enumVerifier.
  351. union {
  352. GPBEnumDescriptor *enumDescriptor_;
  353. GPBEnumValidationFunc enumVerifier_;
  354. } enumHandling_;
  355. }
  356. @synthesize fieldOptions = fieldOptions_;
  357. @synthesize msgClass = msgClass_;
  358. @synthesize containingOneof = containingOneof_;
  359. - (instancetype)init {
  360. // Throw an exception if people attempt to not use the designated initializer.
  361. self = [super init];
  362. if (self != nil) {
  363. [self doesNotRecognizeSelector:_cmd];
  364. self = nil;
  365. }
  366. return self;
  367. }
  368. - (instancetype)initWithFieldDescription:
  369. (GPBMessageFieldDescription *)description
  370. rootClass:(Class)rootClass
  371. syntax:(GPBFileSyntax)syntax {
  372. if ((self = [super init])) {
  373. description_ = description;
  374. getSel_ = sel_getUid(description->name);
  375. setSel_ = SelFromStrings("set", description->name, NULL, YES);
  376. if (description->fieldOptions) {
  377. // FieldOptions stored as a length prefixed c-escaped string in descriptor
  378. // records.
  379. uint8_t *optionsBytes = (uint8_t *)description->fieldOptions;
  380. uint32_t optionsLength = *((uint32_t *)optionsBytes);
  381. // The length is stored in network byte order.
  382. optionsLength = ntohl(optionsLength);
  383. if (optionsLength > 0) {
  384. optionsBytes += sizeof(optionsLength);
  385. NSData *optionsData = [NSData dataWithBytesNoCopy:optionsBytes
  386. length:optionsLength
  387. freeWhenDone:NO];
  388. GPBExtensionRegistry *registry = [rootClass extensionRegistry];
  389. fieldOptions_ = [[GPBFieldOptions parseFromData:optionsData
  390. extensionRegistry:registry
  391. error:NULL] retain];
  392. }
  393. }
  394. GPBType type = description->type;
  395. BOOL isMessage = GPBTypeIsMessage(type);
  396. if (isMessage) {
  397. // No has* for repeated/map or something in a oneof (we can't check
  398. // containingOneof_ because it isn't set until after initialization).
  399. if ((description->hasIndex >= 0) &&
  400. (description->hasIndex != GPBNoHasBit)) {
  401. hasSel_ = SelFromStrings("has", description->name, NULL, NO);
  402. setHasSel_ = SelFromStrings("setHas", description->name, NULL, YES);
  403. }
  404. const char *className = description->typeSpecific.className;
  405. msgClass_ = objc_getClass(className);
  406. NSAssert1(msgClass_, @"Class %s not defined", className);
  407. // The defaultValue_ is fetched directly in -defaultValue to avoid
  408. // initialization order issues.
  409. } else {
  410. if (!GPBFieldIsMapOrArray(self)) {
  411. defaultValue_ = description->defaultValue;
  412. if (type == GPBTypeData) {
  413. // Data stored as a length prefixed c-string in descriptor records.
  414. const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData;
  415. if (bytes) {
  416. uint32_t length = *((uint32_t *)bytes);
  417. // The length is stored in network byte order.
  418. length = ntohl(length);
  419. bytes += sizeof(length);
  420. defaultValue_.valueData =
  421. [[NSData alloc] initWithBytes:bytes length:length];
  422. }
  423. }
  424. // No has* methods for proto3 or if our hasIndex is < 0 because it
  425. // means the field is in a oneof (we can't check containingOneof_
  426. // because it isn't set until after initialization).
  427. if ((syntax != GPBFileSyntaxProto3) && (description->hasIndex >= 0) &&
  428. (description->hasIndex != GPBNoHasBit)) {
  429. hasSel_ = SelFromStrings("has", description->name, NULL, NO);
  430. setHasSel_ = SelFromStrings("setHas", description->name, NULL, YES);
  431. }
  432. }
  433. if (GPBTypeIsEnum(type)) {
  434. if (description_->flags & GPBFieldHasEnumDescriptor) {
  435. enumHandling_.enumDescriptor_ =
  436. description->typeSpecific.enumDescFunc();
  437. } else {
  438. enumHandling_.enumVerifier_ = description->typeSpecific.enumVerifier;
  439. }
  440. }
  441. }
  442. }
  443. return self;
  444. }
  445. - (void)dealloc {
  446. if (description_->type == GPBTypeData &&
  447. !(description_->flags & GPBFieldRepeated)) {
  448. [defaultValue_.valueData release];
  449. }
  450. [super dealloc];
  451. }
  452. - (GPBType)type {
  453. return description_->type;
  454. }
  455. - (BOOL)hasDefaultValue {
  456. return (description_->flags & GPBFieldHasDefaultValue) != 0;
  457. }
  458. - (uint32_t)number {
  459. return description_->number;
  460. }
  461. - (NSString *)name {
  462. return @(description_->name);
  463. }
  464. - (BOOL)isRequired {
  465. return (description_->flags & GPBFieldRequired) != 0;
  466. }
  467. - (BOOL)isOptional {
  468. return (description_->flags & GPBFieldOptional) != 0;
  469. }
  470. - (GPBFieldType)fieldType {
  471. GPBFieldFlags flags = description_->flags;
  472. if ((flags & GPBFieldRepeated) != 0) {
  473. return GPBFieldTypeRepeated;
  474. } else if ((flags & GPBFieldMapKeyMask) != 0) {
  475. return GPBFieldTypeMap;
  476. } else {
  477. return GPBFieldTypeSingle;
  478. }
  479. }
  480. - (GPBType)mapKeyType {
  481. switch (description_->flags & GPBFieldMapKeyMask) {
  482. case GPBFieldMapKeyInt32:
  483. return GPBTypeInt32;
  484. case GPBFieldMapKeyInt64:
  485. return GPBTypeInt64;
  486. case GPBFieldMapKeyUInt32:
  487. return GPBTypeUInt32;
  488. case GPBFieldMapKeyUInt64:
  489. return GPBTypeUInt64;
  490. case GPBFieldMapKeySInt32:
  491. return GPBTypeSInt32;
  492. case GPBFieldMapKeySInt64:
  493. return GPBTypeSInt64;
  494. case GPBFieldMapKeyFixed32:
  495. return GPBTypeFixed32;
  496. case GPBFieldMapKeyFixed64:
  497. return GPBTypeFixed64;
  498. case GPBFieldMapKeySFixed32:
  499. return GPBTypeSFixed32;
  500. case GPBFieldMapKeySFixed64:
  501. return GPBTypeSFixed64;
  502. case GPBFieldMapKeyBool:
  503. return GPBTypeBool;
  504. case GPBFieldMapKeyString:
  505. return GPBTypeString;
  506. default:
  507. NSAssert(0, @"Not a map type");
  508. return GPBTypeInt32; // For lack of anything better.
  509. }
  510. }
  511. - (BOOL)isPackable {
  512. return (description_->flags & GPBFieldPacked) != 0;
  513. }
  514. - (BOOL)isValidEnumValue:(int32_t)value {
  515. NSAssert(description_->type == GPBTypeEnum,
  516. @"Field Must be of type GPBTypeEnum");
  517. if (description_->flags & GPBFieldHasEnumDescriptor) {
  518. return enumHandling_.enumDescriptor_.enumVerifier(value);
  519. } else {
  520. return enumHandling_.enumVerifier_(value);
  521. }
  522. }
  523. - (GPBEnumDescriptor *)enumDescriptor {
  524. if (description_->flags & GPBFieldHasEnumDescriptor) {
  525. return enumHandling_.enumDescriptor_;
  526. } else {
  527. return nil;
  528. }
  529. }
  530. - (GPBValue)defaultValue {
  531. // Depends on the fact that defaultValue_ is initialized either to "0/nil" or
  532. // to an actual defaultValue in our initializer.
  533. GPBValue value = defaultValue_;
  534. if (!(description_->flags & GPBFieldRepeated)) {
  535. // We special handle data and strings. If they are nil, we replace them
  536. // with empty string/empty data.
  537. GPBType type = description_->type;
  538. if (type == GPBTypeData && value.valueData == nil) {
  539. value.valueData = GPBEmptyNSData();
  540. } else if (type == GPBTypeString && value.valueString == nil) {
  541. value.valueString = @"";
  542. }
  543. }
  544. return value;
  545. }
  546. - (NSString *)textFormatName {
  547. if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
  548. NSValue *extraInfoValue =
  549. objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
  550. // Support can be left out at generation time.
  551. if (!extraInfoValue) {
  552. return nil;
  553. }
  554. const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
  555. return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self),
  556. self.name);
  557. }
  558. // The logic here has to match SetCommonFieldVariables() from
  559. // objectivec_field.cc in the proto compiler.
  560. NSString *name = self.name;
  561. NSUInteger len = [name length];
  562. // Remove the "_p" added to reserved names.
  563. if ([name hasSuffix:@"_p"]) {
  564. name = [name substringToIndex:(len - 2)];
  565. len = [name length];
  566. }
  567. // Remove "Array" from the end for repeated fields.
  568. if (((description_->flags & GPBFieldRepeated) != 0) &&
  569. [name hasSuffix:@"Array"]) {
  570. name = [name substringToIndex:(len - 5)];
  571. len = [name length];
  572. }
  573. // Groups vs. other fields.
  574. if (description_->type == GPBTypeGroup) {
  575. // Just capitalize the first letter.
  576. unichar firstChar = [name characterAtIndex:0];
  577. if (firstChar >= 'a' && firstChar <= 'z') {
  578. NSString *firstCharString =
  579. [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
  580. NSString *result =
  581. [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
  582. withString:firstCharString];
  583. return result;
  584. }
  585. return name;
  586. } else {
  587. // Undo the CamelCase.
  588. NSMutableString *result = [NSMutableString stringWithCapacity:len];
  589. for (NSUInteger i = 0; i < len; i++) {
  590. unichar c = [name characterAtIndex:i];
  591. if (c >= 'A' && c <= 'Z') {
  592. if (i > 0) {
  593. [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')];
  594. } else {
  595. [result appendFormat:@"%C", c];
  596. }
  597. } else {
  598. [result appendFormat:@"%C", c];
  599. }
  600. }
  601. return result;
  602. }
  603. }
  604. @end
  605. @implementation GPBEnumDescriptor {
  606. NSString *name_;
  607. GPBMessageEnumValueDescription *valueDescriptions_;
  608. NSUInteger valueDescriptionsCount_;
  609. GPBEnumValidationFunc enumVerifier_;
  610. const uint8_t *extraTextFormatInfo_;
  611. }
  612. @synthesize name = name_;
  613. @synthesize enumVerifier = enumVerifier_;
  614. + (instancetype)
  615. allocDescriptorForName:(NSString *)name
  616. values:(GPBMessageEnumValueDescription *)valueDescriptions
  617. valueCount:(NSUInteger)valueCount
  618. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  619. GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name
  620. values:valueDescriptions
  621. valueCount:valueCount
  622. enumVerifier:enumVerifier];
  623. return descriptor;
  624. }
  625. + (instancetype)
  626. allocDescriptorForName:(NSString *)name
  627. values:(GPBMessageEnumValueDescription *)valueDescriptions
  628. valueCount:(NSUInteger)valueCount
  629. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  630. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  631. // Call the common case.
  632. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name
  633. values:valueDescriptions
  634. valueCount:valueCount
  635. enumVerifier:enumVerifier];
  636. // Set the extra info.
  637. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo;
  638. return descriptor;
  639. }
  640. - (instancetype)initWithName:(NSString *)name
  641. values:(GPBMessageEnumValueDescription *)valueDescriptions
  642. valueCount:(NSUInteger)valueCount
  643. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  644. if ((self = [super init])) {
  645. name_ = [name copy];
  646. valueDescriptions_ = valueDescriptions;
  647. valueDescriptionsCount_ = valueCount;
  648. enumVerifier_ = enumVerifier;
  649. }
  650. return self;
  651. }
  652. - (NSString *)enumNameForValue:(int32_t)number {
  653. for (NSUInteger i = 0; i < valueDescriptionsCount_; ++i) {
  654. GPBMessageEnumValueDescription *scan = &valueDescriptions_[i];
  655. if ((scan->number == number) && (scan->name != NULL)) {
  656. NSString *fullName =
  657. [NSString stringWithFormat:@"%@_%s", name_, scan->name];
  658. return fullName;
  659. }
  660. }
  661. return nil;
  662. }
  663. - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name {
  664. // Must have the prefix.
  665. NSUInteger prefixLen = name_.length + 1;
  666. if ((name.length <= prefixLen) || ![name hasPrefix:name_] ||
  667. ([name characterAtIndex:prefixLen - 1] != '_')) {
  668. return NO;
  669. }
  670. // Skip over the prefix.
  671. const char *nameAsCStr = [name UTF8String];
  672. nameAsCStr += prefixLen;
  673. // Find it.
  674. for (NSUInteger i = 0; i < valueDescriptionsCount_; ++i) {
  675. GPBMessageEnumValueDescription *scan = &valueDescriptions_[i];
  676. if ((scan->name != NULL) && (strcmp(nameAsCStr, scan->name) == 0)) {
  677. if (outValue) {
  678. *outValue = scan->number;
  679. }
  680. return YES;
  681. }
  682. }
  683. return NO;
  684. }
  685. - (void)dealloc {
  686. [name_ release];
  687. [super dealloc];
  688. }
  689. - (NSString *)textFormatNameForValue:(int32_t)number {
  690. // Find the EnumValue descriptor and its index.
  691. GPBMessageEnumValueDescription *valueDescriptor = NULL;
  692. NSUInteger valueDescriptorIndex;
  693. for (valueDescriptorIndex = 0; valueDescriptorIndex < valueDescriptionsCount_;
  694. ++valueDescriptorIndex) {
  695. GPBMessageEnumValueDescription *scan =
  696. &valueDescriptions_[valueDescriptorIndex];
  697. if (scan->number == number) {
  698. valueDescriptor = scan;
  699. break;
  700. }
  701. }
  702. // If we didn't find it, or names were disable at proto compile time, nothing
  703. // we can do.
  704. if (!valueDescriptor || !valueDescriptor->name) {
  705. return nil;
  706. }
  707. NSString *result = nil;
  708. // Naming adds an underscore between enum name and value name, skip that also.
  709. NSString *shortName = @(valueDescriptor->name);
  710. // See if it is in the map of special format handling.
  711. if (extraTextFormatInfo_) {
  712. result = GPBDecodeTextFormatName(extraTextFormatInfo_,
  713. (int32_t)valueDescriptorIndex, shortName);
  714. }
  715. // Logic here needs to match what objectivec_enum.cc does in the proto
  716. // compiler.
  717. if (result == nil) {
  718. NSUInteger len = [shortName length];
  719. NSMutableString *worker = [NSMutableString stringWithCapacity:len];
  720. for (NSUInteger i = 0; i < len; i++) {
  721. unichar c = [shortName characterAtIndex:i];
  722. if (i > 0 && c >= 'A' && c <= 'Z') {
  723. [worker appendString:@"_"];
  724. }
  725. [worker appendFormat:@"%c", toupper((char)c)];
  726. }
  727. result = worker;
  728. }
  729. return result;
  730. }
  731. @end
  732. @implementation GPBExtensionDescriptor
  733. - (instancetype)initWithExtensionDescription:
  734. (GPBExtensionDescription *)description {
  735. if ((self = [super init])) {
  736. description_ = description;
  737. }
  738. return self;
  739. }
  740. - (NSString *)singletonName {
  741. return @(description_->singletonName);
  742. }
  743. - (const char *)singletonNameC {
  744. return description_->singletonName;
  745. }
  746. - (uint32_t)fieldNumber {
  747. return description_->fieldNumber;
  748. }
  749. - (GPBType)type {
  750. return description_->type;
  751. }
  752. - (BOOL)isRepeated {
  753. return (description_->options & GPBExtensionRepeated) != 0;
  754. }
  755. - (BOOL)isMap {
  756. return (description_->options & GPBFieldMapKeyMask) != 0;
  757. }
  758. - (BOOL)isPackable {
  759. return (description_->options & GPBExtensionPacked) != 0;
  760. }
  761. - (Class)msgClass {
  762. return objc_getClass(description_->messageOrGroupClassName);
  763. }
  764. - (GPBEnumDescriptor *)enumDescriptor {
  765. if (GPBTypeIsEnum(description_->type)) {
  766. GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc();
  767. return enumDescriptor;
  768. }
  769. return nil;
  770. }
  771. @end