-
Notifications
You must be signed in to change notification settings - Fork 49
/
CPGrammarInternal.m
427 lines (371 loc) · 14.3 KB
/
CPGrammarInternal.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
//
// CPGrammarInternal.m
// CoreParse
//
// Created by Tom Davie on 04/06/2011.
// Copyright 2011 In The Beginning... All rights reserved.
//
#import "CPGrammarInternal.h"
#import "CPGrammarPrivate.h"
#import "CPRule+Internal.h"
#import "CPItem.h"
#import "CPLR1Item.h"
#import "CPRHSItem.h"
#import "CPRHSItem+Private.h"
#import "CPRHSItemResult.h"
#import "NSSetFunctional.h"
@implementation CPGrammar (CPGrammarInternal)
- (CPGrammar *)augmentedGrammar
{
return [[[CPGrammar alloc] initWithStart:@"s'"
rules:[[self rules] arrayByAddingObject:[CPRule ruleWithName:@"s'" rightHandSideElements:[NSArray arrayWithObject:[CPGrammarSymbol nonTerminalWithName:[self start]]]]]]
autorelease];
}
- (NSUInteger)indexOfRule:(CPRule *)rule
{
return [[self orderedRules] indexOfObject:rule];
}
- (NSString *)description
{
NSArray *ordered = [self orderedRules];
NSMutableString *s = [NSMutableString string];
NSUInteger idx = 0;
for (CPRule *r in ordered)
{
[s appendFormat:@"%3ld %@\n", (long)idx, r];
idx++;
}
return s;
}
- (NSSet *)lr0Closure:(NSSet *)i
{
NSMutableSet *j = [i mutableCopy];
NSMutableArray *processingQueue = [[j allObjects] mutableCopy];
while ([processingQueue count] > 0)
{
CPItem *item = [processingQueue objectAtIndex:0];
CPGrammarSymbol *nextSymbol = [item nextSymbol];
if (![nextSymbol isTerminal])
{
[[self rulesForNonTerminalWithName:[nextSymbol name]] enumerateObjectsUsingBlock:^(CPRule *rule, NSUInteger ix, BOOL *s)
{
CPItem *newItem = [CPItem itemWithRule:rule position:0];
if (![j containsObject:newItem])
{
[processingQueue addObject:newItem];
[j addObject:newItem];
}
}];
}
[processingQueue removeObjectAtIndex:0];
}
[processingQueue release];
return [j autorelease];
}
- (NSSet *)lr0GotoKernelWithItems:(NSSet *)i symbol:(CPGrammarSymbol *)symbol
{
return [[i objectsPassingTest:^ BOOL (CPItem *item, BOOL *stop)
{
return [symbol isEqual:[item nextSymbol]];
}]
map:^ id (CPItem *item)
{
return [item itemByMovingDotRight];
}];
}
- (NSArray *)lr0Kernels
{
CPRule *startRule = [[self rulesForNonTerminalWithName:[self start]] objectAtIndex:0];
NSSet *initialKernel = [NSSet setWithObject:[CPItem itemWithRule:startRule position:0]];
NSMutableArray *c = [NSMutableArray arrayWithObject:initialKernel];
NSMutableArray *processingQueue = [NSMutableArray arrayWithObject:initialKernel];
while ([processingQueue count] > 0)
{
NSSet *kernel = [processingQueue objectAtIndex:0];
NSSet *itemSet = [self lr0Closure:kernel];
NSSet *validNexts = [itemSet map:^ id (CPItem *item) { return [item nextSymbol]; }];
for (CPGrammarSymbol *s in validNexts)
{
NSSet *g = [self lr0GotoKernelWithItems:itemSet symbol:s];
if (![c containsObject:g])
{
[processingQueue addObject:g];
[c addObject:g];
}
}
[processingQueue removeObjectAtIndex:0];
}
return c;
}
- (NSSet *)lr1Closure:(NSSet *)i
{
NSMutableSet *j = [i mutableCopy];
NSMutableArray *processingQueue = [[j allObjects] mutableCopy];
while ([processingQueue count] > 0)
{
CPLR1Item *item = (CPLR1Item *)[processingQueue objectAtIndex:0];
NSArray *followingSymbols = [item followingSymbols];
CPGrammarSymbol *nextSymbol = [followingSymbols count] > 0 ? [followingSymbols objectAtIndex:0] : nil;
if (![nextSymbol isTerminal])
{
NSArray *rs = [self rulesForNonTerminalWithName:[(CPGrammarSymbol *)nextSymbol name]];
for (CPRule *r in rs)
{
NSArray *afterNext = [followingSymbols subarrayWithRange:NSMakeRange(1, [followingSymbols count] - 1)];
NSArray *afterNextWithTerminal = [afterNext arrayByAddingObject:[item terminal]];
NSSet *firstAfterNext = [self first:afterNextWithTerminal];
for (NSString *o in firstAfterNext)
{
CPLR1Item *newItem = [CPLR1Item lr1ItemWithRule:r position:0 terminal:[CPGrammarSymbol terminalWithName:o]];
if (![j containsObject:newItem])
{
[processingQueue addObject:newItem];
[j addObject:newItem];
}
}
}
}
[processingQueue removeObjectAtIndex:0];
}
[processingQueue release];
return [j autorelease];
}
- (NSSet *)lr1GotoKernelWithItems:(NSSet *)i symbol:(CPGrammarSymbol *)symbol
{
return [[i objectsPassingTest:^ BOOL (CPItem *item, BOOL *stop)
{
return [symbol isEqual:[item nextSymbol]];
}]
map:^ id (CPItem *item)
{
return [item itemByMovingDotRight];
}];
}
- (NSSet *)follow:(NSString *)name
{
NSSet *follows = [[self followCache] objectForKey:name];
if (nil == follows)
{
NSMutableSet *f = [NSMutableSet setWithObject:@"EOF"];
for (CPRule *rule in [self allRules])
{
NSArray *rightHandSide = [rule rightHandSideElements];
NSUInteger numElements = [rightHandSide count];
[rightHandSide enumerateObjectsUsingBlock:^(CPGrammarSymbol *rhsE, NSUInteger idx, BOOL *s)
{
if (![rhsE isTerminal] && [[rhsE name] isEqualToString:name])
{
if (idx + 1 < numElements)
{
NSSet *first = [self first:[rightHandSide subarrayWithRange:NSMakeRange(idx+1, [rightHandSide count] - idx - 1)]];
NSSet *firstMinusEmpty = [first objectsPassingTest:^ BOOL (NSString *symbolName, BOOL *fstop)
{
return ![symbolName isEqualToString:@""];
}];
[f unionSet:firstMinusEmpty];
}
else if (![[rule name] isEqualToString:name])
{
[f unionSet:[self follow:[rule name]]];
}
}
}];
}
follows = f;
[[self followCache] setObject:f forKey:name];
}
return follows;
}
- (NSSet *)first:(NSArray *)symbols
{
NSMutableSet *f = [NSMutableSet set];
for (CPGrammarSymbol *symbol in symbols)
{
NSSet *f1 = [self firstSymbol:symbol];
[f unionSet:f1];
if (![f1 containsObject:@""])
{
break;
}
}
return f;
}
- (NSString *)uniqueSymbolNameBasedOnName:(NSString *)name
{
return [self symbolNameNotInSet:[self allSymbolNames] basedOnName:name];
}
- (NSString *)symbolNameNotInSet:(NSSet *)symbols basedOnName:(NSString *)name
{
NSString *testName = [[name copy] autorelease];
while ([symbols containsObject:testName])
{
testName = [NSString stringWithFormat:@"_%@", testName];
}
return testName;
}
- (NSArray *)tidyRightHandSides:(NSArray *)oldRules error:(NSError **)error
{
NSError *invalidRuleError = [self checkRulesForErrors:oldRules];
if (nil != invalidRuleError)
{
*error = invalidRuleError;
return nil;
}
NSMutableSet *rhsElements = [NSMutableSet set];
for (CPRule *r in oldRules)
{
[rhsElements unionSet:[self collectRHSElementsForNewRules:[r rightHandSideElements]]];
}
NSDictionary *names = [self nameNewRules:rhsElements withRules:oldRules];
return [self addRHSRules:names toRules:oldRules];
}
- (NSError *)checkRulesForErrors:(NSArray *)rules
{
NSError *error = nil;
for (CPRule *rule in rules)
{
NSArray *rightHandSide = [rule rightHandSideElements];
NSMutableSet *tagNames = [NSMutableSet set];
for (id element in rightHandSide)
{
if ([element isRHSItem])
{
NSSet *newTagNames = [(CPRHSItem *)element tagNamesWithError:&error];
if (nil != error)
{
return error;
}
NSMutableSet *duplicateTags = [[tagNames mutableCopy] autorelease];
[duplicateTags intersectSet:newTagNames];
if ([duplicateTags count] > 0)
{
return [NSError errorWithDomain:CPEBNFParserErrorDomain
code:CPErrorCodeDuplicateTag
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Duplicate tag names %@ in same part of alternative is not allowed in \"%@\".", duplicateTags, rule], NSLocalizedDescriptionKey,
nil]];
}
[tagNames unionSet:newTagNames];
NSString *tagName = [(CPRHSItem *)element tag];
if (nil != tagName)
{
if ([tagNames containsObject:tagName])
{
return [NSError errorWithDomain:CPEBNFParserErrorDomain
code:CPErrorCodeDuplicateTag
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Duplicate tag names (%@) in same part of alternative is not allowed in \"%@\".", tagName, rule], NSLocalizedDescriptionKey,
nil]];
}
[tagNames addObject:tagName];
}
}
}
}
return nil;
}
- (NSSet *)collectRHSElementsForNewRules:(NSArray *)rightHandSide
{
NSMutableSet *ret = [NSMutableSet set];
for (id element in rightHandSide)
{
if ([element isRHSItem])
{
[ret addObject:element];
for (NSArray *contents in [(CPRHSItem *)element alternatives])
{
[ret unionSet:[self collectRHSElementsForNewRules:contents]];
}
}
}
return ret;
}
- (NSDictionary *)nameNewRules:(NSSet *)rhsElements withRules:(NSArray *)oldRules
{
NSSet *symbolNames = [self symbolNamesInRules:oldRules];
NSUInteger name = 0;
NSMutableDictionary *namedRules = [NSMutableDictionary dictionaryWithCapacity:[rhsElements count]];
for (CPRHSItem *item in rhsElements)
{
[namedRules setObject:[self symbolNameNotInSet:symbolNames basedOnName:[NSString stringWithFormat:@"RHS%ld", (long)name]] forKey:item];
name++;
}
return namedRules;
}
- (NSArray *)addRHSRules:(NSDictionary *)newRules toRules:(NSArray *)oldRules
{
NSMutableArray *rules = [[NSMutableArray alloc] initWithArray:oldRules];
Class rhsItemClass = [CPRHSItemResult class];
for (CPRHSItem *item in newRules)
{
NSString *ruleName = [newRules objectForKey:item];
// We never generate a CPRHSItem which both repeats/mayNotExist, and has alternatives
// Cases where this happens are represented as two CPRHSItems, one inside another
// Because of this, we can deal with the two cases completely seperately.
if ([[item alternatives] count] == 1)
{
CPRule *rule;
if ([item mayNotExist])
{
rule = [[[CPRule alloc] initWithName:ruleName rightHandSideElements:[NSArray array]] autorelease];
[rule setTag:0];
}
else
{
rule = [[[CPRule alloc] initWithName:ruleName rightHandSideElements:[[item alternatives] objectAtIndex:0]] autorelease];
[rule setTag:1];
}
[rule setShouldCollapse:[item shouldCollapse]];
[rule setTagName:[item tag]];
[rule setRepresentitiveClass:rhsItemClass];
[rules addObject:rule];
if ([item repeats])
{
rule = [[[CPRule alloc] initWithName:ruleName rightHandSideElements:[[[item alternatives] objectAtIndex:0] arrayByAddingObject:[CPGrammarSymbol nonTerminalWithName:ruleName]]] autorelease];
[rule setTag:2];
}
else if ([item mayNotExist])
{
rule = [[[CPRule alloc] initWithName:ruleName rightHandSideElements:[[item alternatives] objectAtIndex:0]] autorelease];
[rule setTag:1];
}
else
{
rule = nil;
}
if (nil != rule)
{
[rule setShouldCollapse:[item shouldCollapse]];
[rule setTagName:[item tag]];
[rule setRepresentitiveClass:rhsItemClass];
[rules addObject:rule];
}
}
else
{
NSUInteger i = 0;
for (NSArray *contents in [item alternatives])
{
CPRule *rule = [[[CPRule alloc] initWithName:ruleName rightHandSideElements:contents] autorelease];
[rule setTag:3 + i];
[rule setRepresentitiveClass:rhsItemClass];
[rule setShouldCollapse:[item shouldCollapse]];
[rule setTagName:[item tag]];
[rules addObject:rule];
i++;
}
}
}
for (CPRule *rule in rules)
{
NSArray *rhsElements = [rule rightHandSideElements];
NSMutableArray *newRightHandSideElements = [NSMutableArray arrayWithCapacity:[rhsElements count]];
for (id element in rhsElements)
{
[newRightHandSideElements addObject:[element isRHSItem] ? [CPGrammarSymbol nonTerminalWithName:[newRules objectForKey:element]] : element];
}
[rule setRightHandSideElements:newRightHandSideElements];
}
return rules;
}
@end