-
Notifications
You must be signed in to change notification settings - Fork 306
/
grep.c
3364 lines (3179 loc) · 102 KB
/
grep.c
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
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1997--2019 The R Core Team
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Pulic License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.R-project.org/Licenses/
*/
/*
Support for UTF-8-encoded strings in non-UTF-8 locales
======================================================
strsplit grep [g]sub [g]regexpr
handle UTF-8 directly if fixed/perl = TRUE, via wchar_t for extended
We currrently translate latin1 strings to the native encoding.
We could use UTF-8 in a non-latin1-locale instead.
*/
/* It is possible to use TRE for fixed = TRUE.
The main benefit would be code simplification: however, the
special-purpose code is substantially faster, so we no longer
plan to do so.
*/
/* PCRE supports only single-byte locales and UTF-8, so we convert
inputs in all other MBCS locales to UTF-8.
In [g]sub and [g]regexpr we need to know match postions in
characters. To avoid yet more cases we handle all MBCS locales in
wchar in ERE for those functions. (Byte positions suffice for
[g]sub(fixed = TRUE), and [g]regexpr needs to convert to char
positions for all MBCSs.)
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
/* interval at which to check interrupts */
#define NINTERRUPT 1000000
/* How many encoding warnings to give */
#define NWARN 5
#include <Defn.h>
#include <Internal.h>
#include <R_ext/RS.h> /* for Calloc/Free */
#include <ctype.h>
#include <wchar.h>
#include <wctype.h> /* for wctrans_t */
/* As from TRE 0.8.0, tre.h replaces regex.h */
#include <tre/tre.h>
#ifdef HAVE_PCRE2
/* PCRE2_CODE_UNIT_WIDTH is defined to 8 via config.h */
# include<pcre2.h>
#else
/*
Some systems might have pcre headers in a subdirectory -- not seen recently.
*/
# ifdef HAVE_PCRE_PCRE_H
# include <pcre/pcre.h>
# else
# include <pcre.h>
# endif
#endif
/*
Default maximum stack size: note this is reserved but not allocated
until needed. The help says 1M suffices, but we found more was
needed for strings around a million bytes.
*/
#define JIT_STACK_MAX 64*1024*1024
/*
This will stay reserved until the end of the session, but at 64MB
that is not an issue -- and most sessions will not use PCRE with
more than 10 strings.
*/
#ifdef HAVE_PCRE2
static pcre2_jit_stack *jit_stack = NULL; // allocated at first use.
#else
static pcre_jit_stack *jit_stack = NULL; // allocated at first use.
#endif
static int jit_stack_size()
{
int stmax = JIT_STACK_MAX;
char *p = getenv("R_PCRE_JIT_STACK_MAXSIZE");
if (p) {
char *endp;
double xdouble = R_strtod(p, &endp);
if (xdouble >= 0 && xdouble <= 1000)
stmax = (int)(xdouble*1024*1024);
else warning ("R_PCRE_JIT_STACK_MAXSIZE invalid and ignored");
}
return stmax;
}
#ifdef HAVE_PCRE2
static void setup_jit(pcre2_match_context *mcontext)
{
if (!jit_stack)
jit_stack = pcre2_jit_stack_create(32*1024, jit_stack_size(), NULL);
if (jit_stack)
pcre2_jit_stack_assign(mcontext, NULL, jit_stack);
}
#else
static void setup_jit(pcre_extra *re_pe)
{
if (!jit_stack)
jit_stack = pcre_jit_stack_alloc(32*1024, jit_stack_size());
if (jit_stack)
pcre_assign_jit_stack(re_pe, NULL, jit_stack);
}
#endif
#ifndef MAX
# define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
#ifndef isRaw
#define isRaw(x) (TYPEOF(x) == RAWSXP)
#endif
/* we allow pat == NULL if the regex cannot be safely expressed
as a string (e.g., when using grepRaw) */
static void NORET reg_report(int rc, regex_t *reg, const char *pat)
{
char errbuf[1001];
tre_regerror(rc, reg, errbuf, 1001);
if (pat)
error(_("invalid regular expression '%s', reason '%s'"), pat, errbuf);
else
error(_("invalid regular expression, reason '%s'"), errbuf);
}
/* FIXME: make more robust, and public */
static SEXP mkCharWLen(const wchar_t *wc, int nc)
{
size_t nb; char *xi; wchar_t *wt;
R_CheckStack2(sizeof(wchar_t)*(nc+1));
wt = (wchar_t *) alloca((nc+1)*sizeof(wchar_t));
wcsncpy(wt, wc, nc); wt[nc] = 0;
nb = wcstoutf8(NULL, wt, INT_MAX);
R_CheckStack2(sizeof(char)*nb);
xi = (char *) alloca(nb*sizeof(char));
wcstoutf8(xi, wt, nb);
return mkCharLenCE(xi, (int)nb-1, CE_UTF8);
}
static SEXP mkCharW(const wchar_t *wc)
{
size_t nb = wcstoutf8(NULL, wc, INT_MAX);
char *xi = (char *) Calloc(nb, char);
SEXP ans;
wcstoutf8(xi, wc, nb);
ans = mkCharCE(xi, CE_UTF8);
Free(xi);
return ans;
}
#ifdef HAVE_PCRE2
static void R_pcre_exec_error(int rc, R_xlen_t i)
{
if (rc >= 0 || rc == PCRE2_ERROR_NOMATCH)
return;
// too much effort to handle long-vector indices, including on Windows
char buf[256];
pcre2_get_error_message(rc, (PCRE2_UCHAR *)buf, sizeof(buf));
warning(_("PCRE error\n\t'%s'\n\tfor element %d"), buf, (int) i + 1);
}
#else
static void R_pcre_exec_error(int rc, R_xlen_t i)
{
if (rc > -2) return;
// too much effort to handle long-vector indices, including on Windows
switch (rc) {
# ifdef PCRE_ERROR_JIT_STACKLIMIT
case PCRE_ERROR_JIT_STACKLIMIT:
warning("JIT stack limit reached in PCRE for element %d",
(int) i + 1);
break;
# endif
case PCRE_ERROR_MATCHLIMIT:
warning("back-tracking limit reached in PCRE for element %d",
(int) i + 1);
break;
case PCRE_ERROR_RECURSIONLIMIT:
warning("recursion limit reached in PCRE for element %d\n consider increasing the C stack size for the R process",
(int) i + 1);
break;
case PCRE_ERROR_INTERNAL:
case PCRE_ERROR_UNKNOWN_OPCODE:
warning("unexpected internal error in PCRE for element %d",
(int) i + 1);
break;
# ifdef PCRE_ERROR_RECURSELOOP
case PCRE_ERROR_RECURSELOOP:
warning("PCRE detected a recursive loop in the pattern for element %d",
(int) i + 1);
break;
# endif
}
}
#endif
/* returns value allocated on R_alloc stack */
static const char *to_native(const char *str, Rboolean use_UTF8)
{
return use_UTF8 ? reEnc(str, CE_UTF8, CE_NATIVE, 1) : str;
}
#ifdef HAVE_PCRE2
# if PCRE2_MAJOR < 10 || (PCRE2_MAJOR == 10 && PCRE2_MINOR < 30)
# define R_PCRE_LIMIT_RECURSION
# endif
#else
# define R_PCRE_LIMIT_RECURSION
#endif
#ifdef R_PCRE_LIMIT_RECURSION
static Rboolean use_recursion_limit(SEXP subject)
{
Rboolean use_limit = FALSE;
if (R_PCRE_limit_recursion == NA_LOGICAL) {
// use recursion limit only on long strings
R_xlen_t i;
R_xlen_t len = XLENGTH(subject);
for (i = 0 ; i < len ; i++)
if (strlen(CHAR(STRING_ELT(subject, i))) >= 1000) {
use_limit = TRUE;
break;
}
} else if (R_PCRE_limit_recursion)
use_limit = TRUE;
return use_limit;
}
static long R_pcre_max_recursions()
{
uintptr_t ans, stack_used, current_frame;
/* Approximate size of stack frame in PCRE match(), actually
platform / compiler dependent. Estimate found at
https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=16757
However, it seems that on Solaris compiled with cc, the size is
much larger (not too surprising as that happens with R's
parser). OTOH, OpenCSW's builds of PCRE are built to use the
heap for recursion.
*/
const uintptr_t recursion_size = 600;
const uintptr_t fallback_used = 10000;
/* This is about 6MB stack, reasonable since stacks are usually >= 8MB
OTOH, the out-of-box limit is 10000000.
*/
const long fallback_limit = 10000;
/* Was PCRE compiled to use stack or heap for recursion? 1=stack */
int use_recursion;
# ifdef HAVE_PCRE2
pcre2_config(PCRE2_CONFIG_STACKRECURSE, &use_recursion);
/* from PCRE2 10.30, use_recursion is always false */
# else
pcre_config(PCRE_CONFIG_STACKRECURSE, &use_recursion);
# endif
if (!use_recursion) return -1L;
if (R_CStackLimit == -1) return fallback_limit;
current_frame = (uintptr_t) &ans;
/* Approximate number of bytes used in the stack, or fallback */
if (R_CStackDir == 1) {
stack_used = (R_CStackStart >= current_frame) ?
R_CStackStart - current_frame : fallback_used;
} else {
stack_used = (current_frame >= R_CStackStart) ?
current_frame - R_CStackStart : fallback_used;
}
if (stack_used >= R_CStackLimit) return 0L;
ans = (R_CStackLimit - stack_used) / recursion_size;
return (long) ((ans <= LONG_MAX) ? ans : -1L);
}
#endif
#ifdef HAVE_PCRE2
static void
R_pcre2_prepare(const char *pattern, SEXP subject, Rboolean use_UTF8,
Rboolean caseless, const unsigned char **tables,
pcre2_code **re, pcre2_match_context **mcontext)
{
int errcode;
PCRE2_SIZE erroffset;
uint32_t options = 0;
pcre2_compile_context *ccontext = NULL;
if (use_UTF8)
options |= PCRE2_UTF | PCRE2_NO_UTF_CHECK;
else {
ccontext = pcre2_compile_context_create(NULL);
/* PCRE2 internal tables by default are only for ASCII characters.
They are needed for lower/upper case distinction and character
classes in non-UTF mode. */
if (!*tables)
*tables = pcre2_maketables(NULL);
pcre2_set_character_tables(ccontext, *tables);
}
if (caseless)
options |= PCRE2_CASELESS;
*re = pcre2_compile((PCRE2_SPTR) pattern, PCRE2_ZERO_TERMINATED, options,
&errcode, &erroffset, ccontext);
if (!*re) {
/* not managing R_alloc stack because this ends in error */
char buf[256];
pcre2_get_error_message(errcode, (PCRE2_UCHAR *)buf, sizeof(buf));
pcre2_compile_context_free(ccontext);
warning(_("PCRE pattern compilation error\n\t'%s'\n\tat '%s'\n"), buf,
to_native(pattern + erroffset, use_UTF8));
error(_("invalid regular expression '%s'"),
to_native(pattern, use_UTF8));
}
pcre2_compile_context_free(ccontext);
*mcontext = pcre2_match_context_create(NULL);
if (R_PCRE_use_JIT) {
int rc = pcre2_jit_compile(*re, 0);
if (rc && rc != PCRE2_ERROR_JIT_BADOPTION) {
/* PCRE2_ERROR_JIT_BADOPTION is returned when JIT support is not
compiled in PCRE2 library */
char buf[256];
pcre2_get_error_message(rc, (PCRE2_UCHAR *)buf, sizeof(buf));
warning(_("PCRE JIT compilation error\n\t'%s'"), buf);
}
if (!rc)
setup_jit(*mcontext);
}
# ifdef R_PCRE_LIMIT_RECURSION
else if (use_recursion_limit(subject))
pcre2_set_recursion_limit(*mcontext, (uint32_t) R_pcre_max_recursions());
/* we could use set_depth_limit() in newer versions, but the memory limit
imposed then depends on the regular expression, and the values have
different meaning from those for recursion limit in versions before
10.30 */
# endif
}
#else /* ! HAVE_PCRE2 */
static void
set_pcre_recursion_limit(pcre_extra **re_pe_ptr, const long limit)
{
if (limit >= 0) {
pcre_extra *re_pe = *re_pe_ptr;
if (!re_pe) {
// this will be freed by pcre_free_study so cannot use Calloc
re_pe = (pcre_extra *) calloc(1, sizeof(pcre_extra));
if (!re_pe) {
warning("allocation failure in set_pcre_recursion_limit");
return;
}
re_pe->flags = PCRE_EXTRA_MATCH_LIMIT_RECURSION;
*re_pe_ptr = re_pe;
} else
re_pe->flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
re_pe->match_limit_recursion = (unsigned long) limit;
}
}
static void
R_pcre_prepare(const char *pattern, SEXP subject, Rboolean use_UTF8,
Rboolean caseless, Rboolean always_study,
const unsigned char **tables, pcre **re, pcre_extra **re_extra)
{
int erroffset;
const char *errorptr;
int options = 0;
R_xlen_t len = XLENGTH(subject);
Rboolean pcre_st = always_study ||
(R_PCRE_study == -2 ? FALSE : len >= R_PCRE_study);
if (use_UTF8)
options |= PCRE_UTF8;
if (caseless)
options |= PCRE_CASELESS;
if (!*tables)
// PCRE docs say this is not needed, but it is on Windows
*tables = pcre_maketables();
*re = pcre_compile(pattern, options, &errorptr, &erroffset, *tables);
if (!*re) {
if (errorptr)
warning(_("PCRE pattern compilation error\n\t'%s'\n\tat '%s'\n"),
errorptr, to_native(pattern + erroffset, use_UTF8));
/* in R 3.6 and earlier strsplit reported "invalid split pattern" */
error(_("invalid regular expression '%s'"),
to_native(pattern, use_UTF8));
}
if (pcre_st) {
*re_extra = pcre_study(*re,
R_PCRE_use_JIT ? PCRE_STUDY_JIT_COMPILE : 0,
&errorptr);
if (errorptr)
warning(_("PCRE pattern study error\n\t'%s'\n"), errorptr);
else if (R_PCRE_use_JIT)
setup_jit(*re_extra);
}
/* FIXME: do not set recursion limit when JIT compilation succeeded? */
if (use_recursion_limit(subject))
set_pcre_recursion_limit(re_extra, R_pcre_max_recursions());
}
#endif
// FIXME: Protect PCRE/PCRE2 data via contexts (as well as other data).
// FIXME: Do not rebuild locale tables repeatedly.
// FIXME: There is no documented way to free locale tables with PCRE2.
// Using free() would not work on Windows if PCRE2 is dynamically
// linked but uses a different C runtime from R.
/* strsplit is going to split the strings in the first argument into
* tokens depending on the second argument. The characters of the second
* argument are used to split the first argument. A list of vectors is
* returned of length equal to the input vector x, each element of the
* list is the collection of splits for the corresponding element of x.
*/
SEXP attribute_hidden do_strsplit(SEXP call, SEXP op, SEXP args, SEXP env)
{
SEXP args0 = args, ans, tok, x;
R_xlen_t i, itok, len, tlen;
size_t j, ntok;
int fixed_opt, perl_opt, useBytes;
char *pt = NULL; wchar_t *wpt = NULL;
const char *buf, *split = "", *bufp;
const unsigned char *tables = NULL;
Rboolean use_UTF8 = FALSE, haveBytes = FALSE;
const void *vmax, *vmax2;
int nwarn = 0;
checkArity(op, args);
x = CAR(args); args = CDR(args);
tok = CAR(args); args = CDR(args);
fixed_opt = asLogical(CAR(args)); args = CDR(args);
perl_opt = asLogical(CAR(args)); args = CDR(args);
useBytes = asLogical(CAR(args));
if (fixed_opt == NA_INTEGER) fixed_opt = 0;
if (perl_opt == NA_INTEGER) perl_opt = 0;
if (useBytes == NA_INTEGER) useBytes = 0;
if (fixed_opt && perl_opt) {
warning(_("argument '%s' will be ignored"), "perl = TRUE");
perl_opt = 0;
}
if (!isString(x) || !isString(tok)) error(_("non-character argument"));
len = XLENGTH(x);
tlen = XLENGTH(tok);
/* treat split = NULL as split = "" */
if (!tlen) { tlen = 1; SETCADR(args0, tok = mkString("")); }
if (!useBytes) {
for (i = 0; i < tlen; i++)
if (IS_BYTES(STRING_ELT(tok, i))) {
haveBytes = TRUE; break;
}
if (!haveBytes)
for (i = 0; i < len; i++)
if (IS_BYTES(STRING_ELT(x, i))) {
haveBytes = TRUE;
break;
}
if (haveBytes) {
useBytes = TRUE;
} else {
if (perl_opt && mbcslocale) use_UTF8 = TRUE;
if (!use_UTF8)
for (i = 0; i < tlen; i++)
if (IS_UTF8(STRING_ELT(tok, i))) {
use_UTF8 = TRUE; break;
}
if (!use_UTF8)
for (i = 0; i < len; i++)
if (IS_UTF8(STRING_ELT(x, i))) {
use_UTF8 = TRUE;
break;
}
}
}
/* group by token for efficiency with PCRE/TRE versions */
PROTECT(ans = allocVector(VECSXP, len));
vmax = vmaxget();
for (itok = 0; itok < tlen; itok++) {
SEXP this = STRING_ELT(tok, itok);
if (this == NA_STRING) { /* NA token doesn't split */
for (i = itok; i < len; i += tlen)
SET_VECTOR_ELT(ans, i, ScalarString(STRING_ELT(x, i)));
continue;
} else if (!CHAR(this)[0]) { /* empty */
vmax2 = vmaxget();
for (i = itok; i < len; i += tlen) {
SEXP t;
if (STRING_ELT(x, i) == NA_STRING) {
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
if (useBytes)
buf = CHAR(STRING_ELT(x, i));
else if (use_UTF8) {
buf = translateCharUTF8(STRING_ELT(x, i));
if (!utf8Valid(buf)) {
if(nwarn++ < NWARN)
warning(_("input string %d is invalid UTF-8"), i+1);
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
} else {
buf = translateChar(STRING_ELT(x, i));
if (mbcslocale && !mbcsValid(buf)) {
if(nwarn++ < NWARN)
warning(_("input string %d is invalid in this locale"), i+1);
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
}
if (!useBytes && (use_UTF8 || mbcslocale) && !strIsASCII(buf)) {
/* split into individual characters (not bytes) */
char bf[20 /* > MB_CUR_MAX */];
const char *p = buf;
size_t used;
mbstate_t mb_st;
ssize_t nt; /* need to check error on size_t */
if (use_UTF8) {
for (ntok = 0; *p; p += used, ntok++)
used = utf8clen(*p);
p = buf;
PROTECT(t = allocVector(STRSXP, ntok));
for (j = 0; j < ntok; j++, p += used) {
used = utf8clen(*p);
memcpy(bf, p, used); bf[used] = '\0';
SET_STRING_ELT(t, j, mkCharCE(bf, CE_UTF8));
}
} else if ((nt = mbstowcs(NULL, buf, 0)) < 0) {
PROTECT(t = ScalarString(NA_STRING));
} else {
ntok = nt;
mbs_init(&mb_st);
PROTECT(t = allocVector(STRSXP, ntok));
for (j = 0; j < ntok; j++, p += used) {
/* This is valid as we have already checked */
used = mbrtowc(NULL, p, MB_CUR_MAX, &mb_st);
memcpy(bf, p, used); bf[used] = '\0';
SET_STRING_ELT(t, j, markKnown(bf, STRING_ELT(x, i)));
}
}
} else {
/* useBytes or ASCII or
single-byte locale and not marked as UTF-8 */
char bf[2];
ntok = strlen(buf);
PROTECT(t = allocVector(STRSXP, ntok));
bf[1] = '\0';
for (j = 0; j < ntok; j++) {
bf[0] = buf[j];
SET_STRING_ELT(t, j, markKnown(bf, STRING_ELT(x, i)));
}
}
SET_VECTOR_ELT(ans, i, t);
UNPROTECT(1);
vmaxset(vmax2);
}
} else if (fixed_opt) {
const char *laststart, *ebuf;
if (useBytes)
split = CHAR(STRING_ELT(tok, itok));
else if (use_UTF8) {
split = translateCharUTF8(STRING_ELT(tok, itok));
if (!utf8Valid(split))
error(_("'split' string %d is invalid UTF-8"), itok+1);
} else {
split = translateChar(STRING_ELT(tok, itok));
if (mbcslocale && !mbcsValid(split))
error(_("'split' string %d is invalid in this locale"),
itok+1);
}
int slen = (int) strlen(split);
vmax2 = vmaxget();
for (i = itok; i < len; i += tlen) {
SEXP t;
if (STRING_ELT(x, i) == NA_STRING) {
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
if (useBytes)
buf = CHAR(STRING_ELT(x, i));
else if (use_UTF8) {
buf = translateCharUTF8(STRING_ELT(x, i));
if (!utf8Valid(buf)) {
if(nwarn++ < NWARN)
warning(_("input string %d is invalid UTF-8"), i+1);
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
} else {
buf = translateChar(STRING_ELT(x, i));
if (mbcslocale && !mbcsValid(buf)) {
if(nwarn++ < NWARN)
warning(_("input string %d is invalid in this locale"), i+1);
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
}
/* find out how many splits there will be */
size_t ntok = 0;
/* This is UTF-8 safe since it compares whole strings */
laststart = buf;
ebuf = buf + strlen(buf);
for (bufp = buf; bufp < ebuf; bufp++) {
if ((slen == 1 && *bufp != *split) ||
(slen > 1 && strncmp(bufp, split, slen))) continue;
ntok++;
bufp += MAX(slen - 1, 0);
laststart = bufp+1;
}
bufp = laststart;
SET_VECTOR_ELT(ans, i,
t = allocVector(STRSXP, ntok + (*bufp ? 1 : 0)));
/* and fill with the splits */
laststart = bufp = buf;
pt = Realloc(pt, strlen(buf)+1, char);
for (size_t j = 0; j < ntok; j++) {
/* This is UTF-8 safe since it compares whole
strings, but <MBCS-FIXME> it would be more
efficient to skip along by chars.
*/
for (; bufp < ebuf; bufp++) {
if ((slen == 1 && *bufp != *split) ||
(slen > 1 && strncmp(bufp, split, slen))) continue;
if (slen) {
strncpy(pt, laststart, bufp - laststart);
pt[bufp - laststart] = '\0';
} else {
pt[0] = *bufp; pt[1] ='\0';
}
bufp += MAX(slen-1, 0);
laststart = bufp+1;
if (use_UTF8)
SET_STRING_ELT(t, j, mkCharCE(pt, CE_UTF8));
else
SET_STRING_ELT(t, j, markKnown(pt, STRING_ELT(x, i)));
break;
}
bufp = laststart;
}
if (*bufp) {
if (use_UTF8)
SET_STRING_ELT(t, ntok, mkCharCE(bufp, CE_UTF8));
else
SET_STRING_ELT(t, ntok, markKnown(bufp, STRING_ELT(x, i)));
}
vmaxset(vmax2);
}
} else if (perl_opt) {
if (useBytes)
split = CHAR(STRING_ELT(tok, itok));
else if (use_UTF8) {
split = translateCharUTF8(STRING_ELT(tok, itok));
if (!utf8Valid(split))
error(_("'split' string %d is invalid UTF-8"), itok+1);
} else {
split = translateChar(STRING_ELT(tok, itok));
if (mbcslocale && !mbcsValid(split))
error(_("'split' string %d is invalid in this locale"), itok+1);
}
#ifdef HAVE_PCRE2
pcre2_code *re = NULL;
pcre2_match_context *mcontext = NULL;
PCRE2_SIZE *ovector = NULL;
uint32_t ovecsize = 10;
R_pcre2_prepare(split, x, use_UTF8, FALSE, &tables, &re, &mcontext);
pcre2_match_data *mdata = pcre2_match_data_create(ovecsize, NULL);
#else
pcre *re_pcre = NULL;
pcre_extra *re_pe = NULL;
int ovecsize = 30;
int ovector[ovecsize];
R_pcre_prepare(split, x, use_UTF8, FALSE, TRUE, &tables, &re_pcre,
&re_pe);
#endif
vmax2 = vmaxget();
for (i = itok; i < len; i += tlen) {
SEXP t;
if (STRING_ELT(x, i) == NA_STRING) {
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
if (useBytes)
buf = CHAR(STRING_ELT(x, i));
else if (use_UTF8) {
buf = translateCharUTF8(STRING_ELT(x, i));
if (!utf8Valid(buf)) {
if(nwarn++ < NWARN)
warning(_("input string %d is invalid UTF-8"), i+1);
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
} else {
buf = translateChar(STRING_ELT(x, i));
if (mbcslocale && !mbcsValid(buf)) {
if(nwarn++ < NWARN)
warning(_("input string %d is invalid in this locale"), i+1);
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
}
/* find out how many splits there will be */
ntok = 0;
bufp = buf;
if (*bufp) {
int rc;
#ifdef HAVE_PCRE2
while((rc = pcre2_match(re, (PCRE2_SPTR) bufp,
PCRE2_ZERO_TERMINATED,
0, 0, mdata, mcontext)) >= 0) {
ovector = pcre2_get_ovector_pointer(mdata);
#else
while((rc = pcre_exec(re_pcre, re_pe, bufp,
(int) strlen(bufp),
0, 0, ovector, ovecsize)) >= 0) {
#endif
/* Empty matches get the next char, so move by one. */
bufp += MAX(ovector[1], 1);
ntok++;
if (*bufp == '\0')
break;
}
R_pcre_exec_error(rc, i);
}
SET_VECTOR_ELT(ans, i,
t = allocVector(STRSXP, ntok + (*bufp ? 1 : 0)));
/* and fill with the splits */
bufp = buf;
pt = Realloc(pt, strlen(buf)+1, char);
for (j = 0; j < ntok; j++) {
#ifdef HAVE_PCRE2
int rc = pcre2_match(re, (PCRE2_SPTR) bufp,
PCRE2_ZERO_TERMINATED,
0, 0, mdata, mcontext);
#else
int rc = pcre_exec(re_pcre, re_pe, bufp,
(int) strlen(bufp), 0, 0,
ovector, ovecsize);
#endif
R_pcre_exec_error(rc, i);
if (ovector[1] > 0) {
/* Match was non-empty. */
if (ovector[0] > 0)
strncpy(pt, bufp, ovector[0]);
pt[ovector[0]] = '\0';
bufp += ovector[1];
} else {
/* Match was empty. */
pt[0] = *bufp;
pt[1] = '\0';
bufp++;
}
if (use_UTF8)
SET_STRING_ELT(t, j, mkCharCE(pt, CE_UTF8));
else
SET_STRING_ELT(t, j, markKnown(pt, STRING_ELT(x, i)));
}
if (*bufp) {
if (use_UTF8)
SET_STRING_ELT(t, ntok, mkCharCE(bufp, CE_UTF8));
else
SET_STRING_ELT(t, ntok, markKnown(bufp, STRING_ELT(x, i)));
}
vmaxset(vmax2);
}
#ifdef HAVE_PCRE2
pcre2_match_data_free(mdata);
pcre2_code_free(re);
pcre2_match_context_free(mcontext);
#else
if(re_pe) pcre_free_study(re_pe);
pcre_free(re_pcre);
#endif
} else if (!useBytes && use_UTF8) { /* ERE in wchar_t */
regex_t reg;
regmatch_t regmatch[1];
int rc;
int cflags = REG_EXTENDED;
const wchar_t *wbuf, *wbufp, *wsplit;
/* Careful: need to distinguish empty (rm_eo == 0) from
non-empty (rm_eo > 0) matches. In the former case, the
token extracted is the next character. Otherwise, it is
everything before the start of the match, which may be
the empty string (not a ``token'' in the strict sense).
*/
wsplit = wtransChar(STRING_ELT(tok, itok));
if ((rc = tre_regwcomp(®, wsplit, cflags)))
reg_report(rc, ®, translateChar(STRING_ELT(tok, itok)));
vmax2 = vmaxget();
for (i = itok; i < len; i += tlen) {
SEXP t;
if (STRING_ELT(x, i) == NA_STRING) {
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
wbuf = wtransChar(STRING_ELT(x, i));
/* find out how many splits there will be */
ntok = 0;
wbufp = wbuf;
if (*wbufp) {
while(tre_regwexec(®, wbufp, 1, regmatch, 0) == 0) {
/* Empty matches get the next char, so move by one. */
wbufp += MAX(regmatch[0].rm_eo, 1);
ntok++;
if (!*wbufp) break;
}
}
SET_VECTOR_ELT(ans, i,
t = allocVector(STRSXP, ntok + (*wbufp ? 1 : 0)));
/* and fill with the splits */
wbufp = wbuf;
wpt = Realloc(wpt, wcslen(wbuf)+1, wchar_t);
for (j = 0; j < ntok; j++) {
tre_regwexec(®, wbufp, 1, regmatch, 0);
if (regmatch[0].rm_eo > 0) {
/* Match was non-empty. */
if (regmatch[0].rm_so > 0)
wcsncpy(wpt, wbufp, regmatch[0].rm_so);
wpt[regmatch[0].rm_so] = 0;
wbufp += regmatch[0].rm_eo;
} else {
/* Match was empty. */
wpt[0] = *wbufp;
wpt[1] = 0;
wbufp++;
}
SET_STRING_ELT(t, j,
mkCharWLen(wpt, regmatch[0].rm_so));
}
if (*wbufp)
SET_STRING_ELT(t, ntok,
mkCharWLen(wbufp, (int) wcslen(wbufp)));
vmaxset(vmax2);
}
tre_regfree(®);
} else { /* ERE in normal chars -- single byte or MBCS */
regex_t reg;
regmatch_t regmatch[1];
int rc;
int cflags = REG_EXTENDED;
/* Careful: need to distinguish empty (rm_eo == 0) from
non-empty (rm_eo > 0) matches. In the former case, the
token extracted is the next character. Otherwise, it is
everything before the start of the match, which may be
the empty string (not a ``token'' in the strict sense).
*/
/* never use_UTF8 */
if (useBytes)
split = CHAR(STRING_ELT(tok, itok));
else {
split = translateChar(STRING_ELT(tok, itok));
if (mbcslocale && !mbcsValid(split))
error(_("'split' string %d is invalid in this locale"), itok+1);
}
if ((rc = tre_regcomp(®, split, cflags)))
reg_report(rc, ®, split);
vmax2 = vmaxget();
for (i = itok; i < len; i += tlen) {
SEXP t;
if (STRING_ELT(x, i) == NA_STRING) {
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
/* never use_UTF8 */
if (useBytes)
buf = CHAR(STRING_ELT(x, i));
else {
buf = translateChar(STRING_ELT(x, i));
if (mbcslocale && !mbcsValid(buf)) {
if(nwarn++ < NWARN)
warning(_("input string %d is invalid in this locale"), i+1);
SET_VECTOR_ELT(ans, i, ScalarString(NA_STRING));
continue;
}
}
/* find out how many splits there will be */
ntok = 0;
bufp = buf;
if (*bufp) {
while((rc = tre_regexec(®, bufp, 1, regmatch, 0)) == 0) {
/* Empty matches get the next char, so move by one. */
bufp += MAX(regmatch[0].rm_eo, 1);
ntok++;
if (*bufp == '\0') break;
}
// AFAICS the only possible error report is REG_ESPACE
if (rc == REG_ESPACE)
warning("Out-of-memory error in regexp matching for element %d",
(int) i + 1);
}
SET_VECTOR_ELT(ans, i,
t = allocVector(STRSXP, ntok + (*bufp ? 1 : 0)));
/* and fill with the splits */
bufp = buf;
pt = Realloc(pt, strlen(buf)+1, char);
for (j = 0; j < ntok; j++) {
int rc = tre_regexec(®, bufp, 1, regmatch, 0);
// AFAICS the only possible error report is REG_ESPACE
if (rc == REG_ESPACE)
warning("Out-of-memory error in regexp matching for element %d",
(int) i + 1);
if (regmatch[0].rm_eo > 0) {
/* Match was non-empty. */
if (regmatch[0].rm_so > 0)
strncpy(pt, bufp, regmatch[0].rm_so);
pt[regmatch[0].rm_so] = '\0';
bufp += regmatch[0].rm_eo;
} else {
/* Match was empty. */
pt[0] = *bufp;
pt[1] = '\0';
bufp++;
}
SET_STRING_ELT(t, j, markKnown(pt, STRING_ELT(x, i)));
}
if (*bufp)
SET_STRING_ELT(t, ntok, markKnown(bufp, STRING_ELT(x, i)));
vmaxset(vmax2);
}
tre_regfree(®);
}
vmaxset(vmax);
}
if (getAttrib(x, R_NamesSymbol) != R_NilValue)
namesgets(ans, getAttrib(x, R_NamesSymbol));
UNPROTECT(1);
Free(pt); Free(wpt);
#ifdef HAVE_PCRE2
if (tables) free((void *)tables);
/* new PCRE2 will have pcre2_maketables_free() */
#else
if (tables) pcre_free((void *)tables);
#endif
return ans;
}
/* Used by grep[l] and [g]regexpr, with return value the match
position in characters */
/* This could be faster for plen > 1, but uses in R are for small strings */
static int fgrep_one(const char *pat, const char *target,
Rboolean useBytes, Rboolean use_UTF8, int *next)
{
int plen = (int) strlen(pat), len = (int) strlen(target);
int i = -1;
const char *p;
if (plen == 0) {
if (next != NULL) *next = 1;
return 0;
}
if (plen == 1 && (useBytes || !(mbcslocale || use_UTF8))) {
/* a single byte is a common case */
for (i = 0, p = target; *p; p++, i++)
if (*p == pat[0]) {
if (next != NULL) *next = i + 1;
return i;
}
return -1;