forked from k3a/AssistantExtensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AEX.mm
916 lines (801 loc) · 29.6 KB
/
AEX.mm
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//
// AEX.m
// AssistantExtensions
//
// Created by K3A on 3/19/12.
// Copyright (c) 2012 K3A. All rights reserved.
//
#include <pcre.h>
#include <string.h>
#import "AEStringAdditions.h"
#import "AEX.h"
@implementation AEPatternMatchImpl
+(id)patternMatchForText:(NSString*)text language:(NSString*)lang userInfo:(id)ui
{
AEPatternMatchImpl* pm = [[AEPatternMatchImpl alloc] initWithText:text language:lang userInfo:ui];
return [pm autorelease];
}
-(id)initWithText:(NSString*)text language:(NSString*)lang userInfo:(id)ui
{
if ( (self = [super init]) )
{
_text = [text retain];
_lang = [lang retain];
_userInfo = [ui retain];
_namedElements = [[NSMutableDictionary alloc] init];
_vectorElements = [[NSMutableArray alloc] init];
_tokens = [[NSMutableArray alloc] initWithCapacity:1];
NSScanner *scanner = [NSScanner scannerWithString:_text];
NSString *token;
while ([scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@" \t\r\n,.?!"] intoString:&token])
[_tokens addObject:token];
_tokenSet = [[NSSet alloc] initWithArray:_tokens];
}
return self;
}
-(void)dealloc
{
[_text release];
[_lang release];
[_userInfo release];
[_namedElements release];
[_vectorElements release];
[_tokens release];
[_tokenSet release];
[super dealloc];
}
-(NSString*)language
{
return _lang;
}
-(NSString*)text
{
return _text;
}
-(NSArray*)tokens
{
return _tokens;
}
-(NSSet*)tokenSet
{
return _tokenSet;
}
-(id)userInfo
{
return _userInfo;
}
-(NSString*)namedElement:(NSString*)name
{
return [_namedElements objectForKey:name];
}
-(NSString*)elementAtIndex:(unsigned)idx
{
if (idx >= [_vectorElements count]) return nil;
return [_vectorElements objectAtIndex:idx];
}
-(NSString*)firstElement
{
if ([_vectorElements count] < 1) return nil;
return [_vectorElements objectAtIndex:0];
}
-(NSString*)secondElement
{
if ([_vectorElements count] < 2) return nil;
return [_vectorElements objectAtIndex:1];
}
-(NSString*)thirdElement
{
if ([_vectorElements count] < 3) return nil;
return [_vectorElements objectAtIndex:2];
}
-(NSString*)fourthElement
{
if ([_vectorElements count] < 4) return nil;
return [_vectorElements objectAtIndex:3];
}
// private ---
-(void)addElement:(NSString*)elem
{
if (!elem) return;
NSString* e = [elem copy];
[_vectorElements addObject:e];
[e release];
}
-(void)addElement:(NSString*)elem forName:(NSString*)name
{
if (!elem) return;
NSString* e = [elem copy];
if (name && [name length])
{
[_namedElements setObject:e forKey:name];
}
[_vectorElements addObject:e];
[e release];
}
@end
#pragma mark - ===================================================================================
struct AEPatternToken {
NSString* label;
unsigned minWords; // minimum words to parse
//unsigned maxWords; // maximum words to parse
bool moreWords; // if this token represents more than one word
bool optional; // whether the token is optional
bool matchable; // whether token represents result
bool _canBeSplitCached;
bool _canBeSplit;
// one of these is used, the other is NULL
struct AEPatternSubtoken* subtoken; // if at least one subtoken matches, the whole pattern token matches
pcre* regexp;
struct AEPatternToken* next;
bool CanBeSplit()
{
if (_canBeSplitCached) return _canBeSplit;
struct AEPatternSubtoken* stok = subtoken;
while(stok)
{
if (stok->part2) { _canBeSplitCached=true; _canBeSplit=true; return _canBeSplit;}
stok = stok->next;
}
_canBeSplitCached = true;
_canBeSplit = false;
return _canBeSplit;
}
bool MatchesWord(NSString* word, int wordPart) // wordPart: 0-whole word, 1-first part, 2-second part
{
// regexp
if (regexp)
{
const char* inputPartStr = [word UTF8String];
size_t inputPartLen = strlen(inputPartStr);
int ovector[30];
int rc = pcre_exec(regexp, /* the compiled pattern */
NULL, /* no extra data - we didn't study the pattern */
inputPartStr, /* the subject string */
(int)inputPartLen, /* the length of the subject */
0, /* start at offset 0 in the subject */
0, /* default options */
ovector, /* output vector for substring information */
30); /* number of elements in the output vector */
if (rc < 0) // regexp exec failed
{
if (rc == PCRE_ERROR_NOMATCH)
{
if (!optional) return false;
}
else
{
NSLog(@"AE ERROR: Pcre matching error %d!", rc);
return FALSE;
}
}
else if (rc == 0)
{
NSLog(@"AE ERROR: Too many match results (%d)!", rc);
if (!optional) return false;
}
return true;
}
// normal
unsigned long wordHash = [word hash];
struct AEPatternSubtoken* stok = subtoken;
while(stok)
{
if (stok->type == AEPatternSubtoken::EXACT)
{
if (wordPart == 2 && !stok->part2) goto nextToken; // this subtoken is not splittable
if (wordPart == 0)
{
if (stok->wordHash && stok->wordHash == wordHash)
return true;
else if ([stok->word isEqualToString:word])
return true;
}
else if (wordPart == 1)
{
if (stok->hash1 && stok->hash1 == wordHash)
return true;
else if ([stok->part1 isEqualToString:word])
return true;
}
else if (wordPart == 2)
{
if (stok->hash2 && stok->hash2 == wordHash)
return true;
else if ([stok->part2 isEqualToString:word])
return true;
}
}
else if (stok->type == AEPatternSubtoken::FUZZY)
{
if (wordPart == 2 && !stok->part2) goto nextToken; // this subtoken is not splittable
if (wordPart == 0)
{
if ([stok->word isFuzzyEqualTo:word])
return true;
}
else if (wordPart == 1)
{
if ([stok->part1 isFuzzyEqualTo:word])
return true;
}
else if (wordPart == 2)
{
if ([stok->part2 isFuzzyEqualTo:word])
return true;
}
}
else if (stok->type == AEPatternSubtoken::WORD)
return true;
else if (stok->type == AEPatternSubtoken::NUMBER)
{
const char* str = [word UTF8String];
bool wrong = false;
while (*str)
{
if (!isdigit(*str) && *str != '.')
{
wrong = true;
break;
}
str++;
}
if (wrong) goto nextToken;
return true;
}
else if (stok->type == AEPatternSubtoken::ALPHA)
{
const char* str = [word UTF8String];
bool wrong = false;
while (*str)
{
if (!isalpha(*str))
{
wrong = true;
break;
}
str++;
}
if (wrong) goto nextToken;
return true;
}
else if (stok->type == AEPatternSubtoken::ALPHANUM)
{
const char* str = [word UTF8String];
bool wrong = false;
while (*str)
{
if (!isalnum(*str))
{
wrong = true;
break;
}
str++;
}
if (wrong) goto nextToken;
return true;
}
else
goto nextToken;
nextToken:
stok = stok->next;
}
return false;
}
};
#pragma mark - ===================================================================================
@implementation AEPattern
+(id)patternWithString:(NSString*)pat target:(id)target selector:(SEL)sel userInfo:(id)user
{
return [[[AEPattern alloc] initWithPatternString:pat target:target selector:sel userInfo:user] autorelease];
}
-(NSString*)description
{
return _description;
}
-(void)dealloc
{
[_description release];
[_target release];
[_userInfo release];
// release tokens
struct AEPatternToken* tok = _first;
while (tok) {
struct AEPatternToken* nextTok = tok->next;
[tok->label release];
// release subtokens
struct AEPatternSubtoken* stok = tok->subtoken;
while(stok) {
[stok->part1 release];
[stok->part2 release];
[stok->word release];
stok = stok->next;
}
// pcre
if (tok->regexp) pcre_free(tok->regexp);
free(tok);
tok = nextTok;
}
[super dealloc];
}
#define FAIL_STATE(reason) { NSLog(@"AE ERROR: " reason " in element '%s' (pattern '%@')", pch, pat); goto fail; }
-(id)initWithPatternString:(NSString*)pat target:(id)target selector:(SEL)sel userInfo:(id)user
{
// Note: braces must be in this order ([<word>])
self = [super init];
if (!self) return nil;
_first = NULL;
_target = [target retain];
_sel = sel;
_userInfo = [user retain];
NSString* lowercasePat = [pat lowercaseString];
_description = [[NSString stringWithFormat:@"'%@'", lowercasePat] retain];
char* pattern = strdup([lowercasePat UTF8String]);
bool optionalMatchableParsed = false;
AEPatternToken* tok;
///NSLog(@" ");
//NSLog(@">>> PATTERN '%s'", pattern);
char* pch = strtok (pattern," \n\r\t");
while (pch != NULL)
{
char* inPtr = pch;
char* rawStart = NULL;
char* rawEnd = NULL;
char* labelStart = NULL;
char* labelEnd = NULL;
bool inMatchPar = false; // inside ()
bool inTypePar = false; // inside <>
bool inRegPar = false; // inside //
bool inOptPar = false; // inside []
bool regParsed = false;
bool matchParsed = false;
bool typeParsed = false;
bool optParsed = false;
bool plusParsed = false;
bool asteriskParsed = false;
while (*inPtr)
{
if (*inPtr == '/' && inRegPar) //regexp end
{
regParsed = true;
inRegPar = false;
if (!rawEnd) rawEnd = inPtr;
}
else if (inRegPar) { // regexp body
inPtr++;
continue;
}
else if (*inPtr == '(')
{
if (inMatchPar) FAIL_STATE("Unexpected second '('");
if (matchParsed) FAIL_STATE("Only one (..) block is allowed");
if (inTypePar || inOptPar) FAIL_STATE("Wrong order of braces must be ([<...>])");
inMatchPar = true;
}
else if (*inPtr == '<')
{
if (inTypePar) FAIL_STATE("Unexpected second '<'");
if (typeParsed) FAIL_STATE("Only one <..> block is allowed");
if (rawStart && !labelEnd) FAIL_STATE("Garbage at the beginning");
inTypePar = true;
rawStart = inPtr;
}
else if (*inPtr == '[')
{
if (inOptPar) FAIL_STATE("Unexpected second '['");
if (optParsed) FAIL_STATE("Only one [..] block is allowed");
if (inTypePar) FAIL_STATE("Wrong order of braces must be ([<...>])");
if (rawStart && !labelEnd) FAIL_STATE("Garbage at the beginning");
inOptPar = true;
}
else if (*inPtr == ':')
{
if (!labelStart) FAIL_STATE("Missing label name");
labelEnd = inPtr;
rawStart = inPtr+1;
}
else if (*inPtr == ')')
{
if (!inMatchPar) FAIL_STATE("Unexpected ')'");
if (inTypePar) FAIL_STATE("Expected '>' before ')'");
if (inOptPar) FAIL_STATE("Expected ']' before ')'");
inMatchPar = false;
matchParsed = true;
if (!rawEnd) rawEnd = inPtr;
}
else if (*inPtr == '>')
{
if (!inTypePar) FAIL_STATE("Unexpected '>'");
inTypePar = false;
typeParsed = true;
if (!rawEnd) rawEnd = inPtr+1;
}
else if (*inPtr == ']')
{
if (!inOptPar) FAIL_STATE("Unexpected ']'");
if (inTypePar) FAIL_STATE("Expected '>' before ']'");
inOptPar = false;
optParsed = true;
if (!rawEnd) rawEnd = inPtr;
}
else if (*inPtr == '/') // regexp begin
{
if (!inRegPar && regParsed) FAIL_STATE("Unexpected '/'");
inRegPar = true;
rawStart = inPtr+1;
}
else if (*inPtr == '+')
{
if (!typeParsed) FAIL_STATE("Unexpected '+'");
plusParsed = true;
}
else if (*inPtr == '*')
{
if (!typeParsed) FAIL_STATE("Unexpected '*'");
asteriskParsed = true;
}
else // other char
{
if (!labelStart) labelStart = inPtr;
// raw start
if (!rawStart) rawStart = inPtr; // raw start for nonmatchable element
// check for garbage at the end
if ( labelEnd // has label but is already parsed
&& inMatchPar && rawEnd) FAIL_STATE("Garbage at the end"); // garbage after raw body (rawEnd), after label, for matchable element
}
inPtr++;
}
if (!rawEnd) rawEnd = inPtr; // end body
if (!rawStart && !regParsed) FAIL_STATE("Missing body");
if (rawEnd-rawStart == 0) FAIL_STATE("Empty body");
if (labelStart >= rawEnd) FAIL_STATE("Bad label");
if (inMatchPar) FAIL_STATE("Missing ')'");
if (inTypePar) FAIL_STATE("Missing '>'");
if (inRegPar) FAIL_STATE("Missing ending '/'");
if (inOptPar) FAIL_STATE("Missing ']'");
// check order of optional matchables
if (optionalMatchableParsed && matchParsed && !optParsed)
FAIL_STATE("Optional matchable words must be at the end");
if (optParsed && matchParsed)
optionalMatchableParsed = true;
// body
unsigned tbodyLen = (unsigned)(rawEnd-rawStart);
char* tbody = (char*)malloc(tbodyLen+1);
strncpy(tbody, rawStart, tbodyLen);
tbody[tbodyLen] = 0;
// label
unsigned tlabelLen = (unsigned)(labelEnd-labelStart);
if (!labelEnd) tlabelLen=0;
char* tlabel = (char*)malloc(tlabelLen+1);
strncpy(tlabel, labelStart, tlabelLen);
tlabel[tlabelLen] = 0;
// print token with parsed data for debug
//NSLog(@"--- %s%s%sTOKEN '%s' label '%s'", matchParsed?"MATCHABLE ":"", optParsed?"OPTIONAL ":"", regParsed?"REGEXP ":"", tbody, tlabel);
// TODO: process body to find | <word>*+ or ~a a~b
tok = (AEPatternToken*)malloc(sizeof(AEPatternToken));
if (!tlabel || !*tlabel)
tok->label = nil;
else
tok->label = [[NSString stringWithUTF8String:tlabel] retain];
tok->minWords = 0;
if (plusParsed) tok->minWords = 1;
tok->moreWords = asteriskParsed || plusParsed;
tok->optional = optParsed || asteriskParsed;
tok->matchable = matchParsed;
tok->subtoken = NULL;
tok->regexp = NULL;
tok->_canBeSplit = tok->_canBeSplitCached = false;
if (regParsed) // pcre regexp
{
const char *err_msg;
int err;
tok->regexp = pcre_compile(tbody, PCRE_UTF8/*|PCRE_CASELESS*/, &err_msg, &err, NULL);
if (!tok->regexp)
{
NSLog(@"AE ERROR: Regexp error %d '%s' in element '%s' (pattern '%@')", err, err_msg, pch, pat);
goto fail;
}
}
else // normal word - AE expression
{
// split words by |
char* strtok2;
pch = strtok_r(tbody,"|",&strtok2);
while (pch != NULL)
{
// find ~ inside word
char* firstPart = pch;
char* secondPart = NULL;
char* tmp = pch+1;
while (*tmp) {
if (*tmp == '~') {
*tmp = 0;
secondPart = tmp+1;
break;
}
tmp++;
}
struct AEPatternSubtoken* stok = (AEPatternSubtoken*)malloc(sizeof(AEPatternSubtoken));
// fuzzy?
if (firstPart[0] == '~')
{
stok->type = AEPatternSubtoken::FUZZY;
firstPart++;
}
else
{
stok->type = AEPatternSubtoken::EXACT;
if (typeParsed)
{
if (!strcmp(tbody, "<word>"))
stok->type = AEPatternSubtoken::WORD;
else if (!strcmp(tbody, "<number>") || !strcmp(tbody, "<num>"))
stok->type = AEPatternSubtoken::NUMBER;
else if (!strcmp(tbody, "<alpha>"))
stok->type = AEPatternSubtoken::ALPHA;
else if (!strcmp(tbody, "<alphanum>"))
stok->type = AEPatternSubtoken::ALPHANUM;
else if (!strcmp(tbody, "<person>"))
stok->type = AEPatternSubtoken::PERSON;
else
FAIL_STATE("Unknown word type")
}
}
// add word
stok->part1 = stok->part2 = stok->word = nil;
stok->hash1 = stok->hash2 = stok->wordHash = 0;
if (!secondPart)
{
stok->word = [[NSString stringWithUTF8String:firstPart] retain];
stok->wordHash = [stok->word hash];
//NSLog(@"WORD: '%@'", stok->word);
}
else
{
// parts
stok->part1 = [[NSString stringWithUTF8String:firstPart] retain];
stok->hash1 = [stok->part1 hash];
stok->part2 = [[NSString stringWithUTF8String:secondPart] retain];
stok->hash2 = [stok->part2 hash];
// whole word
size_t l1 = strlen(firstPart);
size_t l2 = strlen(secondPart);
char* wholeWord = (char*)malloc( l1 + l2 + 1 );
strcpy(wholeWord, firstPart);
strcpy(&wholeWord[l1], secondPart);
stok->word = [[NSString stringWithUTF8String:wholeWord] retain];
stok->wordHash = [stok->word hash];
free(wholeWord);
//NSLog(@"WHOLE: '%@' PART1:'%@' PART2:'%@'", stok->word, stok->part1, stok->part2);
}
// add subtoken
stok->next = tok->subtoken;
tok->subtoken = stok;
pch = strtok_r(NULL,"|",&strtok2);
}
}
// cache can be split
tok->CanBeSplit();
free(tbody);
free(tlabel);
// add token to the end
AEPatternToken* lastTok = _first;
while (lastTok && lastTok->next)
lastTok = lastTok->next;
tok->next = NULL;
if (lastTok)
lastTok->next = tok;
else
_first = tok;
// next token
pch = strtok (NULL, " \n\r\t");
}
// check for good pattern form
tok = _first;
while (tok)
{
if (tok->moreWords && tok->next) // find a stop word
{
if (tok->next->moreWords)
FAIL_STATE("Pattern uses two or more multiple-word tokens (like <word>*) in a row!")
/*bool gotStopWord = false;
AEPatternToken* tmpt = tok->next;
while (tmpt)
{
if (!tmpt->moreWords && !tmpt->subtoken->type != AEPatternSubtoken::WORD && !tmpt->optional)
{
gotStopWord = true;
break;
}
tmpt = tmpt->next;
}
if (!gotStopWord)
FAIL_STATE("Pattern uses multiple-word tokens (like <word>*) but there is not a stop word!")*/
}
tok = tok->next;
}
free(pattern);
return self;
fail:
free(pattern);
[self release];
return nil;
}
-(BOOL)fireWithMatch:(id<AEPatternMatch>)match context:(id<SEContext>)ctx
{
NSLog(@"AE: Invoking target %@ (%s) using the selector %s", _target, object_getClassName(_target), sel_getName(_sel));
NSMethodSignature* sig = [_target methodSignatureForSelector:_sel];
NSInvocation* inv = [NSInvocation invocationWithMethodSignature:sig];
[inv setSelector:_sel];
[inv setTarget:_target];
[inv setArgument:&match atIndex:2]; // match
[inv setArgument:&ctx atIndex:3]; // context
[inv invoke];
BOOL val = FALSE;
[inv getReturnValue:&val];
return val;
}
-(BOOL)execute:(NSString*)input language:(NSString*)lang context:(id<SEContext>)ctx
{
if (!_first || [input length] == 0) return FALSE;
NSString* lcInput = [input lowercaseString];
NSArray* inputTokens = [lcInput componentsSeparatedByString:@" "];
NSEnumerator* enumer = [inputTokens objectEnumerator];
AEPatternToken* currentToken = _first;
int currentWordPart = 0;
AEPatternMatchImpl* match = [AEPatternMatchImpl patternMatchForText:lcInput language:lang userInfo:_userInfo];
NSMutableString* currElem = [NSMutableString string];
bool firstWordOfElem = true;
//Break([[input lowercaseString] isEqualTo:@"special you tube fone"] && [[self description] isEqualTo:@"'special You~Tube [~fone]'"]);
unsigned inpTokNum = 0;
NSString* inpTok = [enumer nextObject];
while(inpTok)
{
//Break([inpTok isEqualTo:@"phone"]);
inpTokNum++;
bool doNotGetNextInputToken = false;
// try normally first
bool currTokMatches = currentToken->MatchesWord(inpTok, 0);
// inform REF1 that it should get next aex for the next iteration (like if was second part of spitword aex)
if (currentWordPart == 0 && currTokMatches && currentToken->CanBeSplit())
currentWordPart = 2;
// if not matched, it may be the first input word of a~b splittable aex
if (!currTokMatches && currentToken->CanBeSplit())
{
currTokMatches = currentToken->MatchesWord(inpTok, 1+currentWordPart);
currentWordPart++;
}
// skip optional non-matched aex tokens
if (!currTokMatches && !currentToken->optional) // not matched and not optional, whole input phrase not matched
return FALSE;
else if (!currTokMatches && currentToken->optional) // optional and not matched, get next aex token
{
currentToken = currentToken->next;
if (!currentToken) return FALSE; // it was last optional aex but not matched!
inpTokNum--;
continue;
}
// ... aex and input token matched ...
// add token to current element if it's matchable
if (currentToken->matchable)
{
if (firstWordOfElem)
{
[currElem appendString:inpTok];
firstWordOfElem = false;
}
else
[currElem appendFormat:@" %@", inpTok];
}
// ... next token ...
// multi-word aex token? Eat input tokens until the stop token is found
if (currentToken->moreWords)
{
unsigned numInpTokensForMultiwordAex = 1;
while ( (inpTok = [enumer nextObject]) )
{
if (!inpTok) break;
inpTokNum++;
numInpTokensForMultiwordAex++;
// try to find the nearest, non-optional stop aex word
bool currInpTokIsAtStopAexWord = false;
AEPatternToken* tmpt = currentToken->next;
while (tmpt)
{
if (tmpt->moreWords) // we are too far - multiword aex is not a stop word
break;
else // ok, single word aex token, can be stop but can be optional
{
if (tmpt->MatchesWord(inpTok, 0))
{
if (tmpt->CanBeSplit())
currentWordPart = 1;
currInpTokIsAtStopAexWord = true;
break;
}
else if (!tmpt->optional) // not matched and not optional, currInpTokIsAtStopAexWord=false
break;
}
tmpt = tmpt->next;
}
if (currInpTokIsAtStopAexWord)
{
// do not add to currElem string, as this will be done next iteration, after we are at the next aex token
doNotGetNextInputToken = true;
inpTokNum--;
numInpTokensForMultiwordAex--;
break;
}
else
{
// add token to current element if it's matchable
if (currentToken->matchable)
{
if (firstWordOfElem)
{
[currElem appendString:inpTok];
firstWordOfElem = false;
}
else
[currElem appendFormat:@" %@", inpTok];
}
}
}
// not enough input tokens for minimum-words-criterium in this aex multiword
if (numInpTokensForMultiwordAex < currentToken->minWords)
return FALSE;
/*else if (numInpTokensForMultiwordAex > currentToken->minWords)
return FALSE;*/ // TODO: max criterium
}
// we are done with the current aex token, add it to the match results if matchable
if (currentToken->matchable)
{
[match addElement:currElem forName:currentToken->label];
[currElem setString:@""];
firstWordOfElem = true;
}
// get next aex token (only for non-split aex or after the second part was matched)
if (!currentToken->CanBeSplit() || currentWordPart == 2) // REF1
{
currentToken = currentToken->next;
if (!currentToken) break;
}
if (currentWordPart == 2) currentWordPart = 0; // reset when in second part of a~b
// get the next input token
if (doNotGetNextInputToken == false)
inpTok = [enumer nextObject];
}
// phrase mathed, but make sure it matched completely
// = no current or next token (in case of the last aex token is multiword) + all input tokens must be ate
bool matched = inpTokNum == [inputTokens count];
if (currentToken) // check that current token and next tokens are optional
{
while (currentToken)
{
if (!currentToken->optional)
{
matched = false;
break;
}
currentToken = currentToken->next;
}
}
// if matched and the target was set, call handling method
if (matched && _target)
{
matched = [self fireWithMatch:match context:ctx];
}
return matched;
}
-(id)target
{
return _target;
}
-(SEL)selector
{
return _sel;
}
-(id)userInfo
{
return _userInfo;
}
@end