GPBDescriptor.m 36 KB

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