GPBDescriptor.m 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. //
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file or at
  6. // https://developers.google.com/open-source/licenses/bsd
  7. #import "GPBDescriptor_PackagePrivate.h"
  8. #import <objc/runtime.h>
  9. #import "GPBMessage_PackagePrivate.h"
  10. #import "GPBUtilities_PackagePrivate.h"
  11. #import "GPBWireFormat.h"
  12. @interface GPBDescriptor ()
  13. - (instancetype)initWithClass:(Class)messageClass
  14. messageName:(NSString *)messageName
  15. fileDescription:(GPBFileDescription *)fileDescription
  16. fields:(NSArray *)fields
  17. storageSize:(uint32_t)storage
  18. wireFormat:(BOOL)wireFormat;
  19. @end
  20. @interface GPBFieldDescriptor ()
  21. // Single initializer
  22. // description has to be long lived, it is held as a raw pointer.
  23. - (instancetype)initWithFieldDescription:(void *)description
  24. descriptorFlags:(GPBDescriptorInitializationFlags)descriptorFlags;
  25. @end
  26. @interface GPBEnumDescriptor ()
  27. - (instancetype)initWithName:(NSString *)name
  28. valueNames:(const char *)valueNames
  29. values:(const int32_t *)values
  30. count:(uint32_t)valueCount
  31. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  32. flags:(GPBEnumDescriptorInitializationFlags)flags;
  33. @end
  34. // Direct access is use for speed, to avoid even internally declaring things
  35. // read/write, etc. The warning is enabled in the project to ensure code calling
  36. // protos can turn on -Wdirect-ivar-access without issues.
  37. #pragma clang diagnostic push
  38. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  39. // The addresses of these variables are used as keys for objc_getAssociatedObject.
  40. static const char kTextFormatExtraValueKey = 0;
  41. static const char kParentClassValueKey = 0;
  42. static const char kClassNameSuffixKey = 0;
  43. static const char kFileDescriptorCacheKey = 0;
  44. // Utility function to generate selectors on the fly.
  45. static SEL SelFromStrings(const char *prefix, const char *middle, const char *suffix,
  46. 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 = prefixLen + middleLen + suffixLen + 1; // include space for null on end.
  54. if (takesArg) {
  55. totalLen += 1;
  56. }
  57. char buffer[totalLen];
  58. if (prefix != NULL) {
  59. memcpy(buffer, prefix, prefixLen);
  60. memcpy(buffer + prefixLen, middle, middleLen);
  61. buffer[prefixLen] = (char)toupper(buffer[prefixLen]);
  62. } else {
  63. memcpy(buffer, middle, middleLen);
  64. }
  65. if (suffix != NULL) {
  66. memcpy(buffer + prefixLen + middleLen, suffix, suffixLen);
  67. }
  68. if (takesArg) {
  69. buffer[totalLen - 2] = ':';
  70. }
  71. // Always null terminate it.
  72. buffer[totalLen - 1] = 0;
  73. SEL result = sel_getUid(buffer);
  74. return result;
  75. }
  76. static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields)
  77. __attribute__((ns_returns_retained));
  78. static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields) {
  79. NSMutableArray *result = [[NSMutableArray alloc] init];
  80. for (GPBFieldDescriptor *fieldDesc in allMessageFields) {
  81. if (fieldDesc->description_->hasIndex == hasIndex) {
  82. [result addObject:fieldDesc];
  83. }
  84. }
  85. return result;
  86. }
  87. @implementation GPBDescriptor {
  88. Class messageClass_;
  89. NSString *messageName_;
  90. const GPBFileDescription *fileDescription_;
  91. BOOL wireFormat_;
  92. }
  93. @synthesize messageClass = messageClass_;
  94. @synthesize fields = fields_;
  95. @synthesize oneofs = oneofs_;
  96. @synthesize extensionRanges = extensionRanges_;
  97. @synthesize extensionRangesCount = extensionRangesCount_;
  98. @synthesize wireFormat = wireFormat_;
  99. + (instancetype)allocDescriptorForClass:(Class)messageClass
  100. messageName:(NSString *)messageName
  101. fileDescription:(GPBFileDescription *)fileDescription
  102. fields:(void *)fieldDescriptions
  103. fieldCount:(uint32_t)fieldCount
  104. storageSize:(uint32_t)storageSize
  105. flags:(GPBDescriptorInitializationFlags)flags {
  106. // Compute the unknown flags by this version of the runtime and then check the passed in flags
  107. // (from the generated code) to detect when sources from a newer version are being used with an
  108. // older runtime.
  109. GPBDescriptorInitializationFlags unknownFlags =
  110. ~(GPBDescriptorInitializationFlag_FieldsWithDefault |
  111. GPBDescriptorInitializationFlag_WireFormat | GPBDescriptorInitializationFlag_UsesClassRefs |
  112. GPBDescriptorInitializationFlag_Proto3OptionalKnown |
  113. GPBDescriptorInitializationFlag_ClosedEnumSupportKnown);
  114. if ((flags & unknownFlags) != 0) {
  115. GPBRuntimeMatchFailure();
  116. }
  117. #if defined(DEBUG) && DEBUG
  118. NSAssert((flags & GPBDescriptorInitializationFlag_UsesClassRefs) != 0,
  119. @"Internal error: all fields should have class refs");
  120. NSAssert((flags & GPBDescriptorInitializationFlag_Proto3OptionalKnown) != 0,
  121. @"Internal error: proto3 optional should be known");
  122. NSAssert((flags & GPBDescriptorInitializationFlag_ClosedEnumSupportKnown) != 0,
  123. @"Internal error: close enum should be known");
  124. // `messageName` and `fileDescription` should both be set or both be unset depending on if this is
  125. // being called from current code generation or legacy code generation.
  126. NSAssert((messageName == nil) == (fileDescription == NULL),
  127. @"name and fileDescription should always be provided together");
  128. #endif
  129. NSMutableArray *fields =
  130. (fieldCount ? [[NSMutableArray alloc] initWithCapacity:fieldCount] : nil);
  131. BOOL fieldsIncludeDefault = (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0;
  132. void *desc;
  133. GPBFieldFlags mergedFieldFlags = GPBFieldNone;
  134. for (uint32_t i = 0; i < fieldCount; ++i) {
  135. // Need correctly typed pointer for array indexing below to work.
  136. if (fieldsIncludeDefault) {
  137. desc = &(((GPBMessageFieldDescriptionWithDefault *)fieldDescriptions)[i]);
  138. mergedFieldFlags |=
  139. (((GPBMessageFieldDescriptionWithDefault *)fieldDescriptions)[i]).core.flags;
  140. } else {
  141. desc = &(((GPBMessageFieldDescription *)fieldDescriptions)[i]);
  142. mergedFieldFlags |= (((GPBMessageFieldDescription *)fieldDescriptions)[i]).flags;
  143. }
  144. GPBFieldDescriptor *fieldDescriptor =
  145. [[GPBFieldDescriptor alloc] initWithFieldDescription:desc descriptorFlags:flags];
  146. [fields addObject:fieldDescriptor];
  147. [fieldDescriptor release];
  148. }
  149. // No real value in checking all the fields individually, just check the combined flags at the
  150. // end.
  151. GPBFieldFlags unknownFieldFlags =
  152. ~(GPBFieldRequired | GPBFieldRepeated | GPBFieldPacked | GPBFieldOptional |
  153. GPBFieldHasDefaultValue | GPBFieldClearHasIvarOnZero | GPBFieldTextFormatNameCustom |
  154. GPBFieldHasEnumDescriptor | GPBFieldMapKeyMask | GPBFieldClosedEnum);
  155. if ((mergedFieldFlags & unknownFieldFlags) != 0) {
  156. GPBRuntimeMatchFailure();
  157. }
  158. BOOL wireFormat = (flags & GPBDescriptorInitializationFlag_WireFormat) != 0;
  159. GPBDescriptor *descriptor = [[self alloc] initWithClass:messageClass
  160. messageName:messageName
  161. fileDescription:fileDescription
  162. fields:fields
  163. storageSize:storageSize
  164. wireFormat:wireFormat];
  165. [fields release];
  166. return descriptor;
  167. }
  168. + (instancetype)allocDescriptorForClass:(Class)messageClass
  169. file:(GPBFileDescriptor *)file
  170. fields:(void *)fieldDescriptions
  171. fieldCount:(uint32_t)fieldCount
  172. storageSize:(uint32_t)storageSize
  173. flags:(GPBDescriptorInitializationFlags)flags {
  174. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30006,
  175. time_to_remove_this_old_version_shim);
  176. BOOL fixClassRefs = (flags & GPBDescriptorInitializationFlag_UsesClassRefs) == 0;
  177. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30003,
  178. time_to_remove_non_class_ref_support);
  179. BOOL fixProto3Optional = (flags & GPBDescriptorInitializationFlag_Proto3OptionalKnown) == 0;
  180. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30004,
  181. time_to_remove_proto3_optional_fallback);
  182. BOOL fixClosedEnums = (flags & GPBDescriptorInitializationFlag_ClosedEnumSupportKnown) == 0;
  183. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30005,
  184. time_to_remove_closed_enum_fallback);
  185. if (fixClassRefs || fixProto3Optional || fixClosedEnums) {
  186. BOOL fieldsIncludeDefault = (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0;
  187. #pragma clang diagnostic push
  188. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  189. GPBFileSyntax fileSyntax = file.syntax;
  190. #pragma clang diagnostic pop
  191. for (uint32_t i = 0; i < fieldCount; ++i) {
  192. GPBMessageFieldDescription *coreDesc;
  193. if (fieldsIncludeDefault) {
  194. coreDesc = &((((GPBMessageFieldDescriptionWithDefault *)fieldDescriptions)[i]).core);
  195. } else {
  196. coreDesc = &(((GPBMessageFieldDescription *)fieldDescriptions)[i]);
  197. }
  198. if (fixClassRefs && GPBDataTypeIsMessage(coreDesc->dataType)) {
  199. const char *className = coreDesc->dataTypeSpecific.className;
  200. Class msgClass = objc_getClass(className);
  201. NSAssert(msgClass, @"Class %s not defined", className);
  202. coreDesc->dataTypeSpecific.clazz = msgClass;
  203. }
  204. if (fixProto3Optional) {
  205. // If it was...
  206. // - proto3 syntax
  207. // - not repeated/map
  208. // - not in a oneof (negative has index)
  209. // - not a message (the flag doesn't make sense for messages)
  210. BOOL clearOnZero = ((fileSyntax == GPBFileSyntaxProto3) &&
  211. ((coreDesc->flags & (GPBFieldRepeated | GPBFieldMapKeyMask)) == 0) &&
  212. (coreDesc->hasIndex >= 0) && !GPBDataTypeIsMessage(coreDesc->dataType));
  213. if (clearOnZero) {
  214. coreDesc->flags |= GPBFieldClearHasIvarOnZero;
  215. }
  216. }
  217. if (fixClosedEnums) {
  218. // NOTE: This isn't correct, it is using the syntax of the file that
  219. // declared the field, not the syntax of the file that declared the
  220. // enum; but for older generated code, that's all we have and that happens
  221. // to be what the runtime was doing (even though it was wrong). This is
  222. // only wrong in the rare cases an enum is declared in a proto3 syntax
  223. // file but used for a field in the proto2 syntax file.
  224. BOOL isClosedEnum =
  225. (coreDesc->dataType == GPBDataTypeEnum && fileSyntax == GPBFileSyntaxProto2);
  226. if (isClosedEnum) {
  227. coreDesc->flags |= GPBFieldClosedEnum;
  228. }
  229. }
  230. }
  231. flags |= (GPBDescriptorInitializationFlag_UsesClassRefs |
  232. GPBDescriptorInitializationFlag_Proto3OptionalKnown |
  233. GPBDescriptorInitializationFlag_ClosedEnumSupportKnown);
  234. }
  235. GPBDescriptor *result = [self allocDescriptorForClass:messageClass
  236. messageName:nil
  237. fileDescription:NULL
  238. fields:fieldDescriptions
  239. fieldCount:fieldCount
  240. storageSize:storageSize
  241. flags:flags];
  242. objc_setAssociatedObject(result, &kFileDescriptorCacheKey, file,
  243. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  244. return result;
  245. }
  246. + (instancetype)allocDescriptorForClass:(Class)messageClass
  247. rootClass:(__unused Class)rootClass
  248. file:(GPBFileDescriptor *)file
  249. fields:(void *)fieldDescriptions
  250. fieldCount:(uint32_t)fieldCount
  251. storageSize:(uint32_t)storageSize
  252. flags:(GPBDescriptorInitializationFlags)flags {
  253. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30006,
  254. time_to_remove_this_old_version_shim);
  255. // The rootClass is no longer used, but it is passed as [ROOT class] to
  256. // ensure it was started up during initialization also when the message
  257. // scopes extensions.
  258. return [self allocDescriptorForClass:messageClass
  259. file:file
  260. fields:fieldDescriptions
  261. fieldCount:fieldCount
  262. storageSize:storageSize
  263. flags:flags];
  264. }
  265. - (instancetype)initWithClass:(Class)messageClass
  266. messageName:(NSString *)messageName
  267. fileDescription:(GPBFileDescription *)fileDescription
  268. fields:(NSArray *)fields
  269. storageSize:(uint32_t)storageSize
  270. wireFormat:(BOOL)wireFormat {
  271. if ((self = [super init])) {
  272. messageClass_ = messageClass;
  273. messageName_ = [messageName copy];
  274. fileDescription_ = fileDescription;
  275. fields_ = [fields retain];
  276. storageSize_ = storageSize;
  277. wireFormat_ = wireFormat;
  278. }
  279. return self;
  280. }
  281. - (void)dealloc {
  282. [messageName_ release];
  283. [fields_ release];
  284. [oneofs_ release];
  285. [super dealloc];
  286. }
  287. // No need to provide -hash/-isEqual: as the instances are singletons and the
  288. // default from NSObject is fine.
  289. - (instancetype)copyWithZone:(__unused NSZone *)zone {
  290. // Immutable.
  291. return [self retain];
  292. }
  293. - (void)setupOneofs:(const char **)oneofNames
  294. count:(uint32_t)count
  295. firstHasIndex:(int32_t)firstHasIndex {
  296. NSCAssert(firstHasIndex < 0, @"Should always be <0");
  297. NSMutableArray *oneofs = [[NSMutableArray alloc] initWithCapacity:count];
  298. for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) {
  299. const char *name = oneofNames[i];
  300. NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_);
  301. NSCAssert(fieldsForOneof.count > 0, @"No fields for this oneof? (%s:%d)", name, hasIndex);
  302. GPBOneofDescriptor *oneofDescriptor = [[GPBOneofDescriptor alloc] initWithName:name
  303. fields:fieldsForOneof];
  304. [oneofs addObject:oneofDescriptor];
  305. [oneofDescriptor release];
  306. [fieldsForOneof release];
  307. }
  308. oneofs_ = oneofs;
  309. }
  310. - (void)setupExtraTextInfo:(const char *)extraTextFormatInfo {
  311. // Extra info is a compile time option, so skip the work if not needed.
  312. if (extraTextFormatInfo) {
  313. NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo];
  314. for (GPBFieldDescriptor *fieldDescriptor in fields_) {
  315. if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) {
  316. objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey, extraInfoValue,
  317. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  318. }
  319. }
  320. }
  321. }
  322. - (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count {
  323. extensionRanges_ = ranges;
  324. extensionRangesCount_ = count;
  325. }
  326. - (void)setupContainingMessageClass:(Class)messageClass {
  327. objc_setAssociatedObject(self, &kParentClassValueKey, messageClass, OBJC_ASSOCIATION_ASSIGN);
  328. }
  329. - (void)setupContainingMessageClassName:(const char *)msgClassName {
  330. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30003,
  331. time_to_remove_this_old_version_shim);
  332. // Note: Only fetch the class here, can't send messages to it because
  333. // that could cause cycles back to this class within +initialize if
  334. // two messages have each other in fields (i.e. - they build a graph).
  335. Class clazz = objc_getClass(msgClassName);
  336. NSAssert(clazz, @"Class %s not defined", msgClassName);
  337. [self setupContainingMessageClass:clazz];
  338. }
  339. - (void)setupMessageClassNameSuffix:(NSString *)suffix {
  340. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30007,
  341. time_to_remove_this_old_version_shim);
  342. if (suffix.length) {
  343. objc_setAssociatedObject(self, &kClassNameSuffixKey, suffix, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  344. }
  345. }
  346. - (NSString *)name {
  347. return NSStringFromClass(messageClass_);
  348. }
  349. - (GPBFileDescriptor *)file {
  350. @synchronized(self) {
  351. GPBFileDescriptor *result = objc_getAssociatedObject(self, &kFileDescriptorCacheKey);
  352. if (!result) {
  353. #if defined(DEBUG) && DEBUG
  354. NSAssert(fileDescription_ != NULL, @"Internal error in generation/startup");
  355. #endif
  356. // `package` and `prefix` can both be NULL if there wasn't one for the file.
  357. NSString *package = fileDescription_->package ? @(fileDescription_->package) : @"";
  358. if (fileDescription_->prefix) {
  359. result = [[GPBFileDescriptor alloc] initWithPackage:package
  360. objcPrefix:@(fileDescription_->prefix)
  361. syntax:fileDescription_->syntax];
  362. } else {
  363. result = [[GPBFileDescriptor alloc] initWithPackage:package
  364. syntax:fileDescription_->syntax];
  365. }
  366. objc_setAssociatedObject(result, &kFileDescriptorCacheKey, result,
  367. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  368. }
  369. return result;
  370. }
  371. }
  372. - (GPBDescriptor *)containingType {
  373. Class parentClass = objc_getAssociatedObject(self, &kParentClassValueKey);
  374. return [parentClass descriptor];
  375. }
  376. - (NSString *)fullName {
  377. GPBDescriptor *parent = self.containingType;
  378. if (messageName_) {
  379. if (parent) {
  380. return [NSString stringWithFormat:@"%@.%@", parent.fullName, messageName_];
  381. }
  382. if (fileDescription_->package) {
  383. return [NSString stringWithFormat:@"%s.%@", fileDescription_->package, messageName_];
  384. }
  385. return messageName_;
  386. }
  387. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30007,
  388. time_to_remove_this_old_approach);
  389. // NOTE: When this code path is removed, this also means this api can't return nil any more but
  390. // that would be a breaking code change (not longer a Swift optional), so changing that will be
  391. // harder.
  392. NSString *className = NSStringFromClass(self.messageClass);
  393. GPBFileDescriptor *file = self.file;
  394. NSString *objcPrefix = file.objcPrefix;
  395. if (objcPrefix && ![className hasPrefix:objcPrefix]) {
  396. NSAssert(0, @"Class didn't have correct prefix? (%@ - %@)", className, objcPrefix);
  397. return nil;
  398. }
  399. NSString *name = nil;
  400. if (parent) {
  401. NSString *parentClassName = NSStringFromClass(parent.messageClass);
  402. // The generator will add _Class to avoid reserved words, drop it.
  403. NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey);
  404. if (suffix) {
  405. if (![parentClassName hasSuffix:suffix]) {
  406. NSAssert(0, @"ParentMessage class didn't have correct suffix? (%@ - %@)", className,
  407. suffix);
  408. return nil;
  409. }
  410. parentClassName = [parentClassName substringToIndex:(parentClassName.length - suffix.length)];
  411. }
  412. NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"];
  413. if (![className hasPrefix:parentPrefix]) {
  414. NSAssert(0, @"Class didn't have the correct parent name prefix? (%@ - %@)", parentPrefix,
  415. className);
  416. return nil;
  417. }
  418. name = [className substringFromIndex:parentPrefix.length];
  419. } else {
  420. name = [className substringFromIndex:objcPrefix.length];
  421. }
  422. // The generator will add _Class to avoid reserved words, drop it.
  423. NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey);
  424. if (suffix) {
  425. if (![name hasSuffix:suffix]) {
  426. NSAssert(0, @"Message class didn't have correct suffix? (%@ - %@)", name, suffix);
  427. return nil;
  428. }
  429. name = [name substringToIndex:(name.length - suffix.length)];
  430. }
  431. NSString *prefix = (parent != nil ? parent.fullName : file.package);
  432. NSString *result;
  433. if (prefix.length > 0) {
  434. result = [NSString stringWithFormat:@"%@.%@", prefix, name];
  435. } else {
  436. result = name;
  437. }
  438. return result;
  439. }
  440. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  441. for (GPBFieldDescriptor *descriptor in fields_) {
  442. if (GPBFieldNumber(descriptor) == fieldNumber) {
  443. return descriptor;
  444. }
  445. }
  446. return nil;
  447. }
  448. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  449. for (GPBFieldDescriptor *descriptor in fields_) {
  450. if ([descriptor.name isEqual:name]) {
  451. return descriptor;
  452. }
  453. }
  454. return nil;
  455. }
  456. - (GPBOneofDescriptor *)oneofWithName:(NSString *)name {
  457. for (GPBOneofDescriptor *descriptor in oneofs_) {
  458. if ([descriptor.name isEqual:name]) {
  459. return descriptor;
  460. }
  461. }
  462. return nil;
  463. }
  464. @end
  465. @implementation GPBFileDescriptor {
  466. NSString *package_;
  467. NSString *objcPrefix_;
  468. GPBFileSyntax syntax_;
  469. }
  470. @synthesize package = package_;
  471. @synthesize objcPrefix = objcPrefix_;
  472. @synthesize syntax = syntax_;
  473. - (instancetype)initWithPackage:(NSString *)package
  474. objcPrefix:(NSString *)objcPrefix
  475. syntax:(GPBFileSyntax)syntax {
  476. self = [super init];
  477. if (self) {
  478. package_ = [package copy];
  479. objcPrefix_ = [objcPrefix copy];
  480. syntax_ = syntax;
  481. }
  482. return self;
  483. }
  484. - (instancetype)initWithPackage:(NSString *)package syntax:(GPBFileSyntax)syntax {
  485. self = [super init];
  486. if (self) {
  487. package_ = [package copy];
  488. syntax_ = syntax;
  489. }
  490. return self;
  491. }
  492. - (void)dealloc {
  493. [package_ release];
  494. [objcPrefix_ release];
  495. [super dealloc];
  496. }
  497. - (BOOL)isEqual:(id)other {
  498. if (other == self) {
  499. return YES;
  500. }
  501. if (![other isKindOfClass:[GPBFileDescriptor class]]) {
  502. return NO;
  503. }
  504. GPBFileDescriptor *otherFile = other;
  505. // objcPrefix can be nil, otherwise, straight up compare.
  506. return (syntax_ == otherFile->syntax_ && [package_ isEqual:otherFile->package_] &&
  507. (objcPrefix_ == otherFile->objcPrefix_ ||
  508. (otherFile->objcPrefix_ && [objcPrefix_ isEqual:otherFile->objcPrefix_])));
  509. }
  510. - (NSUInteger)hash {
  511. // The prefix is recommended to be the same for a given package, so just hash
  512. // the package.
  513. return [package_ hash];
  514. }
  515. - (instancetype)copyWithZone:(__unused NSZone *)zone {
  516. // Immutable.
  517. return [self retain];
  518. }
  519. @end
  520. @implementation GPBOneofDescriptor
  521. @synthesize fields = fields_;
  522. - (instancetype)initWithName:(const char *)name fields:(NSArray *)fields {
  523. self = [super init];
  524. if (self) {
  525. name_ = name;
  526. fields_ = [fields retain];
  527. for (GPBFieldDescriptor *fieldDesc in fields) {
  528. fieldDesc->containingOneof_ = self;
  529. }
  530. caseSel_ = SelFromStrings(NULL, name, "OneOfCase", NO);
  531. }
  532. return self;
  533. }
  534. - (void)dealloc {
  535. [fields_ release];
  536. [super dealloc];
  537. }
  538. // No need to provide -hash/-isEqual: as the instances are singletons and the
  539. // default from NSObject is fine.
  540. - (instancetype)copyWithZone:(__unused NSZone *)zone {
  541. // Immutable.
  542. return [self retain];
  543. }
  544. - (NSString *)name {
  545. return (NSString *_Nonnull)@(name_);
  546. }
  547. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  548. for (GPBFieldDescriptor *descriptor in fields_) {
  549. if (GPBFieldNumber(descriptor) == fieldNumber) {
  550. return descriptor;
  551. }
  552. }
  553. return nil;
  554. }
  555. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  556. for (GPBFieldDescriptor *descriptor in fields_) {
  557. if ([descriptor.name isEqual:name]) {
  558. return descriptor;
  559. }
  560. }
  561. return nil;
  562. }
  563. @end
  564. uint32_t GPBFieldTag(GPBFieldDescriptor *self) {
  565. GPBMessageFieldDescription *description = self->description_;
  566. GPBWireFormat format;
  567. if ((description->flags & GPBFieldMapKeyMask) != 0) {
  568. // Maps are repeated messages on the wire.
  569. format = GPBWireFormatForType(GPBDataTypeMessage, NO);
  570. } else {
  571. format =
  572. GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) != 0));
  573. }
  574. return GPBWireFormatMakeTag(description->number, format);
  575. }
  576. uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
  577. GPBMessageFieldDescription *description = self->description_;
  578. NSCAssert((description->flags & GPBFieldRepeated) != 0, @"Only valid on repeated fields");
  579. GPBWireFormat format =
  580. GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) == 0));
  581. return GPBWireFormatMakeTag(description->number, format);
  582. }
  583. @implementation GPBFieldDescriptor {
  584. GPBGenericValue defaultValue_;
  585. // Message ivars
  586. Class msgClass_;
  587. // Enum ivars.
  588. GPBEnumDescriptor *enumDescriptor_;
  589. }
  590. @synthesize msgClass = msgClass_;
  591. @synthesize containingOneof = containingOneof_;
  592. - (instancetype)initWithFieldDescription:(void *)description
  593. descriptorFlags:(GPBDescriptorInitializationFlags)descriptorFlags {
  594. if ((self = [super init])) {
  595. BOOL includesDefault =
  596. (descriptorFlags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0;
  597. GPBMessageFieldDescription *coreDesc;
  598. if (includesDefault) {
  599. coreDesc = &(((GPBMessageFieldDescriptionWithDefault *)description)->core);
  600. } else {
  601. coreDesc = description;
  602. }
  603. description_ = coreDesc;
  604. getSel_ = sel_getUid(coreDesc->name);
  605. setSel_ = SelFromStrings("set", coreDesc->name, NULL, YES);
  606. GPBDataType dataType = coreDesc->dataType;
  607. BOOL isMessage = GPBDataTypeIsMessage(dataType);
  608. BOOL isMapOrArray = GPBFieldIsMapOrArray(self);
  609. if (isMapOrArray) {
  610. // map<>/repeated fields get a *Count property (inplace of a has*) to
  611. // support checking if there are any entries without triggering
  612. // autocreation.
  613. hasOrCountSel_ = SelFromStrings(NULL, coreDesc->name, "_Count", NO);
  614. } else {
  615. // It is a single field; it gets has/setHas selectors if...
  616. // - not in a oneof (negative has index)
  617. // - not clearing on zero
  618. if ((coreDesc->hasIndex >= 0) && ((coreDesc->flags & GPBFieldClearHasIvarOnZero) == 0)) {
  619. hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO);
  620. setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES);
  621. }
  622. }
  623. // Extra type specific data.
  624. if (isMessage) {
  625. // Note: Only fetch the class here, can't send messages to it because
  626. // that could cause cycles back to this class within +initialize if
  627. // two messages have each other in fields (i.e. - they build a graph).
  628. msgClass_ = coreDesc->dataTypeSpecific.clazz;
  629. } else if (dataType == GPBDataTypeEnum) {
  630. enumDescriptor_ = coreDesc->dataTypeSpecific.enumDescFunc();
  631. #if defined(DEBUG) && DEBUG
  632. NSAssert((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0,
  633. @"Field must have GPBFieldHasEnumDescriptor set");
  634. #endif // DEBUG
  635. }
  636. // Non map<>/repeated fields can have defaults in proto2 syntax.
  637. if (!isMapOrArray && includesDefault) {
  638. defaultValue_ = ((GPBMessageFieldDescriptionWithDefault *)description)->defaultValue;
  639. if (dataType == GPBDataTypeBytes) {
  640. // Data stored as a length prefixed (network byte order) c-string in
  641. // descriptor structure.
  642. const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData;
  643. if (bytes) {
  644. uint32_t length;
  645. memcpy(&length, bytes, sizeof(length));
  646. length = ntohl(length);
  647. bytes += sizeof(length);
  648. defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length];
  649. }
  650. }
  651. }
  652. }
  653. return self;
  654. }
  655. - (void)dealloc {
  656. if (description_->dataType == GPBDataTypeBytes && !(description_->flags & GPBFieldRepeated)) {
  657. [defaultValue_.valueData release];
  658. }
  659. [super dealloc];
  660. }
  661. // No need to provide -hash/-isEqual: as the instances are singletons and the
  662. // default from NSObject is fine.
  663. - (instancetype)copyWithZone:(__unused NSZone *)zone {
  664. // Immutable.
  665. return [self retain];
  666. }
  667. - (GPBDataType)dataType {
  668. return description_->dataType;
  669. }
  670. - (BOOL)hasDefaultValue {
  671. return (description_->flags & GPBFieldHasDefaultValue) != 0;
  672. }
  673. - (uint32_t)number {
  674. return description_->number;
  675. }
  676. - (NSString *)name {
  677. return (NSString *_Nonnull)@(description_->name);
  678. }
  679. - (BOOL)isRequired {
  680. return (description_->flags & GPBFieldRequired) != 0;
  681. }
  682. - (BOOL)isOptional {
  683. return (description_->flags & GPBFieldOptional) != 0;
  684. }
  685. - (GPBFieldType)fieldType {
  686. GPBFieldFlags flags = description_->flags;
  687. if ((flags & GPBFieldRepeated) != 0) {
  688. return GPBFieldTypeRepeated;
  689. } else if ((flags & GPBFieldMapKeyMask) != 0) {
  690. return GPBFieldTypeMap;
  691. } else {
  692. return GPBFieldTypeSingle;
  693. }
  694. }
  695. - (GPBDataType)mapKeyDataType {
  696. switch (description_->flags & GPBFieldMapKeyMask) {
  697. case GPBFieldMapKeyInt32:
  698. return GPBDataTypeInt32;
  699. case GPBFieldMapKeyInt64:
  700. return GPBDataTypeInt64;
  701. case GPBFieldMapKeyUInt32:
  702. return GPBDataTypeUInt32;
  703. case GPBFieldMapKeyUInt64:
  704. return GPBDataTypeUInt64;
  705. case GPBFieldMapKeySInt32:
  706. return GPBDataTypeSInt32;
  707. case GPBFieldMapKeySInt64:
  708. return GPBDataTypeSInt64;
  709. case GPBFieldMapKeyFixed32:
  710. return GPBDataTypeFixed32;
  711. case GPBFieldMapKeyFixed64:
  712. return GPBDataTypeFixed64;
  713. case GPBFieldMapKeySFixed32:
  714. return GPBDataTypeSFixed32;
  715. case GPBFieldMapKeySFixed64:
  716. return GPBDataTypeSFixed64;
  717. case GPBFieldMapKeyBool:
  718. return GPBDataTypeBool;
  719. case GPBFieldMapKeyString:
  720. return GPBDataTypeString;
  721. default:
  722. NSAssert(0, @"Not a map type");
  723. return GPBDataTypeInt32; // For lack of anything better.
  724. }
  725. }
  726. - (BOOL)isPackable {
  727. return (description_->flags & GPBFieldPacked) != 0;
  728. }
  729. - (BOOL)isValidEnumValue:(int32_t)value {
  730. NSAssert(description_->dataType == GPBDataTypeEnum, @"Field Must be of type GPBDataTypeEnum");
  731. return enumDescriptor_.enumVerifier(value);
  732. }
  733. - (GPBEnumDescriptor *)enumDescriptor {
  734. return enumDescriptor_;
  735. }
  736. - (GPBGenericValue)defaultValue {
  737. // Depends on the fact that defaultValue_ is initialized either to "0/nil" or
  738. // to an actual defaultValue in our initializer.
  739. GPBGenericValue value = defaultValue_;
  740. if (!(description_->flags & GPBFieldRepeated)) {
  741. // We special handle data and strings. If they are nil, we replace them
  742. // with empty string/empty data.
  743. GPBDataType type = description_->dataType;
  744. if (type == GPBDataTypeBytes && value.valueData == nil) {
  745. value.valueData = GPBEmptyNSData();
  746. } else if (type == GPBDataTypeString && value.valueString == nil) {
  747. value.valueString = @"";
  748. }
  749. }
  750. return value;
  751. }
  752. - (NSString *)textFormatName {
  753. if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
  754. NSValue *extraInfoValue = objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
  755. // Support can be left out at generation time.
  756. if (!extraInfoValue) {
  757. return nil;
  758. }
  759. const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
  760. return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self), self.name);
  761. }
  762. // The logic here has to match SetCommonFieldVariables() from
  763. // objectivec/field.cc in the proto compiler.
  764. NSString *name = self.name;
  765. NSUInteger len = [name length];
  766. // Remove the "_p" added to reserved names.
  767. if ([name hasSuffix:@"_p"]) {
  768. name = [name substringToIndex:(len - 2)];
  769. len = [name length];
  770. }
  771. // Remove "Array" from the end for repeated fields.
  772. if (((description_->flags & GPBFieldRepeated) != 0) && [name hasSuffix:@"Array"]) {
  773. name = [name substringToIndex:(len - 5)];
  774. len = [name length];
  775. }
  776. // Groups vs. other fields.
  777. if (description_->dataType == GPBDataTypeGroup) {
  778. // Just capitalize the first letter.
  779. unichar firstChar = [name characterAtIndex:0];
  780. if (firstChar >= 'a' && firstChar <= 'z') {
  781. NSString *firstCharString =
  782. [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
  783. NSString *result = [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
  784. withString:firstCharString];
  785. return result;
  786. }
  787. return name;
  788. } else {
  789. // Undo the CamelCase.
  790. NSMutableString *result = [NSMutableString stringWithCapacity:len];
  791. for (uint32_t i = 0; i < len; i++) {
  792. unichar c = [name characterAtIndex:i];
  793. if (c >= 'A' && c <= 'Z') {
  794. if (i > 0) {
  795. [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')];
  796. } else {
  797. [result appendFormat:@"%C", c];
  798. }
  799. } else {
  800. [result appendFormat:@"%C", c];
  801. }
  802. }
  803. return result;
  804. }
  805. }
  806. @end
  807. @implementation GPBEnumDescriptor {
  808. NSString *name_;
  809. // valueNames_ is a single c string with all of the value names appended
  810. // together, each null terminated. -calcValueNameOffsets fills in
  811. // nameOffsets_ with the offsets to allow quicker access to the individual
  812. // names.
  813. const char *valueNames_;
  814. const int32_t *values_;
  815. GPBEnumValidationFunc enumVerifier_;
  816. const uint8_t *extraTextFormatInfo_;
  817. uint32_t *nameOffsets_;
  818. uint32_t valueCount_;
  819. uint32_t flags_;
  820. }
  821. @synthesize name = name_;
  822. @synthesize enumVerifier = enumVerifier_;
  823. + (instancetype)allocDescriptorForName:(NSString *)name
  824. valueNames:(const char *)valueNames
  825. values:(const int32_t *)values
  826. count:(uint32_t)valueCount
  827. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  828. flags:(GPBEnumDescriptorInitializationFlags)flags {
  829. // Compute the unknown flags by this version of the runtime and then check the passed in flags
  830. // (from the generated code) to detect when sources from a newer version are being used with an
  831. // older runtime.
  832. GPBEnumDescriptorInitializationFlags unknownFlags =
  833. ~(GPBEnumDescriptorInitializationFlag_IsClosed);
  834. if ((flags & unknownFlags) != 0) {
  835. GPBRuntimeMatchFailure();
  836. }
  837. GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name
  838. valueNames:valueNames
  839. values:values
  840. count:valueCount
  841. enumVerifier:enumVerifier
  842. flags:flags];
  843. return descriptor;
  844. }
  845. + (instancetype)allocDescriptorForName:(NSString *)name
  846. valueNames:(const char *)valueNames
  847. values:(const int32_t *)values
  848. count:(uint32_t)valueCount
  849. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  850. flags:(GPBEnumDescriptorInitializationFlags)flags
  851. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  852. // Call the common case.
  853. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name
  854. valueNames:valueNames
  855. values:values
  856. count:valueCount
  857. enumVerifier:enumVerifier
  858. flags:flags];
  859. // Set the extra info.
  860. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo;
  861. return descriptor;
  862. }
  863. + (instancetype)allocDescriptorForName:(NSString *)name
  864. valueNames:(const char *)valueNames
  865. values:(const int32_t *)values
  866. count:(uint32_t)valueCount
  867. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  868. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30005,
  869. time_to_remove_this_old_version_shim);
  870. return [self allocDescriptorForName:name
  871. valueNames:valueNames
  872. values:values
  873. count:valueCount
  874. enumVerifier:enumVerifier
  875. flags:GPBEnumDescriptorInitializationFlag_None];
  876. }
  877. + (instancetype)allocDescriptorForName:(NSString *)name
  878. valueNames:(const char *)valueNames
  879. values:(const int32_t *)values
  880. count:(uint32_t)valueCount
  881. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  882. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  883. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30005,
  884. time_to_remove_this_old_version_shim);
  885. return [self allocDescriptorForName:name
  886. valueNames:valueNames
  887. values:values
  888. count:valueCount
  889. enumVerifier:enumVerifier
  890. flags:GPBEnumDescriptorInitializationFlag_None
  891. extraTextFormatInfo:extraTextFormatInfo];
  892. }
  893. - (instancetype)initWithName:(NSString *)name
  894. valueNames:(const char *)valueNames
  895. values:(const int32_t *)values
  896. count:(uint32_t)valueCount
  897. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  898. flags:(GPBEnumDescriptorInitializationFlags)flags {
  899. if ((self = [super init])) {
  900. name_ = [name copy];
  901. valueNames_ = valueNames;
  902. values_ = values;
  903. valueCount_ = valueCount;
  904. enumVerifier_ = enumVerifier;
  905. flags_ = flags;
  906. }
  907. return self;
  908. }
  909. - (void)dealloc {
  910. [name_ release];
  911. if (nameOffsets_) free(nameOffsets_);
  912. [super dealloc];
  913. }
  914. // No need to provide -hash/-isEqual: as the instances are singletons and the
  915. // default from NSObject is fine.
  916. - (instancetype)copyWithZone:(__unused NSZone *)zone {
  917. // Immutable.
  918. return [self retain];
  919. }
  920. - (BOOL)isClosed {
  921. return (flags_ & GPBEnumDescriptorInitializationFlag_IsClosed) != 0;
  922. }
  923. - (void)calcValueNameOffsets {
  924. @synchronized(self) {
  925. if (nameOffsets_ != NULL) {
  926. return;
  927. }
  928. uint32_t *offsets = malloc(valueCount_ * sizeof(uint32_t));
  929. if (!offsets) return;
  930. const char *scan = valueNames_;
  931. for (uint32_t i = 0; i < valueCount_; ++i) {
  932. offsets[i] = (uint32_t)(scan - valueNames_);
  933. while (*scan != '\0') ++scan;
  934. ++scan; // Step over the null.
  935. }
  936. nameOffsets_ = offsets;
  937. }
  938. }
  939. - (NSString *)enumNameForValue:(int32_t)number {
  940. for (uint32_t i = 0; i < valueCount_; ++i) {
  941. if (values_[i] == number) {
  942. return [self getEnumNameForIndex:i];
  943. }
  944. }
  945. return nil;
  946. }
  947. - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name {
  948. // Must have the prefix.
  949. NSUInteger prefixLen = name_.length + 1;
  950. if ((name.length <= prefixLen) || ![name hasPrefix:name_] ||
  951. ([name characterAtIndex:prefixLen - 1] != '_')) {
  952. return NO;
  953. }
  954. // Skip over the prefix.
  955. const char *nameAsCStr = [name UTF8String];
  956. nameAsCStr += prefixLen;
  957. [self calcValueNameOffsets];
  958. if (nameOffsets_ == NULL) return NO;
  959. // Find it.
  960. for (uint32_t i = 0; i < valueCount_; ++i) {
  961. const char *valueName = valueNames_ + nameOffsets_[i];
  962. if (strcmp(nameAsCStr, valueName) == 0) {
  963. if (outValue) {
  964. *outValue = values_[i];
  965. }
  966. return YES;
  967. }
  968. }
  969. return NO;
  970. }
  971. - (BOOL)getValue:(int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName {
  972. [self calcValueNameOffsets];
  973. if (nameOffsets_ == NULL) return NO;
  974. for (uint32_t i = 0; i < valueCount_; ++i) {
  975. NSString *valueTextFormatName = [self getEnumTextFormatNameForIndex:i];
  976. if ([valueTextFormatName isEqual:textFormatName]) {
  977. if (outValue) {
  978. *outValue = values_[i];
  979. }
  980. return YES;
  981. }
  982. }
  983. return NO;
  984. }
  985. - (NSString *)textFormatNameForValue:(int32_t)number {
  986. // Find the EnumValue descriptor and its index.
  987. BOOL foundIt = NO;
  988. uint32_t valueDescriptorIndex;
  989. for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_; ++valueDescriptorIndex) {
  990. if (values_[valueDescriptorIndex] == number) {
  991. foundIt = YES;
  992. break;
  993. }
  994. }
  995. if (!foundIt) {
  996. return nil;
  997. }
  998. return [self getEnumTextFormatNameForIndex:valueDescriptorIndex];
  999. }
  1000. - (uint32_t)enumNameCount {
  1001. return valueCount_;
  1002. }
  1003. - (NSString *)getEnumNameForIndex:(uint32_t)index {
  1004. [self calcValueNameOffsets];
  1005. if (nameOffsets_ == NULL) return nil;
  1006. if (index >= valueCount_) {
  1007. return nil;
  1008. }
  1009. const char *valueName = valueNames_ + nameOffsets_[index];
  1010. NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName];
  1011. return fullName;
  1012. }
  1013. - (NSString *)getEnumTextFormatNameForIndex:(uint32_t)index {
  1014. [self calcValueNameOffsets];
  1015. if (nameOffsets_ == NULL) return nil;
  1016. if (index >= valueCount_) {
  1017. return nil;
  1018. }
  1019. NSString *result = nil;
  1020. // Naming adds an underscore between enum name and value name, skip that also.
  1021. const char *valueName = valueNames_ + nameOffsets_[index];
  1022. NSString *shortName = @(valueName);
  1023. // See if it is in the map of special format handling.
  1024. if (extraTextFormatInfo_) {
  1025. result = GPBDecodeTextFormatName(extraTextFormatInfo_, (int32_t)index, shortName);
  1026. }
  1027. // Logic here needs to match what objectivec/enum.cc does in the proto
  1028. // compiler.
  1029. if (result == nil) {
  1030. NSUInteger len = [shortName length];
  1031. NSMutableString *worker = [NSMutableString stringWithCapacity:len];
  1032. for (NSUInteger i = 0; i < len; i++) {
  1033. unichar c = [shortName characterAtIndex:i];
  1034. if (i > 0 && c >= 'A' && c <= 'Z') {
  1035. [worker appendString:@"_"];
  1036. }
  1037. [worker appendFormat:@"%c", toupper((char)c)];
  1038. }
  1039. result = worker;
  1040. }
  1041. return result;
  1042. }
  1043. @end
  1044. @implementation GPBExtensionDescriptor {
  1045. GPBGenericValue defaultValue_;
  1046. }
  1047. - (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc
  1048. usesClassRefs:(BOOL)usesClassRefs {
  1049. // Compute the unknown options by this version of the runtime and then check the passed in
  1050. // descriptor's options (from the generated code) to detect when sources from a newer version are
  1051. // being used with an older runtime.
  1052. GPBExtensionOptions unknownOptions =
  1053. ~(GPBExtensionRepeated | GPBExtensionPacked | GPBExtensionSetWireFormat);
  1054. if ((desc->options & unknownOptions) != 0) {
  1055. GPBRuntimeMatchFailure();
  1056. }
  1057. #if defined(DEBUG) && DEBUG
  1058. NSAssert(usesClassRefs, @"Internal error: all extensions should have class refs");
  1059. #endif
  1060. if ((self = [super init])) {
  1061. description_ = desc;
  1062. GPBDataType type = description_->dataType;
  1063. if (type == GPBDataTypeBytes) {
  1064. // Data stored as a length prefixed c-string in descriptor records.
  1065. const uint8_t *bytes = (const uint8_t *)description_->defaultValue.valueData;
  1066. if (bytes) {
  1067. uint32_t length;
  1068. memcpy(&length, bytes, sizeof(length));
  1069. // The length is stored in network byte order.
  1070. length = ntohl(length);
  1071. bytes += sizeof(length);
  1072. defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length];
  1073. }
  1074. } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) {
  1075. // The default is looked up in -defaultValue instead since extensions
  1076. // aren't common, we avoid the hit startup hit and it avoids initialization
  1077. // order issues.
  1078. } else {
  1079. defaultValue_ = description_->defaultValue;
  1080. }
  1081. }
  1082. return self;
  1083. }
  1084. - (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc {
  1085. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION <= 30003,
  1086. time_to_remove_this_old_version_shim);
  1087. const char *className = desc->messageOrGroupClass.name;
  1088. if (className) {
  1089. Class clazz = objc_lookUpClass(className);
  1090. NSAssert(clazz != Nil, @"Class %s not defined", className);
  1091. desc->messageOrGroupClass.clazz = clazz;
  1092. }
  1093. const char *extendedClassName = desc->extendedClass.name;
  1094. if (extendedClassName) {
  1095. Class clazz = objc_lookUpClass(extendedClassName);
  1096. NSAssert(clazz, @"Class %s not defined", extendedClassName);
  1097. desc->extendedClass.clazz = clazz;
  1098. }
  1099. return [self initWithExtensionDescription:desc usesClassRefs:YES];
  1100. }
  1101. - (void)dealloc {
  1102. if ((description_->dataType == GPBDataTypeBytes) && !GPBExtensionIsRepeated(description_)) {
  1103. [defaultValue_.valueData release];
  1104. }
  1105. [super dealloc];
  1106. }
  1107. // No need to provide -hash/-isEqual: as the instances are singletons and the
  1108. // default from NSObject is fine.
  1109. - (instancetype)copyWithZone:(__unused NSZone *)zone {
  1110. // Immutable.
  1111. return [self retain];
  1112. }
  1113. - (NSString *)singletonName {
  1114. return (NSString *_Nonnull)@(description_->singletonName);
  1115. }
  1116. - (const char *)singletonNameC {
  1117. return description_->singletonName;
  1118. }
  1119. - (uint32_t)fieldNumber {
  1120. return description_->fieldNumber;
  1121. }
  1122. - (GPBDataType)dataType {
  1123. return description_->dataType;
  1124. }
  1125. - (GPBWireFormat)wireType {
  1126. return GPBWireFormatForType(description_->dataType, GPBExtensionIsPacked(description_));
  1127. }
  1128. - (GPBWireFormat)alternateWireType {
  1129. NSAssert(GPBExtensionIsRepeated(description_), @"Only valid on repeated extensions");
  1130. return GPBWireFormatForType(description_->dataType, !GPBExtensionIsPacked(description_));
  1131. }
  1132. - (BOOL)isRepeated {
  1133. return GPBExtensionIsRepeated(description_);
  1134. }
  1135. - (BOOL)isPackable {
  1136. return GPBExtensionIsPacked(description_);
  1137. }
  1138. - (Class)msgClass {
  1139. return description_->messageOrGroupClass.clazz;
  1140. }
  1141. - (Class)containingMessageClass {
  1142. return description_->extendedClass.clazz;
  1143. }
  1144. - (GPBEnumDescriptor *)enumDescriptor {
  1145. if (description_->dataType == GPBDataTypeEnum) {
  1146. GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc();
  1147. return enumDescriptor;
  1148. }
  1149. return nil;
  1150. }
  1151. - (id)defaultValue {
  1152. if (GPBExtensionIsRepeated(description_)) {
  1153. return nil;
  1154. }
  1155. switch (description_->dataType) {
  1156. case GPBDataTypeBool:
  1157. return @(defaultValue_.valueBool);
  1158. case GPBDataTypeFloat:
  1159. return @(defaultValue_.valueFloat);
  1160. case GPBDataTypeDouble:
  1161. return @(defaultValue_.valueDouble);
  1162. case GPBDataTypeInt32:
  1163. case GPBDataTypeSInt32:
  1164. case GPBDataTypeEnum:
  1165. case GPBDataTypeSFixed32:
  1166. return @(defaultValue_.valueInt32);
  1167. case GPBDataTypeInt64:
  1168. case GPBDataTypeSInt64:
  1169. case GPBDataTypeSFixed64:
  1170. return @(defaultValue_.valueInt64);
  1171. case GPBDataTypeUInt32:
  1172. case GPBDataTypeFixed32:
  1173. return @(defaultValue_.valueUInt32);
  1174. case GPBDataTypeUInt64:
  1175. case GPBDataTypeFixed64:
  1176. return @(defaultValue_.valueUInt64);
  1177. case GPBDataTypeBytes:
  1178. // Like message fields, the default is zero length data.
  1179. return (defaultValue_.valueData ? defaultValue_.valueData : GPBEmptyNSData());
  1180. case GPBDataTypeString:
  1181. // Like message fields, the default is zero length string.
  1182. return (defaultValue_.valueString ? defaultValue_.valueString : @"");
  1183. case GPBDataTypeGroup:
  1184. case GPBDataTypeMessage:
  1185. return nil;
  1186. }
  1187. }
  1188. - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other {
  1189. int32_t selfNumber = description_->fieldNumber;
  1190. int32_t otherNumber = other->description_->fieldNumber;
  1191. if (selfNumber < otherNumber) {
  1192. return NSOrderedAscending;
  1193. } else if (selfNumber == otherNumber) {
  1194. return NSOrderedSame;
  1195. } else {
  1196. return NSOrderedDescending;
  1197. }
  1198. }
  1199. @end
  1200. #pragma clang diagnostic pop