forked from tomaz/appledoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGBObjectiveCParser.m
793 lines (669 loc) · 29.9 KB
/
GBObjectiveCParser.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//
// GBObjectiveCParser.m
// appledoc
//
// Created by Tomaz Kragelj on 25.7.10.
// Copyright (C) 2010, Gentle Bytes. All rights reserved.
//
#import "RegexKitLite.h"
#import "ParseKit.h"
#import "PKToken+GBToken.h"
#import "GBTokenizer.h"
#import "GBStore.h"
#import "GBApplicationSettingsProvider.h"
#import "GBDataObjects.h"
#import "GBObjectiveCParser.h"
@interface GBObjectiveCParser ()
- (PKTokenizer *)tokenizerWithInputString:(NSString *)input;
- (void)updateLastComment:(GBComment **)comment sectionComment:(GBComment **)sectionComment sectionName:(NSString **)sectionName;
@property (retain) GBTokenizer *tokenizer;
@property (retain) GBStore *store;
@property (retain) GBApplicationSettingsProvider *settings;
@property (assign) BOOL includeInOutput;
@property (assign) BOOL propertyAfterPragma;
@end
@interface GBObjectiveCParser (DefinitionParsing)
- (void)matchClassDefinition;
- (void)matchCategoryDefinition;
- (void)matchExtensionDefinition;
- (void)matchProtocolDefinition;
- (void)matchSuperclassForClass:(GBClassData *)class;
- (void)matchAdoptedProtocolForProvider:(GBAdoptedProtocolsProvider *)provider;
- (void)matchIvarsForProvider:(GBIvarsProvider *)provider;
- (void)matchMethodDefinitionsForProvider:(GBMethodsProvider *)provider defaultsRequired:(BOOL)required;
- (BOOL)matchMethodDefinitionForProvider:(GBMethodsProvider *)provider required:(BOOL)required;
- (BOOL)matchPropertyDefinitionForProvider:(GBMethodsProvider *)provider required:(BOOL)required;
@end
@interface GBObjectiveCParser (DeclarationsParsing)
- (void)matchClassDeclaration;
- (void)matchCategoryDeclaration;
- (void)matchMethodDeclarationsForProvider:(GBMethodsProvider *)provider defaultsRequired:(BOOL)required;
- (BOOL)matchMethodDeclarationForProvider:(GBMethodsProvider *)provider required:(BOOL)required;
- (void)consumeMethodBody;
@end
@interface GBObjectiveCParser (CommonParsing)
- (BOOL)matchNextObject;
- (BOOL)matchObjectDefinition;
- (BOOL)matchObjectDeclaration;
- (BOOL)matchTypedefEnumDefinition;
- (BOOL)matchMethodDataForProvider:(GBMethodsProvider *)provider from:(NSString *)start to:(NSString *)end required:(BOOL)required;
- (void)registerComment:(GBComment *)comment toObject:(GBModelBase *)object;
- (void)registerLastCommentToObject:(GBModelBase *)object;
- (void)registerSourceInfoFromCurrentTokenToObject:(GBModelBase *)object;
- (NSString *)sectionNameFromComment:(GBComment *)comment;
@end
#pragma mark -
@implementation GBObjectiveCParser
#pragma mark Initialization & disposal
+ (id)parserWithSettingsProvider:(id)settingsProvider {
return [[[self alloc] initWithSettingsProvider:settingsProvider] autorelease];
}
- (id)initWithSettingsProvider:(id)settingsProvider {
NSParameterAssert(settingsProvider != nil);
GBLogDebug(@"Initializing objective-c parser with settings provider %@...", settingsProvider);
self = [super init];
if (self) {
self.settings = settingsProvider;
}
return self;
}
#pragma mark Parsing handling
- (void)parseObjectsFromString:(NSString *)input sourceFile:(NSString *)filename toStore:(id)aStore {
NSParameterAssert(input != nil);
NSParameterAssert(filename != nil);
NSParameterAssert([filename length] > 0);
NSParameterAssert(aStore != nil);
GBLogDebug(@"Parsing objective-c objects...");
self.store = aStore;
self.tokenizer = [GBTokenizer tokenizerWithSource:[self tokenizerWithInputString:input] filename:filename settings:self.settings];
self.includeInOutput = YES;
self.propertyAfterPragma = NO;
for (NSString *excludeOutputPath in self.settings.excludeOutputPaths) {
if ([filename isEqualToString:excludeOutputPath]) {
self.includeInOutput = NO;
break;
}
NSString *excludeOutputDir = excludeOutputPath;
if (![excludeOutputDir hasSuffix:@"/"])
excludeOutputDir = [NSString stringWithFormat:@"%@/", excludeOutputDir];
if ([filename hasPrefix:excludeOutputDir]) {
self.includeInOutput = NO;
break;
}
}
while (![self.tokenizer eof]) {
if (![self matchNextObject]) {
[self.tokenizer consume:1];
}
}
}
- (PKTokenizer *)tokenizerWithInputString:(NSString *)input {
PKTokenizer *result = [PKTokenizer tokenizerWithString:input];
[result setTokenizerState:result.wordState from:'_' to:'_']; // Allow words to start with _
[result.symbolState add:@"..."]; // Allow ... as single token
return result;
}
#pragma mark Helper methods
- (void)updateLastComment:(GBComment **)comment sectionComment:(GBComment **)sectionComment sectionName:(NSString **)sectionName {
if (comment) *comment = [self.tokenizer lastComment];
if (sectionComment) {
*sectionComment = [self.tokenizer previousComment];
if (sectionName) *sectionName = [self sectionNameFromComment:*sectionComment];
}
}
#pragma mark Properties
@synthesize tokenizer;
@synthesize settings;
@synthesize store;
@synthesize includeInOutput;
@synthesize propertyAfterPragma;
@end
#pragma mark -
@implementation GBObjectiveCParser (DefinitionParsing)
- (void)matchClassDefinition {
// @interface CLASSNAME
NSString *className = [[self.tokenizer lookahead:1] stringValue];
GBClassData *class = [GBClassData classDataWithName:className];
class.includeInOutput = self.includeInOutput;
[self registerSourceInfoFromCurrentTokenToObject:class];
GBLogDebug(@"Matched %@ class definition at line %lu.", className, class.prefferedSourceInfo.lineNumber);
[self registerLastCommentToObject:class];
[self.tokenizer consume:2];
[self matchSuperclassForClass:class];
[self matchAdoptedProtocolForProvider:class.adoptedProtocols];
[self matchIvarsForProvider:class.ivars];
GBMethodsProvider *methodsProvider = class.methods;
methodsProvider.useAlphabeticalOrder = !self.settings.useCodeOrder;
[self matchMethodDefinitionsForProvider:methodsProvider defaultsRequired:NO];
[self.store registerClass:class];
}
- (void)matchCategoryDefinition {
// @interface CLASSNAME ( CATEGORYNAME )
NSString *className = [[self.tokenizer lookahead:1] stringValue];
NSString *categoryName = [[self.tokenizer lookahead:3] stringValue];
GBCategoryData *category = [GBCategoryData categoryDataWithName:categoryName className:className];
category.includeInOutput = self.includeInOutput;
[self registerSourceInfoFromCurrentTokenToObject:category];
GBLogVerbose(@"Matched %@(%@) category definition at line %lu.", className, categoryName, category.prefferedSourceInfo.lineNumber);
[self registerLastCommentToObject:category];
[self.tokenizer consume:5];
[self matchAdoptedProtocolForProvider:category.adoptedProtocols];
GBMethodsProvider *methodsProvider = category.methods;
methodsProvider.useAlphabeticalOrder = !self.settings.useCodeOrder;
[self matchMethodDefinitionsForProvider:methodsProvider defaultsRequired:NO];
[self.store registerCategory:category];
}
- (void)matchExtensionDefinition {
// @interface CLASSNAME ( )
NSString *className = [[self.tokenizer lookahead:1] stringValue];
GBCategoryData *extension = [GBCategoryData categoryDataWithName:nil className:className];
extension.includeInOutput = self.includeInOutput;
GBLogVerbose(@"Matched %@() extension definition at line %lu.", className, extension.prefferedSourceInfo.lineNumber);
[self registerSourceInfoFromCurrentTokenToObject:extension];
[self registerLastCommentToObject:extension];
[self.tokenizer consume:4];
[self matchAdoptedProtocolForProvider:extension.adoptedProtocols];
GBMethodsProvider *methodsProvider = extension.methods;
methodsProvider.useAlphabeticalOrder = !self.settings.useCodeOrder;
[self matchMethodDefinitionsForProvider:methodsProvider defaultsRequired:NO];
[self.store registerCategory:extension];
}
- (void)matchProtocolDefinition {
// @protocol PROTOCOLNAME
NSString *protocolName = [[self.tokenizer lookahead:1] stringValue];
GBProtocolData *protocol = [GBProtocolData protocolDataWithName:protocolName];
protocol.includeInOutput = self.includeInOutput;
GBLogVerbose(@"Matched %@ protocol definition at line %lu.", protocolName, protocol.prefferedSourceInfo.lineNumber);
[self registerSourceInfoFromCurrentTokenToObject:protocol];
[self registerLastCommentToObject:protocol];
[self.tokenizer consume:2];
[self matchAdoptedProtocolForProvider:protocol.adoptedProtocols];
GBMethodsProvider *methodsProvider = protocol.methods;
methodsProvider.useAlphabeticalOrder = !self.settings.useCodeOrder;
[self matchMethodDefinitionsForProvider:methodsProvider defaultsRequired:YES];
[self.store registerProtocol:protocol];
}
- (void)matchSuperclassForClass:(GBClassData *)class {
if (![[self.tokenizer currentToken] matches:@":"]) return;
class.nameOfSuperclass = [[self.tokenizer lookahead:1] stringValue];
GBLogDebug(@"Matched superclass %@.", class.nameOfSuperclass);
[self.tokenizer consume:2];
}
- (void)matchAdoptedProtocolForProvider:(GBAdoptedProtocolsProvider *)provider {
[self.tokenizer consumeFrom:@"<" to:@">" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if ([token matches:@","]) return;
GBProtocolData *protocol = [[GBProtocolData alloc] initWithName:[token stringValue]];
GBLogDebug(@"Matched adopted protocol %@.", protocol);
[provider registerProtocol:protocol];
}];
}
- (void)matchIvarsForProvider:(GBIvarsProvider *)provider {
[self.tokenizer consumeFrom:@"{" to:@"}" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
return; // Ignore all ivars, no need to document these(?)
}];
}
- (void)matchMethodDefinitionsForProvider:(GBMethodsProvider *)provider defaultsRequired:(BOOL)required {
__block BOOL isRequired = required;
[self.tokenizer consumeTo:@"@end" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if ([token matches:@"@required"]) {
isRequired = YES;
} else if ([token matches:@"@optional"]) {
isRequired = NO;
} else if ([self matchMethodDefinitionForProvider:provider required:isRequired]) {
*consume = NO;
} else if ([self matchPropertyDefinitionForProvider:provider required:isRequired]) {
*consume = NO;
}
}];
}
- (BOOL)matchMethodDefinitionForProvider:(GBMethodsProvider *)provider required:(BOOL)required {
if ([self matchMethodDataForProvider:provider from:@"+" to:@";" required:required]) return YES;
if ([self matchMethodDataForProvider:provider from:@"-" to:@";" required:required]) return YES;
return NO;
}
- (BOOL)matchPropertyDefinitionForProvider:(GBMethodsProvider *)provider required:(BOOL)required {
__block GBComment *comment;
__block GBComment *sectionComment;
__block NSString *sectionName;
__block BOOL firstToken = YES;
__block BOOL result = NO;
__block GBSourceInfo *filedata = nil;
[self updateLastComment:&comment sectionComment:§ionComment sectionName:§ionName];
[self.tokenizer consumeFrom:@"@property" to:@";" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if (!filedata) filedata = [self.tokenizer sourceInfoForToken:token];
if (firstToken) {
if (!self.propertyAfterPragma) [self.tokenizer resetComments];
self.propertyAfterPragma = NO;
firstToken = NO;
}
// Get attributes.
NSMutableArray *propertyAttributes = [NSMutableArray array];
[self.tokenizer consumeFrom:@"(" to:@")" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if ([token matches:@","]) return;
[propertyAttributes addObject:[token stringValue]];
}];
// Get property types and name. Handle block types properly!
NSMutableArray *propertyComponents = [NSMutableArray array];
__block BOOL parseAttribute = NO;
__block NSUInteger parenthesisDepth = 0;
[self.tokenizer consumeTo:@";" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if ([token matches:@"__attribute__"] || [token matches:@"DEPRECATED_ATTRIBUTE"]) {
parseAttribute = YES;
parenthesisDepth = 0;
} else if (parseAttribute) {
if ([token matches:@"("]) {
parenthesisDepth++;
} else if ([token matches:@")"]) {
parenthesisDepth--;
if (parenthesisDepth == 0) parseAttribute = NO;
}
} else {
[propertyComponents addObject:[token stringValue]];
}
}];
// Register property.
GBMethodData *propertyData = [GBMethodData propertyDataWithAttributes:propertyAttributes components:propertyComponents];
[propertyData registerSourceInfo:filedata];
GBLogDebug(@"Matched property definition %@ at line %lu.", propertyData, propertyData.prefferedSourceInfo.lineNumber);
[self registerComment:comment toObject:propertyData];
[propertyData setIsRequired:required];
[provider registerSectionIfNameIsValid:sectionName];
[provider registerMethod:propertyData];
*consume = NO;
*stop = YES;
result = YES;
}];
return result;
}
@end
#pragma mark -
@implementation GBObjectiveCParser (DeclarationsParsing)
- (void)matchClassDeclaration {
// @implementation CLASSNAME
NSString *className = [[self.tokenizer lookahead:1] stringValue];
GBClassData *class = [GBClassData classDataWithName:className];
class.includeInOutput = self.includeInOutput;
[self registerSourceInfoFromCurrentTokenToObject:class];
GBLogVerbose(@"Matched %@ class declaration at line %lu.", className, class.prefferedSourceInfo.lineNumber);
[self registerLastCommentToObject:class];
[self.tokenizer consume:2];
GBMethodsProvider *methodsProvider = class.methods;
methodsProvider.useAlphabeticalOrder = !self.settings.useCodeOrder;
[self matchMethodDeclarationsForProvider:class.methods defaultsRequired:NO];
[self.store registerClass:class];
}
- (void)matchCategoryDeclaration {
// @implementation CLASSNAME ( CATEGORYNAME )
NSString *className = [[self.tokenizer lookahead:1] stringValue];
NSString *categoryName = [[self.tokenizer lookahead:3] stringValue];
GBCategoryData *category = [GBCategoryData categoryDataWithName:categoryName className:className];
category.includeInOutput = self.includeInOutput;
[self registerSourceInfoFromCurrentTokenToObject:category];
GBLogVerbose(@"Matched %@(%@) category declaration at line %lu.", className, categoryName, category.prefferedSourceInfo.lineNumber);
[self registerLastCommentToObject:category];
[self.tokenizer consume:5];
GBMethodsProvider *methodsProvider = category.methods;
methodsProvider.useAlphabeticalOrder = !self.settings.useCodeOrder;
[self matchMethodDeclarationsForProvider:methodsProvider defaultsRequired:NO];
[self.store registerCategory:category];
}
- (void)matchMethodDeclarationsForProvider:(GBMethodsProvider *)provider defaultsRequired:(BOOL)required {
__block BOOL isRequired = required;
[self.tokenizer consumeTo:@"@end" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if ([self matchMethodDeclarationForProvider:provider required:isRequired]) {
*consume = NO;
}
}];
}
- (BOOL)matchMethodDeclarationForProvider:(GBMethodsProvider *)provider required:(BOOL)required {
if ([self matchMethodDataForProvider:provider from:@"+" to:@"{" required:required]) {
[self consumeMethodBody];
return YES;
}
if ([self matchMethodDataForProvider:provider from:@"-" to:@"{" required:required]) {
[self consumeMethodBody];
return YES;
}
return NO;
}
- (void)consumeMethodBody {
// This method assumes we're currently pointing to the first token after method's opening brace!
__block NSUInteger braceLevel = 1;
[self.tokenizer consumeTo:@"@end" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if ([token matches:@"{"]) {
braceLevel++;
return;
}
if ([token matches:@"}"]) {
if (--braceLevel == 0) {
*consume = NO;
*stop = YES;
}
return;
}
}];
}
@end
#pragma mark -
@implementation GBObjectiveCParser (CommonParsing)
- (BOOL)matchNextObject {
if ([self matchObjectDefinition]) return YES;
if ([self matchObjectDeclaration]) return YES;
if ([self matchTypedefEnumDefinition]) return YES;
return NO;
}
- (BOOL)matchTypedefEnumDefinition {
BOOL isTypeDef = [[self.tokenizer currentToken] matches:@"typedef"];
BOOL isTypeDefEnum = [[self.tokenizer lookahead:1] matches:@"NS_ENUM"];
BOOL isTypeDefOptions = [[self.tokenizer lookahead:1] matches:@"NS_OPTIONS"];
BOOL hasOpenBracket = [[self.tokenizer lookahead:2] matches:@"("];
//ONLY SUPPORTED ARE typedef enum { } name; because that is the only way to bind the name to the enum values.
if(!isTypeDef)
{
return NO;
}
if((isTypeDefEnum || isTypeDefOptions) && hasOpenBracket)
{
[self.tokenizer consume:3]; //consume 'typedef' 'NS_ENUM' and '('
//get the enum type
NSString *typedefType = [[self.tokenizer currentToken] stringValue];
[self.tokenizer consume:1];
//consume ','
[self.tokenizer consume:1];
//get the typename
NSString *typedefName = [[self.tokenizer currentToken] stringValue];
[self.tokenizer consume:1];
//consume ')'
[self.tokenizer consume:1];
GBSourceInfo *startInfo = [tokenizer sourceInfoForCurrentToken];
GBComment *lastComment = [tokenizer lastComment];
GBLogVerbose(@"Matched %@ typedef enum definition at line %lu.", typedefName, startInfo.lineNumber);
GBTypedefEnumData *newEnum = [GBTypedefEnumData typedefEnumWithName:typedefName];
newEnum.includeInOutput = self.includeInOutput;
newEnum.enumPrimitive = typedefType;
newEnum.isOptions = isTypeDefOptions;
[newEnum registerSourceInfo:startInfo];
[self registerComment:lastComment toObject:newEnum];
[self.tokenizer resetComments];
//[self.tokenizer consume:1];
[self.tokenizer consumeFrom:@"{" to:@"}" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop)
{
/* ALWAYS start with the name of the Constant */
GBEnumConstantData *newConstant = [GBEnumConstantData constantWithName:[token stringValue]];
GBSourceInfo *filedata = [tokenizer sourceInfoForToken:token];
[newConstant registerSourceInfo:filedata];
[newConstant setParentObject:newEnum];
[self registerLastCommentToObject:newConstant];
[self.tokenizer consume:1];
[self.tokenizer resetComments];
[self consumeMacro];
if([[self.tokenizer currentToken] matches:@"="])
{
[self.tokenizer consume:1];
//collect the stringvalues until a ',' is detected.
NSMutableArray *values = [NSMutableArray array];
while(![[tokenizer currentToken] matches:@","] && ![[tokenizer currentToken] matches:@"}"])
{
if(![self consumeMacro])
{
[values addObject:[[tokenizer currentToken] stringValue]];
[tokenizer consume:1];
}
}
NSString *value = [values componentsJoinedByString:@" "];
[newConstant setAssignedValue:value];
}
if([[self.tokenizer currentToken] matches:@","])
{
[tokenizer consume:1];
}
*consume = NO;
[newEnum.constants registerConstant:newConstant];
}];
//if there is a macro, consume it.
[self consumeMacro];
//consume ;
[self.tokenizer consume:1];
[self.store registerTypedefEnum:newEnum];
return YES;
}
else
{
BOOL isRegularEnum = [[self.tokenizer lookahead:1] matches:@"enum"];
BOOL isCurlyBrace = [[self.tokenizer lookahead:2] matches:@"{"];
if(isRegularEnum && isCurlyBrace)
{
GBSourceInfo *startInfo = [tokenizer sourceInfoForCurrentToken];
GBLogXWarn(startInfo, @"unsupported typedef enum at %@!", startInfo);
}
}
return NO;
}
-(bool)isTokenUppercaseOnly:(NSString *)token
{
return [token isEqualToString:[token uppercaseString]];
}
-(bool)consumeMacro
{
//Eat away and MACRO
if( ![[self.tokenizer currentToken] matches:@"="]
&& ![[self.tokenizer currentToken] matches:@"}"]
&& ![[self.tokenizer currentToken] matches:@","]
&& [[self.tokenizer currentToken] isWord]
&& [self isTokenUppercaseOnly:[[self.tokenizer currentToken] stringValue]])
{
[self.tokenizer consume:1];
//now a macro may come with bracketed arguments.
if([[self.tokenizer currentToken] matches:@"("])
{
[self.tokenizer consumeTo:@")" usingBlock:nil];
}
return YES;
}
return NO;
}
- (BOOL)matchObjectDefinition {
// Get data needed for distinguishing between class, category and extension definition.
BOOL isInterface = [[self.tokenizer currentToken] matches:@"@interface"];
BOOL isOpenParenthesis = [[self.tokenizer lookahead:2] matches:@"("];
BOOL isCloseParenthesis = [[self.tokenizer lookahead:3] matches:@")"];
// Found class extension definition.
if (isInterface && isOpenParenthesis && isCloseParenthesis) {
[self matchExtensionDefinition];
return YES;
}
// Found category definition.
if (isInterface && isOpenParenthesis) {
[self matchCategoryDefinition];
return YES;
}
// Found class definition.
if (isInterface) {
[self matchClassDefinition];
return YES;
}
// Get data needed for distinguishing between protocol definition and directive.
BOOL isProtocol = [[self.tokenizer currentToken] matches:@"@protocol"];
BOOL isDirective = [[self.tokenizer lookahead:2] matches:@";"] || [[self.tokenizer lookahead:2] matches:@","];
// Found protocol definition.
if (isProtocol && !isDirective) {
[self matchProtocolDefinition];
return YES;
}
return NO;
}
- (BOOL)matchObjectDeclaration {
// Get data needed for distinguishing between class and category declaration.
BOOL isImplementation = [[self.tokenizer currentToken] matches:@"@implementation"];
BOOL isOpenParenthesis = [[self.tokenizer lookahead:2] matches:@"("];
// Found category declaration.
if (isImplementation && isOpenParenthesis) {
[self matchCategoryDeclaration];
return YES;
}
// Found class declaration.
if (isImplementation) {
[self matchClassDeclaration];
return YES;
}
return NO;
}
- (BOOL)matchMethodDataForProvider:(GBMethodsProvider *)provider from:(NSString *)start to:(NSString *)end required:(BOOL)required {
// This method only matches class or instance methods, not properties!
// - (void)assertIvar:(GBIvarData *)ivar matches:(NSString *)firstType,... NS_REQUIRES_NIL_TERMINATION;
__block GBComment *comment;
__block GBComment *sectionComment;
__block NSString *sectionName;
__block BOOL assertMethod = YES;
__block BOOL result = NO;
__block GBSourceInfo *filedata = nil;
__block GBMethodType methodType = [start isEqualToString:@"-"] ? GBMethodTypeInstance : GBMethodTypeClass;
[self updateLastComment:&comment sectionComment:§ionComment sectionName:§ionName];
[self.tokenizer consumeFrom:start to:end usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
// In order to provide at least some assurance the minus or plus actually starts the method, we validate next token is opening parenthesis. Very simple so might need some refinement... Note that we skip subsequent - or + tokens so that we can handle stuff like '#pragma mark -' gracefully (note that we also do it for + although that shouldn't be necessary, but feels safer).
if (assertMethod) {
if ([token matches:@"-"] || [token matches:@"+"]) {
[self updateLastComment:&comment sectionComment:§ionComment sectionName:§ionName];
methodType = [token matches:@"-"] ? GBMethodTypeInstance : GBMethodTypeClass;
return;
}
if (![token matches:@"("]) {
if ([token matches:@"@property"]) {
self.propertyAfterPragma = YES;
*consume = NO;
*stop = YES;
return;
}
[self.tokenizer resetComments];
*consume = NO;
*stop = YES;
return;
}
assertMethod = NO;
}
// Prepare source information and reset comments; we alreay read the values so as long as we have found a method, we should reset the comments to prepare ground for next methods. This is needed due to the way this method works - it actually ends by jumping to the first token after the given end symbol, which effectively positions tokenizer to the first token of the following method. Therefore it already consumes any comment preceeding the method. So we can't reset AFTER finished parsing, but rather before! Note that we should only do it once...
if (!filedata) {
filedata = [self.tokenizer sourceInfoForToken:token];
[self.tokenizer resetComments];
}
// Get result types.
NSMutableArray *methodResult = [NSMutableArray array];
[self.tokenizer consumeFrom:@"(" to:@")" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
[methodResult addObject:[token stringValue]];
}];
// Get all arguments. Note that we ignore semicolons which may "happen" in declaration before method opening brace!
__block BOOL parseAttribute = NO;
__block NSUInteger parenthesisDepth = 0;
__block NSMutableArray *methodArgs = [NSMutableArray array];
[self.tokenizer consumeTo:end usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
if ([token matches:@"__attribute__"] || [token matches:@"DEPRECATED_ATTRIBUTE"]) {
parseAttribute = YES;
parenthesisDepth = 0;
return;
}
if (parseAttribute) {
if ([token matches:@"("]) {
parenthesisDepth++;
} else if ([token matches:@")"]) {
parenthesisDepth--;
if (parenthesisDepth == 0) parseAttribute = NO;
}
return;
}
// If we receive semicolon, ignore it - this works for both - definition and declaration!
if ([token matches:@";"]) {
*stop = YES;
return;
}
// Get argument name.
NSString *argumentName = [token stringValue];
[self.tokenizer consume:1];
__block NSString *argumentVar = nil;
__block NSMutableArray *argumentTypes = [NSMutableArray array];
__block NSMutableArray *terminationMacros = [NSMutableArray array];
__block BOOL variableArg = NO;
if ([[self.tokenizer currentToken] matches:@":"]) {
[self.tokenizer consume:1];
// Get argument types.
[self.tokenizer consumeFrom:@"(" to:@")" usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
[argumentTypes addObject:[token stringValue]];
}];
// Get argument variable name.
if (![[self.tokenizer currentToken] matches:end]) {
argumentVar = [[self.tokenizer currentToken] stringValue];
[self.tokenizer consume:1];
}
// If we have variable args block following, consume the rest of the tokens to get optional termination macros.
if ([[self.tokenizer lookahead:0] matches:@","] && [[self.tokenizer lookahead:1] matches:@"..."]) {
variableArg = YES;
[self.tokenizer consume:2];
[self.tokenizer consumeTo:end usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
[terminationMacros addObject:[token stringValue]];
}];
*stop = YES; // Ignore the rest of parameters as vararg is the last and above block consumed end token which would confuse above block!
} else {
// If we have no more colon before end, consume the rest of the tokens to get optional termination macros.
__block BOOL hasColon = NO;
[self.tokenizer lookaheadTo:end usingBlock:^(PKToken *token, BOOL *stop) {
if ([token matches:@":"]) {
hasColon = YES;
*stop = YES;
}
}];
if (!hasColon) {
[self.tokenizer consumeTo:end usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
[terminationMacros addObject:[token stringValue]];
}];
*stop = YES; // Ignore the rest of parameters
}
}
if (terminationMacros.count == 0) {
terminationMacros = nil;
}
} else {
// remaining tokens are termination macros
[self.tokenizer consumeTo:end usingBlock:^(PKToken *token, BOOL *consume, BOOL *stop) {
[terminationMacros addObject:[token stringValue]];
}];
*stop = YES; // Ignore the rest of parameters
}
GBMethodArgument *argument = [GBMethodArgument methodArgumentWithName:argumentName types:argumentTypes var:argumentVar variableArg:variableArg terminationMacros:terminationMacros];
[methodArgs addObject:argument];
*consume = NO;
}];
// Create method instance and register it.
GBMethodData *methodData = [GBMethodData methodDataWithType:methodType result:methodResult arguments:methodArgs];
[methodData registerSourceInfo:filedata];
GBLogDebug(@"Matched method %@%@ at line %lu.", start, methodData, methodData.prefferedSourceInfo.lineNumber);
[self registerComment:comment toObject:methodData];
[methodData setIsRequired:required];
[provider registerSectionIfNameIsValid:sectionName];
[provider registerMethod:methodData];
*consume = NO;
*stop = YES;
result = YES;
}];
return result;
}
- (void)registerLastCommentToObject:(GBModelBase *)object {
[self registerComment:[self.tokenizer lastComment] toObject:object];
[self.tokenizer resetComments];
}
- (void)registerComment:(GBComment *)comment toObject:(GBModelBase *)object {
[object setComment:comment];
if (comment) GBLogDebug(@"Assigned comment '%@' to '%@'...", [comment.stringValue normalizedDescription], object);
}
- (void)registerSourceInfoFromCurrentTokenToObject:(GBModelBase *)object {
GBSourceInfo *info = [self.tokenizer sourceInfoForCurrentToken];
[object registerSourceInfo:info];
}
- (NSString *)sectionNameFromComment:(GBComment *)comment {
// If comment has nil or whitespace-only string value, ignore it.
NSCharacterSet* trimSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
if ([[comment.stringValue stringByTrimmingCharactersInSet:trimSet] length] == 0) return nil;
// If comment doesn't contain section name, ignore it, otherwise return the name.
NSString *name = [comment.stringValue stringByMatching:self.settings.commentComponents.methodGroupRegex capture:1];
if ([[name stringByTrimmingCharactersInSet:trimSet] length] == 0) return nil;
return [name stringByWordifyingWithSpaces];
}
@end