GPBDescriptor.m 36 KB

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