GPBDescriptor.m 29 KB

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