/
NSRegularExpression.m
1163 lines (1040 loc) · 31.1 KB
/
NSRegularExpression.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
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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Implementation of NSRegularExpression for GNUStep
Copyright (C) 2010 Free Software Foundation, Inc.
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
*/
#define EXPOSE_NSRegularExpression_IVARS 1
#import "common.h"
#if GS_USE_ICU == 1
#if defined(HAVE_UNICODE_UREGEX_H)
#include <unicode/uregex.h>
#elif defined(HAVE_ICU_H)
#include <icu.h>
#endif
/* FIXME It would be nice to use autoconf for checking whether uregex_openUText
* is defined. However the naive check using AC_CHECK_FUNCS(uregex_openUText)
* won't work because libicu internally renames all entry points with some cpp
* magic.
*/
#if U_ICU_VERSION_MAJOR_NUM > 4 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM >= 4) || defined(HAVE_ICU_H)
#define HAVE_UREGEX_OPENUTEXT 1
#endif
#define NSRegularExpressionWorks
#define GSREGEXTYPE URegularExpression
#import "GSICUString.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSException.h"
#import "Foundation/NSRegularExpression.h"
#import "Foundation/NSTextCheckingResult.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSCoder.h"
#import "Foundation/NSUserDefaults.h"
#import "Foundation/NSNotification.h"
#import "Foundation/FoundationErrors.h"
#import "Foundation/NSError.h"
/**
* To be helpful, Apple decided to define a set of flags that mean exactly the
* same thing as the URegexpFlags enum in libicu, but have different values.
* This was completely stupid, but we probably have to live with it. We could
* in theory use the libicu values directly (that would be sensible), but that
* would break any code that didn't correctly use the symbolic constants.
*/
uint32_t
NSRegularExpressionOptionsToURegexpFlags(NSRegularExpressionOptions opts)
{
uint32_t flags = 0;
if (opts & NSRegularExpressionCaseInsensitive)
{
flags |= UREGEX_CASE_INSENSITIVE;
}
if (opts & NSRegularExpressionAllowCommentsAndWhitespace)
{
flags |= UREGEX_COMMENTS;
}
if (opts & NSRegularExpressionIgnoreMetacharacters)
{
flags |= UREGEX_LITERAL;
}
if (opts & NSRegularExpressionDotMatchesLineSeparators)
{
flags |= UREGEX_DOTALL;
}
if (opts & NSRegularExpressionAnchorsMatchLines)
{
flags |= UREGEX_MULTILINE;
}
if (opts & NSRegularExpressionUseUnixLineSeparators)
{
flags |= UREGEX_UNIX_LINES;
}
if (opts & NSRegularExpressionUseUnicodeWordBoundaries)
{
flags |= UREGEX_UWORD;
}
return flags;
}
@implementation NSRegularExpression
+ (NSRegularExpression*) regularExpressionWithPattern: (NSString*)aPattern
options: (NSRegularExpressionOptions)opts
error: (NSError**)e
{
NSRegularExpression *r;
r = [[self alloc] initWithPattern: aPattern
options: opts
error: e];
return AUTORELEASE(r);
}
#if HAVE_UREGEX_OPENUTEXT
- (id) initWithPattern: (NSString*)aPattern
options: (NSRegularExpressionOptions)opts
error: (NSError**)e
{
uint32_t flags = NSRegularExpressionOptionsToURegexpFlags(opts);
UText p = UTEXT_INITIALIZER;
UParseError pe = {0};
UErrorCode s = 0;
// Raise an NSInvalidArgumentException to match macOS behaviour.
if (!aPattern)
{
NSException *exp;
exp = [NSException exceptionWithName: NSInvalidArgumentException
reason: @"nil argument"
userInfo: nil];
[exp raise];
}
#if !__has_feature(blocks)
if ([self class] != [NSRegularExpression class])
{
GSOnceMLog(@"Warning: NSRegularExpression was built by a compiler without blocks support. NSRegularExpression will deviate from the documented behaviour when subclassing and any code that subclasses NSRegularExpression may break in unexpected ways. If you must subclass NSRegularExpression, you are strongly recommended to use a compiler with blocks support.");
}
#endif
UTextInitWithNSString(&p, aPattern);
regex = uregex_openUText(&p, flags, &pe, &s);
utext_close(&p);
if (U_FAILURE(s))
{
/* Match macOS behaviour if the pattern is invalid.
* Example:
* Domain=NSCocoaErrorDomain
* Code=2048 "The value “<PATTERN>” is invalid."
* UserInfo={NSInvalidValue=<PATTERN>}
*/
if (e)
{
NSDictionary *userInfo;
NSString *description;
description = [NSString stringWithFormat: @"The value “%@” is invalid.", aPattern];
userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
aPattern, @"NSInvalidValue",
description, NSLocalizedDescriptionKey,
nil];
*e = [NSError errorWithDomain: NSCocoaErrorDomain
code: NSFormattingError
userInfo: userInfo];
}
DESTROY(self);
return self;
}
options = opts;
return self;
}
- (BOOL) isEqual: (id)obj
{
if ([obj isKindOfClass: [NSRegularExpression class]])
{
if (self == obj)
{
return YES;
}
else if (options != ((NSRegularExpression*)obj)->options)
{
return NO;
}
else
{
UErrorCode myErr = 0;
UErrorCode theirErr = 0;
const UText *myText = uregex_patternUText(regex, &myErr);
const UText *theirText =
uregex_patternUText(((NSRegularExpression*)obj)->regex, &theirErr);
if (U_FAILURE(myErr) != U_FAILURE(theirErr))
{
return NO;
}
else if (U_FAILURE(myErr) && U_FAILURE(theirErr))
{
return YES;
}
return utext_equals(myText, theirText);
}
}
else
{
return [super isEqual: obj];
}
}
- (NSString*) pattern
{
UErrorCode s = 0;
UText *t = uregex_patternUText(regex, &s);
GSUTextString *str = NULL;
if (U_FAILURE(s))
{
return nil;
}
str = [GSUTextString new];
utext_clone(&str->txt, t, FALSE, TRUE, &s);
return AUTORELEASE(str);
}
#else
- (id) initWithPattern: (NSString*)aPattern
options: (NSRegularExpressionOptions)opts
error: (NSError**)e
{
int32_t length = [aPattern length];
uint32_t flags = NSRegularExpressionOptionsToURegexpFlags(opts);
UParseError pe = {0};
UErrorCode s = 0;
TEMP_BUFFER(buffer, length);
#if !__has_feature(blocks)
if ([self class] != [NSRegularExpression class])
{
GSOnceMLog(@"Warning: NSRegularExpression was built by a compiler without blocks support. NSRegularExpression will deviate from the documented behaviour when subclassing and any code that subclasses NSRegularExpression may break in unexpected ways. If you must subclass NSRegularExpression, you are strongly recommended to use a compiler with blocks support.");
}
#endif
[aPattern getCharacters: buffer range: NSMakeRange(0, length)];
regex = uregex_open(buffer, length, flags, &pe, &s);
if (U_FAILURE(s))
{
// FIXME: Do something sensible with the error parameter.
DESTROY(self);
return self;
}
options = opts;
return self;
}
- (BOOL) isEqual: (id)obj
{
if ([obj isKindOfClass: [NSRegularExpression class]])
{
if (self == obj)
{
return YES;
}
else if (options != ((NSRegularExpression*)obj)->options)
{
return NO;
}
else
{
UErrorCode myErr = 0;
UErrorCode theirErr = 0;
int32_t myLen = 0;
int32_t theirLen = 0;
const UChar *myText = uregex_pattern(regex, &myLen, &myErr);
const UChar *theirText = uregex_pattern(
((NSRegularExpression*)obj)->regex,
&theirLen, &theirErr);
if (U_FAILURE(myErr) != U_FAILURE(theirErr))
{
return NO;
}
else if (U_FAILURE(myErr) && U_FAILURE(theirErr))
{
return YES;
}
if (myLen != theirLen)
{
return NO;
}
return (0 == memcmp((const void*)myText, (const void*)theirText, myLen));
}
}
else
{
return [super isEqual: obj];
}
}
- (NSString*) pattern
{
UErrorCode s = 0;
int32_t length;
const unichar *pattern = uregex_pattern(regex, &length, &s);
if (U_FAILURE(s))
{
return nil;
}
return [NSString stringWithCharacters: pattern length: length];
}
#endif
- (NSUInteger) hash
{
return [[self pattern] hash] ^ options;
}
static UBool
callback(const void *context, int32_t steps)
{
BOOL stop = NO;
GSRegexBlock block = (GSRegexBlock)context;
if (NULL == context)
{
return FALSE;
}
CALL_BLOCK(block, nil, NSMatchingProgress, &stop);
return stop;
}
#define DEFAULT_WORK_LIMIT 1500
/**
* The work limit specifies the number of iterations the matcher will do before
* aborting an operation. This ensures that degenerate pattern/input
* combinations don't send the application into what for all intents and
* purposes seems like an infinite loop.
*/
static int32_t _workLimit = DEFAULT_WORK_LIMIT;
+ (void) _defaultsChanged: (NSNotification*)n
{
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
id value = [defs objectForKey: @"GSRegularExpressionWorkLimit"];
int32_t newLimit = DEFAULT_WORK_LIMIT;
if ([value respondsToSelector: @selector(intValue)])
{
int32_t v = [value intValue];
if (v >= 0)
{
newLimit = v;
}
}
_workLimit = newLimit;
}
+ (void) initialize
{
if (self == [NSRegularExpression class])
{
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: @selector(_defaultsChanged:)
name: NSUserDefaultsDidChangeNotification
object: nil];
[self _defaultsChanged: nil];
}
}
/**
* Sets up a libicu regex object for use. Note: the documentation states that
* NSRegularExpression must be thread safe. To accomplish this, we store a
* prototype URegularExpression in the object, and then clone it in each
* method. This is required because URegularExpression, unlike
* NSRegularExpression, is stateful, and sharing this state between threads
* would break concurrent calls.
*/
#if HAVE_UREGEX_OPENUTEXT
static URegularExpression *
setupRegex(URegularExpression *regex,
NSString *string,
UText *txt,
NSMatchingOptions options,
NSRange range,
GSRegexBlock block)
{
UErrorCode s = 0;
URegularExpression *r = uregex_clone(regex, &s);
if (options & NSMatchingReportProgress)
{
uregex_setMatchCallback(r, callback, block, &s);
}
UTextInitWithNSString(txt, string);
uregex_setUText(r, txt, &s);
uregex_setRegion(r, range.location, range.location+range.length, &s);
if (options & NSMatchingWithoutAnchoringBounds)
{
uregex_useAnchoringBounds(r, FALSE, &s);
}
if (options & NSMatchingWithTransparentBounds)
{
uregex_useTransparentBounds(r, TRUE, &s);
}
uregex_setTimeLimit(r, _workLimit, &s);
if (U_FAILURE(s))
{
uregex_close(r);
return NULL;
}
return r;
}
#else
static URegularExpression *
setupRegex(URegularExpression *regex,
NSString *string,
unichar *buffer,
int32_t length,
NSMatchingOptions options,
NSRange range,
GSRegexBlock block)
{
UErrorCode s = 0;
URegularExpression *r = uregex_clone(regex, &s);
[string getCharacters: buffer range: NSMakeRange(0, length)];
if (options & NSMatchingReportProgress)
{
uregex_setMatchCallback(r, callback, block, &s);
}
uregex_setText(r, buffer, length, &s);
uregex_setRegion(r, range.location, range.location+range.length, &s);
if (options & NSMatchingWithoutAnchoringBounds)
{
uregex_useAnchoringBounds(r, FALSE, &s);
}
if (options & NSMatchingWithTransparentBounds)
{
uregex_useTransparentBounds(r, TRUE, &s);
}
uregex_setTimeLimit(r, _workLimit, &s);
if (U_FAILURE(s))
{
uregex_close(r);
return NULL;
}
return r;
}
#endif
static uint32_t
prepareResult(NSRegularExpression *regex,
URegularExpression *r,
NSRangePointer ranges,
NSUInteger groups,
UErrorCode *s)
{
uint32_t flags = 0;
NSUInteger i = 0;
for (i = 0; i < groups; i++)
{
NSInteger start = uregex_start(r, i, s);
NSInteger end = uregex_end(r, i, s);
/* The ICU API defines -1 as not found. Convert to
* NSNotFound if applicable.
*/
if (start == -1)
{
start = NSNotFound;
}
if (end == -1)
{
end = NSNotFound;
}
if (end < start)
{
flags |= NSMatchingInternalError;
end = start = NSNotFound;
}
ranges[i] = NSMakeRange(start, end-start);
}
if (uregex_hitEnd(r, s))
{
flags |= NSMatchingHitEnd;
}
if (uregex_requireEnd(r, s))
{
flags |= NSMatchingRequiredEnd;
}
if (0 != *s)
{
flags |= NSMatchingInternalError;
}
return flags;
}
#if HAVE_UREGEX_OPENUTEXT
- (void) enumerateMatchesInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
usingBlock: (GSRegexBlock)block
{
UErrorCode s = 0;
UText txt = UTEXT_INITIALIZER;
BOOL stop = NO;
URegularExpression *r = setupRegex(regex, string, &txt, opts, range, block);
NSUInteger groups = [self numberOfCaptureGroups] + 1;
NSRange ranges[groups];
// Should this throw some kind of exception?
if (NULL == r)
{
return;
}
if (opts & NSMatchingAnchored)
{
if (uregex_lookingAt(r, -1, &s) && (0 == s))
{
// FIXME: Factor all of this out into prepareResult()
uint32_t flags;
NSTextCheckingResult *result;
flags = prepareResult(self, r, ranges, groups, &s);
result = (flags & NSMatchingInternalError) ? nil
: [NSTextCheckingResult
regularExpressionCheckingResultWithRanges: ranges
count: groups
regularExpression: self];
CALL_BLOCK(block, result, flags, &stop);
}
}
else
{
while (!stop && uregex_findNext(r, &s) && (0 == s))
{
uint32_t flags;
NSTextCheckingResult *result;
flags = prepareResult(self, r, ranges, groups, &s);
result = (flags & NSMatchingInternalError) ? nil
: [NSTextCheckingResult
regularExpressionCheckingResultWithRanges: ranges
count: groups
regularExpression: self];
CALL_BLOCK(block, result, flags, &stop);
}
}
if (opts & NSMatchingCompleted)
{
CALL_BLOCK(block, nil, NSMatchingCompleted, &stop);
}
utext_close(&txt);
uregex_close(r);
}
#else
- (void) enumerateMatchesInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
usingBlock: (GSRegexBlock)block
{
UErrorCode s = 0;
BOOL stop = NO;
int32_t length = [string length];
URegularExpression *r;
NSUInteger groups = [self numberOfCaptureGroups] + 1;
NSRange ranges[groups];
TEMP_BUFFER(buffer, length);
r = setupRegex(regex, string, buffer, length, opts, range, block);
// Should this throw some kind of exception?
if (NULL == r)
{
return;
}
if (opts & NSMatchingAnchored)
{
if (uregex_lookingAt(r, -1, &s) && (0 == s))
{
// FIXME: Factor all of this out into prepareResult()
uint32_t flags;
NSTextCheckingResult *result;
flags = prepareResult(self, r, ranges, groups, &s);
result = (flags & NSMatchingInternalError) ? nil
: [NSTextCheckingResult
regularExpressionCheckingResultWithRanges: ranges
count: groups
regularExpression: self];
CALL_BLOCK(block, result, flags, &stop);
}
}
else
{
while (!stop && uregex_findNext(r, &s) && (0 == s))
{
uint32_t flags;
NSTextCheckingResult *result;
flags = prepareResult(self, r, ranges, groups, &s);
result = (flags & NSMatchingInternalError) ? nil
: [NSTextCheckingResult
regularExpressionCheckingResultWithRanges: ranges
count: groups
regularExpression: self];
CALL_BLOCK(block, result, flags, &stop);
}
}
if (opts & NSMatchingCompleted)
{
CALL_BLOCK(block, nil, NSMatchingCompleted, &stop);
}
uregex_close(r);
}
#endif
/* The remaining methods are all meant to be wrappers around the primitive
* method that takes a block argument. Unfortunately, this is not really
* possible when compiling with a compiler that doesn't support blocks.
*/
#if __has_feature(blocks)
- (NSUInteger) numberOfMatchesInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
{
__block NSUInteger count = 0;
opts &= ~NSMatchingReportProgress;
opts &= ~NSMatchingReportCompletion;
GSRegexBlock block =
^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
count++;
};
[self enumerateMatchesInString: string
options: opts
range: range
usingBlock: block];
return count;
}
- (NSTextCheckingResult*) firstMatchInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
{
__block NSTextCheckingResult *r = nil;
opts &= ~NSMatchingReportProgress;
opts &= ~NSMatchingReportCompletion;
GSRegexBlock block =
^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
r = result;
*stop = YES;
};
[self enumerateMatchesInString: string
options: opts
range: range
usingBlock: block];
return r;
}
- (NSArray*) matchesInString: (NSString*)string
options:(NSMatchingOptions)opts
range:(NSRange)range
{
NSMutableArray *array = [NSMutableArray array];
opts &= ~NSMatchingReportProgress;
opts &= ~NSMatchingReportCompletion;
GSRegexBlock block =
^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
[array addObject: result];
};
[self enumerateMatchesInString: string
options: opts
range: range
usingBlock: block];
return array;
}
- (NSRange) rangeOfFirstMatchInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
{
__block NSRange r = {NSNotFound, 0};
opts &= ~NSMatchingReportProgress;
opts &= ~NSMatchingReportCompletion;
GSRegexBlock block =
^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
r = [result range];
*stop = YES;
};
[self enumerateMatchesInString: string
options: opts
range: range
usingBlock: block];
return r;
}
#else
# ifdef __clang__ /* FIXME ... this is blocks specific, not clang specific */
# warning Your compiler does not support blocks. NSRegularExpression will deviate from the documented behaviour when subclassing and any code that subclasses NSRegularExpression may break in unexpected ways. If you must subclass NSRegularExpression, you may want to use a compiler with blocks support.
# warning Your compiler would support blocks if you added -fblocks to your OBJCFLAGS
# endif
#if HAVE_UREGEX_OPENUTEXT
#define FAKE_BLOCK_HACK(failRet, code) \
UErrorCode s = 0;\
UText txt = UTEXT_INITIALIZER;\
BOOL stop = NO;\
URegularExpression *r = setupRegex(regex, string, &txt, opts, range, 0);\
\
if (NULL == r) { return failRet; }\
if (opts & NSMatchingAnchored)\
{\
if (uregex_lookingAt(r, -1, &s) && (0==s))\
{\
code\
}\
}\
else\
{\
while (!stop && uregex_findNext(r, &s) && (s == 0))\
{\
code\
}\
}\
utext_close(&txt);\
uregex_close(r);
#else
#define FAKE_BLOCK_HACK(failRet, code) \
UErrorCode s = 0;\
BOOL stop = NO;\
uint32_t length = [string length];\
URegularExpression *r;\
TEMP_BUFFER(buffer, length);\
r = setupRegex(regex, string, buffer, length, opts, range, 0);\
if (NULL == r) { return failRet; }\
if (opts & NSMatchingAnchored)\
{\
if (uregex_lookingAt(r, -1, &s) && (0==s))\
{\
code\
}\
}\
else\
{\
while (!stop && uregex_findNext(r, &s) && (s == 0))\
{\
code\
}\
}\
uregex_close(r);
#endif
- (NSUInteger) numberOfMatchesInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
{
NSUInteger count = 0;
FAKE_BLOCK_HACK(count,
{
count++;
});
return count;
}
- (NSTextCheckingResult*) firstMatchInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
{
NSTextCheckingResult *result = nil;
NSUInteger groups = [self numberOfCaptureGroups] + 1;
NSRange ranges[groups];
FAKE_BLOCK_HACK(result,
{
uint32_t flags;
flags = prepareResult(self, r, ranges, groups, &s);
result = (flags & NSMatchingInternalError) ? nil
: [NSTextCheckingResult
regularExpressionCheckingResultWithRanges: ranges
count: groups
regularExpression: self];
stop = YES;
});
return result;
}
- (NSArray*) matchesInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
{
NSMutableArray *array = [NSMutableArray array];
NSUInteger groups = [self numberOfCaptureGroups] + 1;
NSRange ranges[groups];
FAKE_BLOCK_HACK(array,
{
NSTextCheckingResult *result = NULL;
uint32_t flags;
flags = prepareResult(self, r, ranges, groups, &s);
result = (flags & NSMatchingInternalError) ? nil
: [NSTextCheckingResult
regularExpressionCheckingResultWithRanges: ranges
count: groups
regularExpression: self];
if (nil != result)
{
[array addObject: result];
}
});
return array;
}
- (NSRange) rangeOfFirstMatchInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
{
NSRange result = {NSNotFound, 0};
FAKE_BLOCK_HACK(result,
{
prepareResult(self, r, &result, 1, &s);
stop = YES;
});
return result;
}
#endif
#if HAVE_UREGEX_OPENUTEXT
- (NSUInteger) replaceMatchesInString: (NSMutableString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
withTemplate: (NSString*)template
{
// FIXME: We're computing a value that is most likely ignored in an
// expensive way.
NSInteger results = [self numberOfMatchesInString: string
options: opts
range: range];
UErrorCode s = 0;
UText txt = UTEXT_INITIALIZER;
UText replacement = UTEXT_INITIALIZER;
GSUTextString *ret = [GSUTextString new];
URegularExpression *r = setupRegex(regex, string, &txt, opts, range, 0);
UText *output = NULL;
UTextInitWithNSString(&replacement, template);
output = uregex_replaceAllUText(r, &replacement, NULL, &s);
if (0 != s)
{
uregex_close(r);
utext_close(&replacement);
utext_close(&txt);
DESTROY(ret);
return 0;
}
utext_clone(&ret->txt, output, TRUE, TRUE, &s);
[string setString: ret];
RELEASE(ret);
uregex_close(r);
utext_close(&txt);
utext_close(output);
utext_close(&replacement);
return results;
}
- (NSString*) stringByReplacingMatchesInString: (NSString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
withTemplate: (NSString*)template
{
UErrorCode s = 0;
UText txt = UTEXT_INITIALIZER;
UText replacement = UTEXT_INITIALIZER;
UText *output = NULL;
GSUTextString *ret = [GSUTextString new];
URegularExpression *r = setupRegex(regex, string, &txt, opts, range, 0);
UTextInitWithNSString(&replacement, template);
output = uregex_replaceAllUText(r, &replacement, NULL, &s);
if (0 != s)
{
uregex_close(r);
utext_close(&replacement);
utext_close(&txt);
DESTROY(ret);
return nil;
}
utext_clone(&ret->txt, output, TRUE, TRUE, &s);
uregex_close(r);
utext_close(&txt);
utext_close(output);
utext_close(&replacement);
return AUTORELEASE(ret);
}
- (NSString*) replacementStringForResult: (NSTextCheckingResult*)result
inString: (NSString*)string
offset: (NSInteger)offset
template: (NSString*)template
{
UErrorCode s = 0;
UText txt = UTEXT_INITIALIZER;
UText replacement = UTEXT_INITIALIZER;
UText *output = NULL;
GSUTextString *ret = [GSUTextString new];
NSRange range = [result range];
URegularExpression *r = setupRegex(regex,
[string substringWithRange: range],
&txt,
0,
NSMakeRange(0, range.length),
0);
UTextInitWithNSString(&replacement, template);
output = uregex_replaceFirstUText(r, &replacement, NULL, &s);
if (0 != s)
{
uregex_close(r);
utext_close(&replacement);
utext_close(&txt);
DESTROY(ret);
return nil;
}
utext_clone(&ret->txt, output, TRUE, TRUE, &s);
uregex_close(r);
utext_close(&txt);
utext_close(output);
utext_close(&replacement);
return AUTORELEASE(ret);
}
#else
- (NSUInteger) replaceMatchesInString: (NSMutableString*)string
options: (NSMatchingOptions)opts
range: (NSRange)range
withTemplate: (NSString*)template
{
// FIXME: We're computing a value that is most likely ignored in an
// expensive way.
NSInteger results = [self numberOfMatchesInString: string
options: opts
range: range];
UErrorCode s = 0;
uint32_t length = [string length];
uint32_t replLength = [template length];
unichar replacement[replLength];
int32_t outLength;
unichar *output;
NSString *out;
URegularExpression *r;
TEMP_BUFFER(buffer, length);
r = setupRegex(regex, string, buffer, length, opts, range, 0);
[template getCharacters: replacement range: NSMakeRange(0, replLength)];
outLength = uregex_replaceAll(r, replacement, replLength, NULL, 0, &s);
s = 0;
output = NSZoneMalloc(0, outLength * sizeof(unichar));
uregex_replaceAll(r, replacement, replLength, output, outLength, &s);
out =
[[NSString alloc] initWithCharactersNoCopy: output
length: outLength
freeWhenDone: YES];