GPBDescriptor.m 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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 know, compute the flag for the rest of the runtime.
  454. if (!proto3OptionalKnown) {
  455. // If it was...
  456. // - proto3 syntax
  457. // - not repeated/map
  458. // - not in a oneof (negative has index)
  459. // - not a message (the flag doesn't make sense for messages)
  460. BOOL clearOnZero = ((syntax == GPBFileSyntaxProto3) &&
  461. !isMapOrArray &&
  462. (coreDesc->hasIndex >= 0) &&
  463. !isMessage);
  464. if (clearOnZero) {
  465. coreDesc->flags |= GPBFieldClearHasIvarOnZero;
  466. }
  467. }
  468. if (isMapOrArray) {
  469. // map<>/repeated fields get a *Count property (inplace of a has*) to
  470. // support checking if there are any entries without triggering
  471. // autocreation.
  472. hasOrCountSel_ = SelFromStrings(NULL, coreDesc->name, "_Count", NO);
  473. } else {
  474. // Know it is a single field; it gets has/setHas selectors if...
  475. // - not in a oneof (negative has index)
  476. // - not clearing on zero
  477. if ((coreDesc->hasIndex >= 0) &&
  478. ((coreDesc->flags & GPBFieldClearHasIvarOnZero) == 0)) {
  479. hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO);
  480. setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES);
  481. }
  482. }
  483. // Extra type specific data.
  484. if (isMessage) {
  485. // Note: Only fetch the class here, can't send messages to it because
  486. // that could cause cycles back to this class within +initialize if
  487. // two messages have each other in fields (i.e. - they build a graph).
  488. if (usesClassRefs) {
  489. msgClass_ = coreDesc->dataTypeSpecific.clazz;
  490. } else {
  491. // Backwards compatibility for sources generated with older protoc.
  492. const char *className = coreDesc->dataTypeSpecific.className;
  493. msgClass_ = objc_getClass(className);
  494. NSAssert(msgClass_, @"Class %s not defined", className);
  495. }
  496. } else if (dataType == GPBDataTypeEnum) {
  497. if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) {
  498. enumHandling_.enumDescriptor_ =
  499. coreDesc->dataTypeSpecific.enumDescFunc();
  500. } else {
  501. enumHandling_.enumVerifier_ =
  502. coreDesc->dataTypeSpecific.enumVerifier;
  503. }
  504. }
  505. // Non map<>/repeated fields can have defaults in proto2 syntax.
  506. if (!isMapOrArray && includesDefault) {
  507. defaultValue_ = ((GPBMessageFieldDescriptionWithDefault *)description)->defaultValue;
  508. if (dataType == GPBDataTypeBytes) {
  509. // Data stored as a length prefixed (network byte order) c-string in
  510. // descriptor structure.
  511. const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData;
  512. if (bytes) {
  513. uint32_t length;
  514. memcpy(&length, bytes, sizeof(length));
  515. length = ntohl(length);
  516. bytes += sizeof(length);
  517. defaultValue_.valueData =
  518. [[NSData alloc] initWithBytes:bytes length:length];
  519. }
  520. }
  521. }
  522. }
  523. return self;
  524. }
  525. - (void)dealloc {
  526. if (description_->dataType == GPBDataTypeBytes &&
  527. !(description_->flags & GPBFieldRepeated)) {
  528. [defaultValue_.valueData release];
  529. }
  530. [super dealloc];
  531. }
  532. - (GPBDataType)dataType {
  533. return description_->dataType;
  534. }
  535. - (BOOL)hasDefaultValue {
  536. return (description_->flags & GPBFieldHasDefaultValue) != 0;
  537. }
  538. - (uint32_t)number {
  539. return description_->number;
  540. }
  541. - (NSString *)name {
  542. return (NSString * _Nonnull)@(description_->name);
  543. }
  544. - (BOOL)isRequired {
  545. return (description_->flags & GPBFieldRequired) != 0;
  546. }
  547. - (BOOL)isOptional {
  548. return (description_->flags & GPBFieldOptional) != 0;
  549. }
  550. - (GPBFieldType)fieldType {
  551. GPBFieldFlags flags = description_->flags;
  552. if ((flags & GPBFieldRepeated) != 0) {
  553. return GPBFieldTypeRepeated;
  554. } else if ((flags & GPBFieldMapKeyMask) != 0) {
  555. return GPBFieldTypeMap;
  556. } else {
  557. return GPBFieldTypeSingle;
  558. }
  559. }
  560. - (GPBDataType)mapKeyDataType {
  561. switch (description_->flags & GPBFieldMapKeyMask) {
  562. case GPBFieldMapKeyInt32:
  563. return GPBDataTypeInt32;
  564. case GPBFieldMapKeyInt64:
  565. return GPBDataTypeInt64;
  566. case GPBFieldMapKeyUInt32:
  567. return GPBDataTypeUInt32;
  568. case GPBFieldMapKeyUInt64:
  569. return GPBDataTypeUInt64;
  570. case GPBFieldMapKeySInt32:
  571. return GPBDataTypeSInt32;
  572. case GPBFieldMapKeySInt64:
  573. return GPBDataTypeSInt64;
  574. case GPBFieldMapKeyFixed32:
  575. return GPBDataTypeFixed32;
  576. case GPBFieldMapKeyFixed64:
  577. return GPBDataTypeFixed64;
  578. case GPBFieldMapKeySFixed32:
  579. return GPBDataTypeSFixed32;
  580. case GPBFieldMapKeySFixed64:
  581. return GPBDataTypeSFixed64;
  582. case GPBFieldMapKeyBool:
  583. return GPBDataTypeBool;
  584. case GPBFieldMapKeyString:
  585. return GPBDataTypeString;
  586. default:
  587. NSAssert(0, @"Not a map type");
  588. return GPBDataTypeInt32; // For lack of anything better.
  589. }
  590. }
  591. - (BOOL)isPackable {
  592. return (description_->flags & GPBFieldPacked) != 0;
  593. }
  594. - (BOOL)isValidEnumValue:(int32_t)value {
  595. NSAssert(description_->dataType == GPBDataTypeEnum,
  596. @"Field Must be of type GPBDataTypeEnum");
  597. if (description_->flags & GPBFieldHasEnumDescriptor) {
  598. return enumHandling_.enumDescriptor_.enumVerifier(value);
  599. } else {
  600. return enumHandling_.enumVerifier_(value);
  601. }
  602. }
  603. - (GPBEnumDescriptor *)enumDescriptor {
  604. if (description_->flags & GPBFieldHasEnumDescriptor) {
  605. return enumHandling_.enumDescriptor_;
  606. } else {
  607. return nil;
  608. }
  609. }
  610. - (GPBGenericValue)defaultValue {
  611. // Depends on the fact that defaultValue_ is initialized either to "0/nil" or
  612. // to an actual defaultValue in our initializer.
  613. GPBGenericValue value = defaultValue_;
  614. if (!(description_->flags & GPBFieldRepeated)) {
  615. // We special handle data and strings. If they are nil, we replace them
  616. // with empty string/empty data.
  617. GPBDataType type = description_->dataType;
  618. if (type == GPBDataTypeBytes && value.valueData == nil) {
  619. value.valueData = GPBEmptyNSData();
  620. } else if (type == GPBDataTypeString && value.valueString == nil) {
  621. value.valueString = @"";
  622. }
  623. }
  624. return value;
  625. }
  626. - (NSString *)textFormatName {
  627. if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
  628. NSValue *extraInfoValue =
  629. objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
  630. // Support can be left out at generation time.
  631. if (!extraInfoValue) {
  632. return nil;
  633. }
  634. const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
  635. return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self),
  636. self.name);
  637. }
  638. // The logic here has to match SetCommonFieldVariables() from
  639. // objectivec_field.cc in the proto compiler.
  640. NSString *name = self.name;
  641. NSUInteger len = [name length];
  642. // Remove the "_p" added to reserved names.
  643. if ([name hasSuffix:@"_p"]) {
  644. name = [name substringToIndex:(len - 2)];
  645. len = [name length];
  646. }
  647. // Remove "Array" from the end for repeated fields.
  648. if (((description_->flags & GPBFieldRepeated) != 0) &&
  649. [name hasSuffix:@"Array"]) {
  650. name = [name substringToIndex:(len - 5)];
  651. len = [name length];
  652. }
  653. // Groups vs. other fields.
  654. if (description_->dataType == GPBDataTypeGroup) {
  655. // Just capitalize the first letter.
  656. unichar firstChar = [name characterAtIndex:0];
  657. if (firstChar >= 'a' && firstChar <= 'z') {
  658. NSString *firstCharString =
  659. [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
  660. NSString *result =
  661. [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
  662. withString:firstCharString];
  663. return result;
  664. }
  665. return name;
  666. } else {
  667. // Undo the CamelCase.
  668. NSMutableString *result = [NSMutableString stringWithCapacity:len];
  669. for (uint32_t i = 0; i < len; i++) {
  670. unichar c = [name characterAtIndex:i];
  671. if (c >= 'A' && c <= 'Z') {
  672. if (i > 0) {
  673. [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')];
  674. } else {
  675. [result appendFormat:@"%C", c];
  676. }
  677. } else {
  678. [result appendFormat:@"%C", c];
  679. }
  680. }
  681. return result;
  682. }
  683. }
  684. @end
  685. @implementation GPBEnumDescriptor {
  686. NSString *name_;
  687. // valueNames_ is a single c string with all of the value names appended
  688. // together, each null terminated. -calcValueNameOffsets fills in
  689. // nameOffsets_ with the offsets to allow quicker access to the individual
  690. // names.
  691. const char *valueNames_;
  692. const int32_t *values_;
  693. GPBEnumValidationFunc enumVerifier_;
  694. const uint8_t *extraTextFormatInfo_;
  695. uint32_t *nameOffsets_;
  696. uint32_t valueCount_;
  697. }
  698. @synthesize name = name_;
  699. @synthesize enumVerifier = enumVerifier_;
  700. + (instancetype)
  701. allocDescriptorForName:(NSString *)name
  702. valueNames:(const char *)valueNames
  703. values:(const int32_t *)values
  704. count:(uint32_t)valueCount
  705. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  706. GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name
  707. valueNames:valueNames
  708. values:values
  709. count:valueCount
  710. enumVerifier:enumVerifier];
  711. return descriptor;
  712. }
  713. + (instancetype)
  714. allocDescriptorForName:(NSString *)name
  715. valueNames:(const char *)valueNames
  716. values:(const int32_t *)values
  717. count:(uint32_t)valueCount
  718. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  719. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  720. // Call the common case.
  721. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name
  722. valueNames:valueNames
  723. values:values
  724. count:valueCount
  725. enumVerifier:enumVerifier];
  726. // Set the extra info.
  727. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo;
  728. return descriptor;
  729. }
  730. - (instancetype)initWithName:(NSString *)name
  731. valueNames:(const char *)valueNames
  732. values:(const int32_t *)values
  733. count:(uint32_t)valueCount
  734. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  735. if ((self = [super init])) {
  736. name_ = [name copy];
  737. valueNames_ = valueNames;
  738. values_ = values;
  739. valueCount_ = valueCount;
  740. enumVerifier_ = enumVerifier;
  741. }
  742. return self;
  743. }
  744. - (void)dealloc {
  745. [name_ release];
  746. if (nameOffsets_) free(nameOffsets_);
  747. [super dealloc];
  748. }
  749. - (void)calcValueNameOffsets {
  750. @synchronized(self) {
  751. if (nameOffsets_ != NULL) {
  752. return;
  753. }
  754. uint32_t *offsets = malloc(valueCount_ * sizeof(uint32_t));
  755. if (!offsets) return;
  756. const char *scan = valueNames_;
  757. for (uint32_t i = 0; i < valueCount_; ++i) {
  758. offsets[i] = (uint32_t)(scan - valueNames_);
  759. while (*scan != '\0') ++scan;
  760. ++scan; // Step over the null.
  761. }
  762. nameOffsets_ = offsets;
  763. }
  764. }
  765. - (NSString *)enumNameForValue:(int32_t)number {
  766. for (uint32_t i = 0; i < valueCount_; ++i) {
  767. if (values_[i] == number) {
  768. return [self getEnumNameForIndex:i];
  769. }
  770. }
  771. return nil;
  772. }
  773. - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name {
  774. // Must have the prefix.
  775. NSUInteger prefixLen = name_.length + 1;
  776. if ((name.length <= prefixLen) || ![name hasPrefix:name_] ||
  777. ([name characterAtIndex:prefixLen - 1] != '_')) {
  778. return NO;
  779. }
  780. // Skip over the prefix.
  781. const char *nameAsCStr = [name UTF8String];
  782. nameAsCStr += prefixLen;
  783. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  784. if (nameOffsets_ == NULL) return NO;
  785. // Find it.
  786. for (uint32_t i = 0; i < valueCount_; ++i) {
  787. const char *valueName = valueNames_ + nameOffsets_[i];
  788. if (strcmp(nameAsCStr, valueName) == 0) {
  789. if (outValue) {
  790. *outValue = values_[i];
  791. }
  792. return YES;
  793. }
  794. }
  795. return NO;
  796. }
  797. - (BOOL)getValue:(int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName {
  798. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  799. if (nameOffsets_ == NULL) return NO;
  800. for (uint32_t i = 0; i < valueCount_; ++i) {
  801. NSString *valueTextFormatName = [self getEnumTextFormatNameForIndex:i];
  802. if ([valueTextFormatName isEqual:textFormatName]) {
  803. if (outValue) {
  804. *outValue = values_[i];
  805. }
  806. return YES;
  807. }
  808. }
  809. return NO;
  810. }
  811. - (NSString *)textFormatNameForValue:(int32_t)number {
  812. // Find the EnumValue descriptor and its index.
  813. BOOL foundIt = NO;
  814. uint32_t valueDescriptorIndex;
  815. for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_;
  816. ++valueDescriptorIndex) {
  817. if (values_[valueDescriptorIndex] == number) {
  818. foundIt = YES;
  819. break;
  820. }
  821. }
  822. if (!foundIt) {
  823. return nil;
  824. }
  825. return [self getEnumTextFormatNameForIndex:valueDescriptorIndex];
  826. }
  827. - (uint32_t)enumNameCount {
  828. return valueCount_;
  829. }
  830. - (NSString *)getEnumNameForIndex:(uint32_t)index {
  831. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  832. if (nameOffsets_ == NULL) return nil;
  833. if (index >= valueCount_) {
  834. return nil;
  835. }
  836. const char *valueName = valueNames_ + nameOffsets_[index];
  837. NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName];
  838. return fullName;
  839. }
  840. - (NSString *)getEnumTextFormatNameForIndex:(uint32_t)index {
  841. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  842. if (nameOffsets_ == NULL) return nil;
  843. if (index >= valueCount_) {
  844. return nil;
  845. }
  846. NSString *result = nil;
  847. // Naming adds an underscore between enum name and value name, skip that also.
  848. const char *valueName = valueNames_ + nameOffsets_[index];
  849. NSString *shortName = @(valueName);
  850. // See if it is in the map of special format handling.
  851. if (extraTextFormatInfo_) {
  852. result = GPBDecodeTextFormatName(extraTextFormatInfo_,
  853. (int32_t)index, shortName);
  854. }
  855. // Logic here needs to match what objectivec_enum.cc does in the proto
  856. // compiler.
  857. if (result == nil) {
  858. NSUInteger len = [shortName length];
  859. NSMutableString *worker = [NSMutableString stringWithCapacity:len];
  860. for (NSUInteger i = 0; i < len; i++) {
  861. unichar c = [shortName characterAtIndex:i];
  862. if (i > 0 && c >= 'A' && c <= 'Z') {
  863. [worker appendString:@"_"];
  864. }
  865. [worker appendFormat:@"%c", toupper((char)c)];
  866. }
  867. result = worker;
  868. }
  869. return result;
  870. }
  871. @end
  872. @implementation GPBExtensionDescriptor {
  873. GPBGenericValue defaultValue_;
  874. }
  875. - (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc
  876. usesClassRefs:(BOOL)usesClassRefs {
  877. if ((self = [super init])) {
  878. description_ = desc;
  879. if (!usesClassRefs) {
  880. // Legacy without class ref support.
  881. const char *className = description_->messageOrGroupClass.name;
  882. if (className) {
  883. Class clazz = objc_lookUpClass(className);
  884. NSAssert(clazz != Nil, @"Class %s not defined", className);
  885. description_->messageOrGroupClass.clazz = clazz;
  886. }
  887. const char *extendedClassName = description_->extendedClass.name;
  888. if (extendedClassName) {
  889. Class clazz = objc_lookUpClass(extendedClassName);
  890. NSAssert(clazz, @"Class %s not defined", extendedClassName);
  891. description_->extendedClass.clazz = clazz;
  892. }
  893. }
  894. GPBDataType type = description_->dataType;
  895. if (type == GPBDataTypeBytes) {
  896. // Data stored as a length prefixed c-string in descriptor records.
  897. const uint8_t *bytes =
  898. (const uint8_t *)description_->defaultValue.valueData;
  899. if (bytes) {
  900. uint32_t length;
  901. memcpy(&length, bytes, sizeof(length));
  902. // The length is stored in network byte order.
  903. length = ntohl(length);
  904. bytes += sizeof(length);
  905. defaultValue_.valueData =
  906. [[NSData alloc] initWithBytes:bytes length:length];
  907. }
  908. } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) {
  909. // The default is looked up in -defaultValue instead since extensions
  910. // aren't common, we avoid the hit startup hit and it avoid initialization
  911. // order issues.
  912. } else {
  913. defaultValue_ = description_->defaultValue;
  914. }
  915. }
  916. return self;
  917. }
  918. - (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc {
  919. return [self initWithExtensionDescription:desc usesClassRefs:NO];
  920. }
  921. - (void)dealloc {
  922. if ((description_->dataType == GPBDataTypeBytes) &&
  923. !GPBExtensionIsRepeated(description_)) {
  924. [defaultValue_.valueData release];
  925. }
  926. [super dealloc];
  927. }
  928. - (instancetype)copyWithZone:(NSZone *)zone {
  929. #pragma unused(zone)
  930. // Immutable.
  931. return [self retain];
  932. }
  933. - (NSString *)singletonName {
  934. return (NSString * _Nonnull)@(description_->singletonName);
  935. }
  936. - (const char *)singletonNameC {
  937. return description_->singletonName;
  938. }
  939. - (uint32_t)fieldNumber {
  940. return description_->fieldNumber;
  941. }
  942. - (GPBDataType)dataType {
  943. return description_->dataType;
  944. }
  945. - (GPBWireFormat)wireType {
  946. return GPBWireFormatForType(description_->dataType,
  947. GPBExtensionIsPacked(description_));
  948. }
  949. - (GPBWireFormat)alternateWireType {
  950. NSAssert(GPBExtensionIsRepeated(description_),
  951. @"Only valid on repeated extensions");
  952. return GPBWireFormatForType(description_->dataType,
  953. !GPBExtensionIsPacked(description_));
  954. }
  955. - (BOOL)isRepeated {
  956. return GPBExtensionIsRepeated(description_);
  957. }
  958. - (BOOL)isPackable {
  959. return GPBExtensionIsPacked(description_);
  960. }
  961. - (Class)msgClass {
  962. return description_->messageOrGroupClass.clazz;
  963. }
  964. - (Class)containingMessageClass {
  965. return description_->extendedClass.clazz;
  966. }
  967. - (GPBEnumDescriptor *)enumDescriptor {
  968. if (description_->dataType == GPBDataTypeEnum) {
  969. GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc();
  970. return enumDescriptor;
  971. }
  972. return nil;
  973. }
  974. - (id)defaultValue {
  975. if (GPBExtensionIsRepeated(description_)) {
  976. return nil;
  977. }
  978. switch (description_->dataType) {
  979. case GPBDataTypeBool:
  980. return @(defaultValue_.valueBool);
  981. case GPBDataTypeFloat:
  982. return @(defaultValue_.valueFloat);
  983. case GPBDataTypeDouble:
  984. return @(defaultValue_.valueDouble);
  985. case GPBDataTypeInt32:
  986. case GPBDataTypeSInt32:
  987. case GPBDataTypeEnum:
  988. case GPBDataTypeSFixed32:
  989. return @(defaultValue_.valueInt32);
  990. case GPBDataTypeInt64:
  991. case GPBDataTypeSInt64:
  992. case GPBDataTypeSFixed64:
  993. return @(defaultValue_.valueInt64);
  994. case GPBDataTypeUInt32:
  995. case GPBDataTypeFixed32:
  996. return @(defaultValue_.valueUInt32);
  997. case GPBDataTypeUInt64:
  998. case GPBDataTypeFixed64:
  999. return @(defaultValue_.valueUInt64);
  1000. case GPBDataTypeBytes:
  1001. // Like message fields, the default is zero length data.
  1002. return (defaultValue_.valueData ? defaultValue_.valueData
  1003. : GPBEmptyNSData());
  1004. case GPBDataTypeString:
  1005. // Like message fields, the default is zero length string.
  1006. return (defaultValue_.valueString ? defaultValue_.valueString : @"");
  1007. case GPBDataTypeGroup:
  1008. case GPBDataTypeMessage:
  1009. return nil;
  1010. }
  1011. }
  1012. - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other {
  1013. int32_t selfNumber = description_->fieldNumber;
  1014. int32_t otherNumber = other->description_->fieldNumber;
  1015. if (selfNumber < otherNumber) {
  1016. return NSOrderedAscending;
  1017. } else if (selfNumber == otherNumber) {
  1018. return NSOrderedSame;
  1019. } else {
  1020. return NSOrderedDescending;
  1021. }
  1022. }
  1023. @end
  1024. #pragma clang diagnostic pop