GPBDescriptor.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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(GPBDataTypeMessage, NO);
  337. } else {
  338. format = GPBWireFormatForType(description->dataType,
  339. ((description->flags & GPBFieldPacked) != 0));
  340. }
  341. return GPBWireFormatMakeTag(description->number, format);
  342. }
  343. uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
  344. GPBMessageFieldDescription *description = self->description_;
  345. NSCAssert((description->flags & GPBFieldRepeated) != 0,
  346. @"Only valid on repeated fields");
  347. GPBWireFormat format =
  348. GPBWireFormatForType(description->dataType,
  349. ((description->flags & GPBFieldPacked) == 0));
  350. return GPBWireFormatMakeTag(description->number, format);
  351. }
  352. @implementation GPBFieldDescriptor {
  353. GPBGenericValue defaultValue_;
  354. GPBFieldOptions *fieldOptions_;
  355. // Message ivars
  356. Class msgClass_;
  357. // Enum ivars.
  358. // If protos are generated with GenerateEnumDescriptors on then it will
  359. // be a enumDescriptor, otherwise it will be a enumVerifier.
  360. union {
  361. GPBEnumDescriptor *enumDescriptor_;
  362. GPBEnumValidationFunc enumVerifier_;
  363. } enumHandling_;
  364. }
  365. @synthesize fieldOptions = fieldOptions_;
  366. @synthesize msgClass = msgClass_;
  367. @synthesize containingOneof = containingOneof_;
  368. - (instancetype)init {
  369. // Throw an exception if people attempt to not use the designated initializer.
  370. self = [super init];
  371. if (self != nil) {
  372. [self doesNotRecognizeSelector:_cmd];
  373. self = nil;
  374. }
  375. return self;
  376. }
  377. - (instancetype)initWithFieldDescription:
  378. (GPBMessageFieldDescription *)description
  379. rootClass:(Class)rootClass
  380. syntax:(GPBFileSyntax)syntax {
  381. if ((self = [super init])) {
  382. description_ = description;
  383. getSel_ = sel_getUid(description->name);
  384. setSel_ = SelFromStrings("set", description->name, NULL, YES);
  385. GPBDataType dataType = description->dataType;
  386. BOOL isMessage = GPBDataTypeIsMessage(dataType);
  387. BOOL isMapOrArray = GPBFieldIsMapOrArray(self);
  388. if (isMapOrArray) {
  389. // map<>/repeated fields get a *Count property (inplace of a has*) to
  390. // support checking if there are any entries without triggering
  391. // autocreation.
  392. hasOrCountSel_ = SelFromStrings(NULL, description->name, "_Count", NO);
  393. } else {
  394. // If there is a positive hasIndex, then:
  395. // - All fields types for proto2 messages get has* selectors.
  396. // - Only message fields for proto3 messages get has* selectors.
  397. // Note: the positive check is to handle oneOfs, we can't check
  398. // containingOneof_ because it isn't set until after initialization.
  399. if ((description->hasIndex >= 0) &&
  400. (description->hasIndex != GPBNoHasBit) &&
  401. ((syntax != GPBFileSyntaxProto3) || isMessage)) {
  402. hasOrCountSel_ = SelFromStrings("has", description->name, NULL, NO);
  403. setHasSel_ = SelFromStrings("setHas", description->name, NULL, YES);
  404. }
  405. }
  406. // Extra type specific data.
  407. if (isMessage) {
  408. const char *className = description->dataTypeSpecific.className;
  409. msgClass_ = objc_getClass(className);
  410. NSAssert(msgClass_, @"Class %s not defined", className);
  411. } else if (dataType == GPBDataTypeEnum) {
  412. if ((description_->flags & GPBFieldHasEnumDescriptor) != 0) {
  413. enumHandling_.enumDescriptor_ =
  414. description->dataTypeSpecific.enumDescFunc();
  415. } else {
  416. enumHandling_.enumVerifier_ =
  417. description->dataTypeSpecific.enumVerifier;
  418. }
  419. }
  420. // Non map<>/repeated fields can have defaults.
  421. if (!isMapOrArray) {
  422. defaultValue_ = description->defaultValue;
  423. if (dataType == GPBDataTypeBytes) {
  424. // Data stored as a length prefixed (network byte order) c-string in
  425. // descriptor structure.
  426. const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData;
  427. if (bytes) {
  428. uint32_t length = *((uint32_t *)bytes);
  429. length = ntohl(length);
  430. bytes += sizeof(length);
  431. defaultValue_.valueData =
  432. [[NSData alloc] initWithBytes:bytes length:length];
  433. }
  434. }
  435. }
  436. // FieldOptions stored as a length prefixed (network byte order) c-escaped
  437. // string in descriptor records.
  438. if (description->fieldOptions) {
  439. uint8_t *optionsBytes = (uint8_t *)description->fieldOptions;
  440. uint32_t optionsLength = *((uint32_t *)optionsBytes);
  441. optionsLength = ntohl(optionsLength);
  442. if (optionsLength > 0) {
  443. optionsBytes += sizeof(optionsLength);
  444. NSData *optionsData = [NSData dataWithBytesNoCopy:optionsBytes
  445. length:optionsLength
  446. freeWhenDone:NO];
  447. GPBExtensionRegistry *registry = [rootClass extensionRegistry];
  448. fieldOptions_ = [[GPBFieldOptions parseFromData:optionsData
  449. extensionRegistry:registry
  450. error:NULL] retain];
  451. }
  452. }
  453. }
  454. return self;
  455. }
  456. - (void)dealloc {
  457. if (description_->dataType == GPBDataTypeBytes &&
  458. !(description_->flags & GPBFieldRepeated)) {
  459. [defaultValue_.valueData release];
  460. }
  461. [super dealloc];
  462. }
  463. - (GPBDataType)dataType {
  464. return description_->dataType;
  465. }
  466. - (BOOL)hasDefaultValue {
  467. return (description_->flags & GPBFieldHasDefaultValue) != 0;
  468. }
  469. - (uint32_t)number {
  470. return description_->number;
  471. }
  472. - (NSString *)name {
  473. return @(description_->name);
  474. }
  475. - (BOOL)isRequired {
  476. return (description_->flags & GPBFieldRequired) != 0;
  477. }
  478. - (BOOL)isOptional {
  479. return (description_->flags & GPBFieldOptional) != 0;
  480. }
  481. - (GPBFieldType)fieldType {
  482. GPBFieldFlags flags = description_->flags;
  483. if ((flags & GPBFieldRepeated) != 0) {
  484. return GPBFieldTypeRepeated;
  485. } else if ((flags & GPBFieldMapKeyMask) != 0) {
  486. return GPBFieldTypeMap;
  487. } else {
  488. return GPBFieldTypeSingle;
  489. }
  490. }
  491. - (GPBDataType)mapKeyDataType {
  492. switch (description_->flags & GPBFieldMapKeyMask) {
  493. case GPBFieldMapKeyInt32:
  494. return GPBDataTypeInt32;
  495. case GPBFieldMapKeyInt64:
  496. return GPBDataTypeInt64;
  497. case GPBFieldMapKeyUInt32:
  498. return GPBDataTypeUInt32;
  499. case GPBFieldMapKeyUInt64:
  500. return GPBDataTypeUInt64;
  501. case GPBFieldMapKeySInt32:
  502. return GPBDataTypeSInt32;
  503. case GPBFieldMapKeySInt64:
  504. return GPBDataTypeSInt64;
  505. case GPBFieldMapKeyFixed32:
  506. return GPBDataTypeFixed32;
  507. case GPBFieldMapKeyFixed64:
  508. return GPBDataTypeFixed64;
  509. case GPBFieldMapKeySFixed32:
  510. return GPBDataTypeSFixed32;
  511. case GPBFieldMapKeySFixed64:
  512. return GPBDataTypeSFixed64;
  513. case GPBFieldMapKeyBool:
  514. return GPBDataTypeBool;
  515. case GPBFieldMapKeyString:
  516. return GPBDataTypeString;
  517. default:
  518. NSAssert(0, @"Not a map type");
  519. return GPBDataTypeInt32; // For lack of anything better.
  520. }
  521. }
  522. - (BOOL)isPackable {
  523. return (description_->flags & GPBFieldPacked) != 0;
  524. }
  525. - (BOOL)isValidEnumValue:(int32_t)value {
  526. NSAssert(description_->dataType == GPBDataTypeEnum,
  527. @"Field Must be of type GPBDataTypeEnum");
  528. if (description_->flags & GPBFieldHasEnumDescriptor) {
  529. return enumHandling_.enumDescriptor_.enumVerifier(value);
  530. } else {
  531. return enumHandling_.enumVerifier_(value);
  532. }
  533. }
  534. - (GPBEnumDescriptor *)enumDescriptor {
  535. if (description_->flags & GPBFieldHasEnumDescriptor) {
  536. return enumHandling_.enumDescriptor_;
  537. } else {
  538. return nil;
  539. }
  540. }
  541. - (GPBGenericValue)defaultValue {
  542. // Depends on the fact that defaultValue_ is initialized either to "0/nil" or
  543. // to an actual defaultValue in our initializer.
  544. GPBGenericValue value = defaultValue_;
  545. if (!(description_->flags & GPBFieldRepeated)) {
  546. // We special handle data and strings. If they are nil, we replace them
  547. // with empty string/empty data.
  548. GPBDataType type = description_->dataType;
  549. if (type == GPBDataTypeBytes && value.valueData == nil) {
  550. value.valueData = GPBEmptyNSData();
  551. } else if (type == GPBDataTypeString && value.valueString == nil) {
  552. value.valueString = @"";
  553. }
  554. }
  555. return value;
  556. }
  557. - (NSString *)textFormatName {
  558. if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
  559. NSValue *extraInfoValue =
  560. objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
  561. // Support can be left out at generation time.
  562. if (!extraInfoValue) {
  563. return nil;
  564. }
  565. const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
  566. return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self),
  567. self.name);
  568. }
  569. // The logic here has to match SetCommonFieldVariables() from
  570. // objectivec_field.cc in the proto compiler.
  571. NSString *name = self.name;
  572. NSUInteger len = [name length];
  573. // Remove the "_p" added to reserved names.
  574. if ([name hasSuffix:@"_p"]) {
  575. name = [name substringToIndex:(len - 2)];
  576. len = [name length];
  577. }
  578. // Remove "Array" from the end for repeated fields.
  579. if (((description_->flags & GPBFieldRepeated) != 0) &&
  580. [name hasSuffix:@"Array"]) {
  581. name = [name substringToIndex:(len - 5)];
  582. len = [name length];
  583. }
  584. // Groups vs. other fields.
  585. if (description_->dataType == GPBDataTypeGroup) {
  586. // Just capitalize the first letter.
  587. unichar firstChar = [name characterAtIndex:0];
  588. if (firstChar >= 'a' && firstChar <= 'z') {
  589. NSString *firstCharString =
  590. [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
  591. NSString *result =
  592. [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
  593. withString:firstCharString];
  594. return result;
  595. }
  596. return name;
  597. } else {
  598. // Undo the CamelCase.
  599. NSMutableString *result = [NSMutableString stringWithCapacity:len];
  600. for (NSUInteger i = 0; i < len; i++) {
  601. unichar c = [name characterAtIndex:i];
  602. if (c >= 'A' && c <= 'Z') {
  603. if (i > 0) {
  604. [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')];
  605. } else {
  606. [result appendFormat:@"%C", c];
  607. }
  608. } else {
  609. [result appendFormat:@"%C", c];
  610. }
  611. }
  612. return result;
  613. }
  614. }
  615. @end
  616. @implementation GPBEnumDescriptor {
  617. NSString *name_;
  618. GPBMessageEnumValueDescription *valueDescriptions_;
  619. NSUInteger valueDescriptionsCount_;
  620. GPBEnumValidationFunc enumVerifier_;
  621. const uint8_t *extraTextFormatInfo_;
  622. }
  623. @synthesize name = name_;
  624. @synthesize enumVerifier = enumVerifier_;
  625. + (instancetype)
  626. allocDescriptorForName:(NSString *)name
  627. values:(GPBMessageEnumValueDescription *)valueDescriptions
  628. valueCount:(NSUInteger)valueCount
  629. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  630. GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name
  631. values:valueDescriptions
  632. valueCount:valueCount
  633. enumVerifier:enumVerifier];
  634. return descriptor;
  635. }
  636. + (instancetype)
  637. allocDescriptorForName:(NSString *)name
  638. values:(GPBMessageEnumValueDescription *)valueDescriptions
  639. valueCount:(NSUInteger)valueCount
  640. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  641. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  642. // Call the common case.
  643. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name
  644. values:valueDescriptions
  645. valueCount:valueCount
  646. enumVerifier:enumVerifier];
  647. // Set the extra info.
  648. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo;
  649. return descriptor;
  650. }
  651. - (instancetype)initWithName:(NSString *)name
  652. values:(GPBMessageEnumValueDescription *)valueDescriptions
  653. valueCount:(NSUInteger)valueCount
  654. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  655. if ((self = [super init])) {
  656. name_ = [name copy];
  657. valueDescriptions_ = valueDescriptions;
  658. valueDescriptionsCount_ = valueCount;
  659. enumVerifier_ = enumVerifier;
  660. }
  661. return self;
  662. }
  663. - (NSString *)enumNameForValue:(int32_t)number {
  664. for (NSUInteger i = 0; i < valueDescriptionsCount_; ++i) {
  665. GPBMessageEnumValueDescription *scan = &valueDescriptions_[i];
  666. if ((scan->number == number) && (scan->name != NULL)) {
  667. NSString *fullName =
  668. [NSString stringWithFormat:@"%@_%s", name_, scan->name];
  669. return fullName;
  670. }
  671. }
  672. return nil;
  673. }
  674. - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name {
  675. // Must have the prefix.
  676. NSUInteger prefixLen = name_.length + 1;
  677. if ((name.length <= prefixLen) || ![name hasPrefix:name_] ||
  678. ([name characterAtIndex:prefixLen - 1] != '_')) {
  679. return NO;
  680. }
  681. // Skip over the prefix.
  682. const char *nameAsCStr = [name UTF8String];
  683. nameAsCStr += prefixLen;
  684. // Find it.
  685. for (NSUInteger i = 0; i < valueDescriptionsCount_; ++i) {
  686. GPBMessageEnumValueDescription *scan = &valueDescriptions_[i];
  687. if ((scan->name != NULL) && (strcmp(nameAsCStr, scan->name) == 0)) {
  688. if (outValue) {
  689. *outValue = scan->number;
  690. }
  691. return YES;
  692. }
  693. }
  694. return NO;
  695. }
  696. - (void)dealloc {
  697. [name_ release];
  698. [super dealloc];
  699. }
  700. - (NSString *)textFormatNameForValue:(int32_t)number {
  701. // Find the EnumValue descriptor and its index.
  702. GPBMessageEnumValueDescription *valueDescriptor = NULL;
  703. NSUInteger valueDescriptorIndex;
  704. for (valueDescriptorIndex = 0; valueDescriptorIndex < valueDescriptionsCount_;
  705. ++valueDescriptorIndex) {
  706. GPBMessageEnumValueDescription *scan =
  707. &valueDescriptions_[valueDescriptorIndex];
  708. if (scan->number == number) {
  709. valueDescriptor = scan;
  710. break;
  711. }
  712. }
  713. // If we didn't find it, or names were disable at proto compile time, nothing
  714. // we can do.
  715. if (!valueDescriptor || !valueDescriptor->name) {
  716. return nil;
  717. }
  718. NSString *result = nil;
  719. // Naming adds an underscore between enum name and value name, skip that also.
  720. NSString *shortName = @(valueDescriptor->name);
  721. // See if it is in the map of special format handling.
  722. if (extraTextFormatInfo_) {
  723. result = GPBDecodeTextFormatName(extraTextFormatInfo_,
  724. (int32_t)valueDescriptorIndex, shortName);
  725. }
  726. // Logic here needs to match what objectivec_enum.cc does in the proto
  727. // compiler.
  728. if (result == nil) {
  729. NSUInteger len = [shortName length];
  730. NSMutableString *worker = [NSMutableString stringWithCapacity:len];
  731. for (NSUInteger i = 0; i < len; i++) {
  732. unichar c = [shortName characterAtIndex:i];
  733. if (i > 0 && c >= 'A' && c <= 'Z') {
  734. [worker appendString:@"_"];
  735. }
  736. [worker appendFormat:@"%c", toupper((char)c)];
  737. }
  738. result = worker;
  739. }
  740. return result;
  741. }
  742. @end
  743. @implementation GPBExtensionDescriptor {
  744. GPBGenericValue defaultValue_;
  745. }
  746. @synthesize containingMessageClass = containingMessageClass_;
  747. - (instancetype)initWithExtensionDescription:
  748. (GPBExtensionDescription *)description {
  749. if ((self = [super init])) {
  750. description_ = description;
  751. #if DEBUG
  752. const char *className = description->messageOrGroupClassName;
  753. if (className) {
  754. NSAssert(objc_lookUpClass(className) != Nil,
  755. @"Class %s not defined", className);
  756. }
  757. #endif
  758. if (description->extendedClass) {
  759. Class containingClass = objc_lookUpClass(description->extendedClass);
  760. NSAssert(containingClass, @"Class %s not defined",
  761. description->extendedClass);
  762. containingMessageClass_ = containingClass;
  763. }
  764. GPBDataType type = description_->dataType;
  765. if (type == GPBDataTypeBytes) {
  766. // Data stored as a length prefixed c-string in descriptor records.
  767. const uint8_t *bytes =
  768. (const uint8_t *)description->defaultValue.valueData;
  769. if (bytes) {
  770. uint32_t length = *((uint32_t *)bytes);
  771. // The length is stored in network byte order.
  772. length = ntohl(length);
  773. bytes += sizeof(length);
  774. defaultValue_.valueData =
  775. [[NSData alloc] initWithBytes:bytes length:length];
  776. }
  777. } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) {
  778. // The default is looked up in -defaultValue instead since extensions
  779. // aren't common, we avoid the hit startup hit and it avoid initialization
  780. // order issues.
  781. } else {
  782. defaultValue_ = description->defaultValue;
  783. }
  784. }
  785. return self;
  786. }
  787. - (void)dealloc {
  788. if ((description_->dataType == GPBDataTypeBytes) &&
  789. !GPBExtensionIsRepeated(description_)) {
  790. [defaultValue_.valueData release];
  791. }
  792. [super dealloc];
  793. }
  794. - (instancetype)copyWithZone:(NSZone *)zone {
  795. #pragma unused(zone)
  796. // Immutable.
  797. return [self retain];
  798. }
  799. - (NSString *)singletonName {
  800. return @(description_->singletonName);
  801. }
  802. - (const char *)singletonNameC {
  803. return description_->singletonName;
  804. }
  805. - (uint32_t)fieldNumber {
  806. return description_->fieldNumber;
  807. }
  808. - (GPBDataType)dataType {
  809. return description_->dataType;
  810. }
  811. - (GPBWireFormat)wireType {
  812. return GPBWireFormatForType(description_->dataType,
  813. GPBExtensionIsPacked(description_));
  814. }
  815. - (GPBWireFormat)alternateWireType {
  816. NSAssert(GPBExtensionIsRepeated(description_),
  817. @"Only valid on repeated extensions");
  818. return GPBWireFormatForType(description_->dataType,
  819. !GPBExtensionIsPacked(description_));
  820. }
  821. - (BOOL)isRepeated {
  822. return GPBExtensionIsRepeated(description_);
  823. }
  824. - (BOOL)isMap {
  825. return (description_->options & GPBFieldMapKeyMask) != 0;
  826. }
  827. - (BOOL)isPackable {
  828. return GPBExtensionIsPacked(description_);
  829. }
  830. - (Class)msgClass {
  831. return objc_getClass(description_->messageOrGroupClassName);
  832. }
  833. - (GPBEnumDescriptor *)enumDescriptor {
  834. if (description_->dataType == GPBDataTypeEnum) {
  835. GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc();
  836. return enumDescriptor;
  837. }
  838. return nil;
  839. }
  840. - (id)defaultValue {
  841. if (GPBExtensionIsRepeated(description_)) {
  842. return nil;
  843. }
  844. switch (description_->dataType) {
  845. case GPBDataTypeBool:
  846. return @(defaultValue_.valueBool);
  847. case GPBDataTypeFloat:
  848. return @(defaultValue_.valueFloat);
  849. case GPBDataTypeDouble:
  850. return @(defaultValue_.valueDouble);
  851. case GPBDataTypeInt32:
  852. case GPBDataTypeSInt32:
  853. case GPBDataTypeEnum:
  854. case GPBDataTypeSFixed32:
  855. return @(defaultValue_.valueInt32);
  856. case GPBDataTypeInt64:
  857. case GPBDataTypeSInt64:
  858. case GPBDataTypeSFixed64:
  859. return @(defaultValue_.valueInt64);
  860. case GPBDataTypeUInt32:
  861. case GPBDataTypeFixed32:
  862. return @(defaultValue_.valueUInt32);
  863. case GPBDataTypeUInt64:
  864. case GPBDataTypeFixed64:
  865. return @(defaultValue_.valueUInt64);
  866. case GPBDataTypeBytes:
  867. // Like message fields, the default is zero length data.
  868. return (defaultValue_.valueData ? defaultValue_.valueData
  869. : GPBEmptyNSData());
  870. case GPBDataTypeString:
  871. // Like message fields, the default is zero length string.
  872. return (defaultValue_.valueString ? defaultValue_.valueString : @"");
  873. case GPBDataTypeGroup:
  874. case GPBDataTypeMessage:
  875. return nil;
  876. }
  877. }
  878. - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other {
  879. int32_t selfNumber = description_->fieldNumber;
  880. int32_t otherNumber = other->description_->fieldNumber;
  881. if (selfNumber < otherNumber) {
  882. return NSOrderedAscending;
  883. } else if (selfNumber == otherNumber) {
  884. return NSOrderedSame;
  885. } else {
  886. return NSOrderedDescending;
  887. }
  888. }
  889. @end