Coverage Report

Created: 2026-11-30 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-source/src/main/agrep.c
Line
Count
Source
1
/*
2
 *  R : A Computer Language for Statistical Data Analysis
3
 *  Copyright (C) 2002--2023  The R Core Team
4
 *
5
 *  This program is free software; you can redistribute it and/or modify
6
 *  it under the terms of the GNU General Pulic License as published by
7
 *  the Free Software Foundation; either version 2 of the License, or
8
 *  (at your option) any later version.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, a copy is available at
17
 *  https://www.R-project.org/Licenses/
18
 */
19
20
/* This at times needed to be separate from grep.c, as TRE has a
21
   conflicting regcomp and the two headers cannot both be included in
22
   one file
23
*/
24
25
#ifdef HAVE_CONFIG_H
26
# include <config.h>
27
#endif
28
29
#include <Defn.h>
30
#include <Internal.h>
31
32
/* This is remapped */
33
#undef pmatch
34
35
/* interval at which to check interrupts */
36
/*   if re-enabling, consider a power of two */
37
/* #define NINTERRUPT 1000000 */
38
39
#include <R_ext/RS.h>   /* for R_Calloc/R_Free */
40
41
#include <wchar.h>
42
#include <tre/tre.h>
43
44
static void
45
amatch_regaparams(regaparams_t *params, int patlen,
46
      double *bounds, int *costs)
47
0
{
48
0
    int cost, max_cost, warn = 0;
49
0
    double bound;
50
51
0
    cost = params->cost_ins = max_cost = costs[0];
52
0
    cost = params->cost_del = costs[1];
53
0
    if(cost > max_cost) max_cost = cost;
54
0
    cost = params->cost_subst = costs[2];
55
0
    if(cost > max_cost) max_cost = cost;
56
0
    bound = bounds[0];
57
0
    if(ISNA(bound)) {
58
0
  params->max_cost = INT_MAX;
59
0
    } else {
60
0
  if(bound < 1) bound *= (patlen * max_cost);
61
0
  params->max_cost = IntegerFromReal(ceil(bound), &warn);
62
0
  CoercionWarning(warn);
63
0
    }
64
0
    bound = bounds[1];
65
0
    if(ISNA(bound)) {
66
0
  params->max_del = INT_MAX;
67
0
    } else {
68
0
  if(bound < 1) bound *= patlen;
69
0
  params->max_del = IntegerFromReal(ceil(bound), &warn);
70
0
  CoercionWarning(warn);
71
0
    }
72
0
    bound = bounds[2];
73
0
    if(ISNA(bound)) {
74
0
  params->max_ins = INT_MAX;
75
0
    } else {
76
0
  if(bound < 1) bound *= patlen;
77
0
  params->max_ins = IntegerFromReal(ceil(bound), &warn);
78
0
  CoercionWarning(warn);
79
0
    }
80
0
    bound = bounds[3];
81
0
    if(ISNA(bound)) {
82
0
  params->max_subst = INT_MAX;
83
0
    } else {
84
0
  if(bound < 1) bound *= patlen;
85
0
  params->max_subst = IntegerFromReal(ceil(bound), &warn);
86
0
  CoercionWarning(warn);
87
0
    }
88
0
    bound = bounds[4];
89
0
    if(ISNA(bound)) {
90
0
  params->max_err = INT_MAX;
91
0
    } else {
92
0
  if(bound < 1) bound *= patlen;
93
0
  params->max_err = IntegerFromReal(ceil(bound), &warn);
94
0
  CoercionWarning(warn);
95
0
    }
96
0
}
97
98
attribute_hidden SEXP do_agrep(SEXP call, SEXP op, SEXP args, SEXP env)
99
0
{
100
0
    SEXP pat, vec, ind, ans;
101
0
    SEXP opt_costs, opt_bounds;
102
0
    int opt_icase, opt_value, opt_fixed, useBytes;
103
0
    R_xlen_t i, j, n;
104
0
    int nmatches, patlen;
105
0
    bool useWC = false;
106
0
    const void *vmax = NULL;
107
108
0
    regex_t reg;
109
0
    regaparams_t params;
110
0
    regamatch_t match;
111
0
    int rc, cflags = REG_EXTENDED | REG_NOSUB;
112
113
0
    checkArity(op, args);
114
0
    pat = CAR(args); args = CDR(args);
115
0
    vec = CAR(args); args = CDR(args);
116
0
    opt_icase = asLogical(CAR(args)); args = CDR(args);
117
0
    opt_value = asLogical(CAR(args)); args = CDR(args);
118
0
    opt_costs = CAR(args); args = CDR(args);
119
0
    opt_bounds = CAR(args); args = CDR(args);
120
0
    useBytes = asLogical(CAR(args));
121
0
    args = CDR(args);
122
0
    opt_fixed = asLogical(CAR(args));
123
124
0
    if(opt_icase == NA_INTEGER) opt_icase = 0;
125
0
    if(opt_value == NA_INTEGER) opt_value = 0;
126
0
    if(useBytes == NA_INTEGER) useBytes = 0;
127
0
    if(opt_fixed == NA_INTEGER) opt_fixed = 1;
128
129
0
    if(opt_fixed) cflags |= REG_LITERAL;
130
131
0
    if(!isString(pat) || LENGTH(pat) < 1)
132
0
  error(_("invalid '%s' argument"), "pattern");
133
0
    if(LENGTH(pat) > 1)
134
0
  warning(_("argument '%s' has length > 1 and only the first element will be used"), "pattern");
135
136
0
    if(!isString(vec)) error(_("invalid '%s' argument"), "x");
137
138
0
    if(opt_icase) cflags |= REG_ICASE;
139
140
0
    n = XLENGTH(vec);
141
0
    if(!useBytes) {
142
0
  bool haveBytes = IS_BYTES(STRING_ELT(pat, 0));
143
0
  if(!haveBytes)
144
0
      for (i = 0; i < n; i++)
145
0
    if(IS_BYTES(STRING_ELT(vec, i))) {
146
0
        haveBytes = true;
147
0
        break;
148
0
    }
149
0
  if(haveBytes) useBytes = true;
150
0
    }
151
0
    if(!useBytes) {
152
0
  useWC = !IS_ASCII(STRING_ELT(pat, 0));
153
0
  if(!useWC) {
154
0
      for (i = 0 ; i < n ; i++) {
155
0
    if(STRING_ELT(vec, i) == NA_STRING) continue;
156
0
    if(!IS_ASCII(STRING_ELT(vec, i))) {
157
0
        useWC = true;
158
0
        break;
159
0
    }
160
0
      }
161
0
  }
162
0
    }
163
164
0
    if(STRING_ELT(pat, 0) == NA_STRING) {
165
0
  if(opt_value) {
166
0
      PROTECT(ans = allocVector(STRSXP, n));
167
0
      for(i = 0; i < n; i++)
168
0
    SET_STRING_ELT(ans, i, NA_STRING);
169
0
      SEXP nms = getAttrib(vec, R_NamesSymbol);
170
0
      if(!isNull(nms))
171
0
    setAttrib(ans, R_NamesSymbol, nms);
172
0
  } else {
173
0
      PROTECT(ans = allocVector(INTSXP, n));
174
0
      for(i = 0; i < n; i++)
175
0
    INTEGER(ans)[i] = NA_INTEGER;
176
0
  }
177
0
  UNPROTECT(1);
178
0
  return ans;
179
0
    }
180
181
0
    SEXP s_nchar = install("nchar");
182
0
    if(useBytes)
183
0
  PROTECT(call = lang3(s_nchar, pat,
184
0
           ScalarString(mkChar("bytes"))));
185
0
    else
186
0
  PROTECT(call = lang3(s_nchar, pat,
187
0
           ScalarString(mkChar("chars"))));
188
0
    patlen = asInteger(eval(call, env));
189
0
    UNPROTECT(1);
190
0
    if(!patlen)
191
0
  error(_("'pattern' must be a non-empty character string"));
192
193
    /* wtransChar and translateChar can R_alloc */
194
0
    vmax = vmaxget();
195
0
    if(useBytes)
196
0
  rc = tre_regcompb(&reg, CHAR(STRING_ELT(pat, 0)), cflags);
197
0
    else if(useWC)
198
0
  rc = tre_regwcomp(&reg, wtransChar(STRING_ELT(pat, 0)), cflags);
199
0
    else {
200
0
  const char *spat = translateChar(STRING_ELT(pat, 0));
201
0
  if(mbcslocale && !mbcsValid(spat))
202
0
      error(_("regular expression is invalid in this locale"));
203
0
  rc = tre_regcomp(&reg, spat, cflags);
204
0
    }
205
0
    if(rc) {
206
0
  char errbuf[1001];
207
0
  tre_regerror(rc, &reg, errbuf, 1001);
208
0
  error(_("regcomp error:  '%s'"), errbuf);
209
0
    }
210
211
0
    tre_regaparams_default(&params);
212
0
    amatch_regaparams(&params, patlen,
213
0
          REAL(opt_bounds), INTEGER(opt_costs));
214
215
    /* Matching. */
216
0
    n = LENGTH(vec);
217
0
    PROTECT(ind = allocVector(LGLSXP, n));
218
0
    nmatches = 0;
219
0
    for (i = 0 ; i < n ; i++) {
220
//  if ((i+1) % NINTERRUPT == 0) R_CheckUserInterrupt();
221
0
  if(STRING_ELT(vec, i) == NA_STRING) {
222
0
      LOGICAL(ind)[i] = 0;
223
0
      continue;
224
0
  }
225
  /* Perform match. */
226
  /* undocumented, must be zeroed */
227
0
  memset(&match, 0, sizeof(match));
228
0
  if(useBytes)
229
0
      rc = tre_regaexecb(&reg,
230
0
             CHAR(STRING_ELT(vec, i)),
231
0
             &match, params, 0);
232
0
  else if(useWC) {
233
0
      rc = tre_regawexec(&reg,
234
0
             wtransChar(STRING_ELT(vec, i)),
235
0
             &match, params, 0);
236
0
      vmaxset(vmax);
237
0
  } else {
238
0
      const char *s = translateChar(STRING_ELT(vec, i));
239
0
      if(mbcslocale && !mbcsValid(s))
240
0
    error(_("input string %lld is invalid in this locale"),
241
0
          (long long)i+1);
242
0
      rc = tre_regaexec(&reg, s, &match, params, 0);
243
0
      vmaxset(vmax);
244
0
  }
245
0
  if(rc == REG_OK) {
246
0
      LOGICAL(ind)[i] = 1;
247
0
      nmatches++;
248
0
  } else LOGICAL(ind)[i] = 0;
249
0
    }
250
0
    tre_regfree(&reg);
251
252
0
    if (PRIMVAL(op)) {/* agrepl case */
253
0
  UNPROTECT(1);
254
0
  return ind;
255
0
    }
256
257
0
    if(opt_value) {
258
0
  PROTECT(ans = allocVector(STRSXP, nmatches));
259
0
  SEXP nmold = getAttrib(vec, R_NamesSymbol), nm;
260
0
  for (j = i = 0 ; i < n ; i++) {
261
0
      if(LOGICAL(ind)[i])
262
0
    SET_STRING_ELT(ans, j++, STRING_ELT(vec, i));
263
0
  }
264
  /* copy across names and subset */
265
0
  if(!isNull(nmold)) {
266
0
      nm = allocVector(STRSXP, nmatches);
267
0
      for (i = 0, j = 0; i < n ; i++)
268
0
    if(LOGICAL(ind)[i])
269
0
        SET_STRING_ELT(nm, j++, STRING_ELT(nmold, i));
270
0
      setAttrib(ans, R_NamesSymbol, nm);
271
0
  }
272
0
    }
273
0
#ifdef LONG_VECTOR_SUPPORT
274
0
    else if (n > INT_MAX) {
275
0
  PROTECT(ans = allocVector(REALSXP, nmatches));
276
0
  for (j = i = 0 ; i < n ; i++)
277
0
      if(LOGICAL(ind)[i] == 1)
278
0
    REAL(ans)[j++] = (double)(i + 1);
279
0
    }
280
0
#endif
281
0
    else {
282
0
  PROTECT(ans = allocVector(INTSXP, nmatches));
283
0
  for (j = i = 0 ; i < n ; i++)
284
0
      if(LOGICAL(ind)[i] == 1)
285
0
    INTEGER(ans)[j++] = (int)(i + 1);
286
0
    }
287
288
0
    UNPROTECT(2);
289
0
    return ans;
290
0
}
291
292
0
#define ANS(I, J)   REAL(ans)[I + J * nx]
293
0
#define COUNTS(I, J, K)   INTEGER(counts)[I + J * nx + K * nxy]
294
295
0
#define MAT(X, I, J)    X[I + (J) * nr]
296
297
static SEXP
298
adist_full(SEXP x, SEXP y, double *costs, bool opt_counts)
299
0
{
300
0
    SEXP ans, counts, trafos = R_NilValue /* -Wall */, dimnames, names;
301
0
    double cost_ins, cost_del, cost_sub;
302
0
    double *dists, d, d_ins, d_del, d_sub;
303
0
    char *paths = NULL, p, *buf = NULL;
304
0
    int i, j, k, l, m, nx, ny, nxy, *xi, *yj, nxi, nyj, nr, nc, nz;
305
0
    int nins, ndel, nsub, buflen = 100, need;
306
307
0
    counts = R_NilValue;  /* -Wall */
308
309
0
    nx = LENGTH(x);
310
0
    ny = LENGTH(y);
311
0
    nxy = nx * ny;
312
313
0
    cost_ins = costs[0];
314
0
    cost_del = costs[1];
315
0
    cost_sub = costs[2];
316
317
0
    PROTECT(ans = allocMatrix(REALSXP, nx, ny));
318
0
    if(opt_counts) {
319
0
  PROTECT(counts = alloc3DArray(INTSXP, nx, ny, 3));
320
0
  PROTECT(trafos = allocMatrix(STRSXP, nx, ny));
321
0
  buf = R_Calloc(buflen, char);
322
0
    }
323
324
0
    for(i = 0; i < nx; i++) {
325
0
  nxi = LENGTH(VECTOR_ELT(x, i));
326
0
  xi = INTEGER(VECTOR_ELT(x, i));
327
0
  if(nxi && (xi[0] == NA_INTEGER)) {
328
0
      for(j = 0; j < ny; j++) {
329
0
    ANS(i, j) = NA_REAL;
330
0
    if(opt_counts) {
331
0
        for(m = 0; m < 3; m++) {
332
0
      COUNTS(i, j, m) = NA_INTEGER;
333
0
        }
334
0
    }
335
0
      }
336
0
  } else {
337
0
      for(j = 0; j < ny; j++) {
338
0
    nyj = LENGTH(VECTOR_ELT(y, j));
339
0
    yj = INTEGER(VECTOR_ELT(y, j));
340
0
    if(nyj && (yj[0] == NA_INTEGER)) {
341
0
        ANS(i, j) = NA_REAL;
342
0
        if(opt_counts) {
343
0
      for(m = 0; m < 3; m++) {
344
0
          COUNTS(i, j, m) = NA_INTEGER;
345
0
      }
346
0
        }
347
0
    }
348
0
    else {
349
        /* Determine operation-weighted edit distance via
350
         * straightforward dynamic programming.
351
         */
352
0
        nr = nxi + 1;
353
0
        nc = nyj + 1;
354
0
        dists = R_Calloc(nr * nc, double);
355
0
        MAT(dists, 0, 0) = 0;
356
0
        for(k = 1; k < nr; k++)
357
0
      MAT(dists, k, 0) = k * cost_del;
358
0
        for(l = 1; l < nc; l++)
359
0
      MAT(dists, 0, l) = l * cost_ins;
360
0
        if(opt_counts) {
361
0
      paths = R_Calloc(nr * nc, char);
362
0
      for(k = 1; k < nr; k++)
363
0
          MAT(paths, k, 0) = 'D';
364
0
      for(l = 1; l < nc; l++)
365
0
          MAT(paths, 0, l) = 'I';
366
0
        }
367
0
        for(k = 1; k < nr; k++) {
368
0
      for(l = 1; l < nc; l++) {
369
0
          if(xi[k - 1] == yj[l - 1]) {
370
0
        MAT(dists, k, l) =
371
0
            MAT(dists, k - 1, l - 1);
372
0
        if(opt_counts)
373
0
            MAT(paths, k, l) = 'M';
374
0
          } else {
375
0
        d_ins = MAT(dists, k, l - 1) + cost_ins;
376
0
        d_del = MAT(dists, k - 1, l) + cost_del;
377
0
        d_sub = MAT(dists, k - 1, l - 1) + cost_sub;
378
0
        if(opt_counts) {
379
0
            if(d_ins <= d_del) {
380
0
          d = d_ins;
381
0
          p = 'I';
382
0
            } else {
383
0
          d = d_del;
384
0
          p = 'D';
385
0
            }
386
0
            if(d_sub < d) {
387
0
          d = d_sub;
388
0
          p = 'S';
389
0
            }
390
0
            MAT(paths, k, l) = p;
391
0
        } else {
392
0
            d = fmin(fmin(d_ins, d_del), d_sub);
393
0
        }
394
0
        MAT(dists, k, l) = d;
395
0
          }
396
0
      }
397
0
        }
398
0
        ANS(i, j) = MAT(dists, nxi, nyj);
399
0
        if(opt_counts) {
400
0
      if(!R_finite(ANS(i, j))) {
401
0
          for(m = 0; m < 3; m++) {
402
0
        COUNTS(i, j, m) = NA_INTEGER;
403
0
          }
404
0
          SET_STRING_ELT(trafos, i + nx * j, NA_STRING);
405
0
      } else {
406
0
          nins = ndel = nsub = 0;
407
0
          k = nxi; l = nyj; m = k + l; nz = m;
408
0
          need = 2 * m + 1;
409
0
          if(buflen < need) {
410
0
        buf = R_Realloc(buf, need , char);
411
0
        buflen = need;
412
0
          }
413
          /* Need to read backwards and fill forwards. */
414
0
          while((k > 0) || (l > 0)) {
415
0
        p = MAT(paths, k, l);
416
0
        if(p == 'I') {
417
0
            nins++;
418
0
            l--;
419
0
        } else if(p == 'D') {
420
0
            ndel++;
421
0
            k--;
422
0
        } else {
423
0
            if(p == 'S')
424
0
          nsub++;
425
0
            k--;
426
0
            l--;
427
0
        }
428
0
        buf[m] = p;
429
0
        m++;
430
0
          }
431
          /* Now reverse the transcript. */
432
0
          for(k = 0, l = --m; l >= nz; k++, l--)
433
0
        buf[k] = buf[l];
434
0
          buf[k] = '\0';
435
0
          COUNTS(i, j, 0) = nins;
436
0
          COUNTS(i, j, 1) = ndel;
437
0
          COUNTS(i, j, 2) = nsub;
438
0
          SET_STRING_ELT(trafos, i + nx * j, mkChar(buf));
439
0
      }
440
0
      R_Free(paths);
441
0
        }
442
0
        R_Free(dists);
443
0
    }
444
0
      }
445
0
  }
446
0
    }
447
448
0
    PROTECT(x = getAttrib(x, R_NamesSymbol));
449
0
    PROTECT(y = getAttrib(y, R_NamesSymbol));
450
0
    if(!isNull(x) || !isNull(y)) {
451
0
  PROTECT(dimnames = allocVector(VECSXP, 2));
452
0
  SET_VECTOR_ELT(dimnames, 0, x);
453
0
  SET_VECTOR_ELT(dimnames, 1, y);
454
0
  setAttrib(ans, R_DimNamesSymbol, dimnames);
455
0
  UNPROTECT(1); /* dimnames */
456
0
    }
457
458
0
    if(opt_counts) {
459
0
  R_Free(buf);
460
0
  PROTECT(dimnames = allocVector(VECSXP, 3));
461
0
  PROTECT(names = allocVector(STRSXP, 3));
462
0
  SET_STRING_ELT(names, 0, mkChar("ins"));
463
0
  SET_STRING_ELT(names, 1, mkChar("del"));
464
0
  SET_STRING_ELT(names, 2, mkChar("sub"));
465
0
  SET_VECTOR_ELT(dimnames, 0, x);
466
0
  SET_VECTOR_ELT(dimnames, 1, y);
467
0
  SET_VECTOR_ELT(dimnames, 2, names);
468
0
  setAttrib(counts, R_DimNamesSymbol, dimnames);
469
0
  setAttrib(ans, install("counts"), counts);
470
0
  UNPROTECT(2); /* names, dimnames */
471
0
  if(!isNull(x) || !isNull(y)) {
472
0
      PROTECT(dimnames = allocVector(VECSXP, 2));
473
0
      SET_VECTOR_ELT(dimnames, 0, x);
474
0
      SET_VECTOR_ELT(dimnames, 1, y);
475
0
      setAttrib(trafos, R_DimNamesSymbol, dimnames);
476
0
      UNPROTECT(1); /* dimnames */
477
0
  }
478
0
  setAttrib(ans, install("trafos"), trafos);
479
0
  UNPROTECT(2); /* trafos, counts */
480
0
    }
481
482
0
    UNPROTECT(3); /* y, x, ans */
483
0
    return ans;
484
0
}
485
486
0
#define OFFSETS(I, J, K)  INTEGER(offsets)[I + J * nx + K * nxy]
487
488
attribute_hidden SEXP do_adist(SEXP call, SEXP op, SEXP args, SEXP env)
489
0
{
490
0
    SEXP x, y;
491
0
    SEXP ans, counts, offsets, dimnames, names, elt;
492
0
    SEXP opt_costs;
493
0
    bool opt_fixed, opt_partial, opt_counts, opt_icase, useBytes;
494
0
    int i = 0, j = 0, m, nx, ny, nxy;
495
0
    const char *s, *t;
496
0
    const void *vmax = NULL;
497
498
0
    bool haveBytes, useWC = false;
499
500
0
    regex_t reg;
501
0
    regaparams_t params;
502
0
    regamatch_t match;
503
0
    size_t nmatch = 0 /* -Wall */;
504
0
    regmatch_t *pmatch = NULL; /* -Wall */
505
506
0
    int rc, cflags = REG_EXTENDED;
507
508
0
    checkArity(op, args);
509
0
    x = CAR(args); args = CDR(args);
510
0
    y = CAR(args); args = CDR(args);
511
0
    opt_costs = CAR(args); args = CDR(args);
512
0
    opt_counts = asBool2(CAR(args), call); args = CDR(args);
513
0
    opt_fixed = asBool2(CAR(args), call); args = CDR(args);
514
0
    opt_partial = asBool2(CAR(args), call); args = CDR(args);
515
0
    opt_icase = asBool2(CAR(args), call); args = CDR(args);
516
0
    useBytes = asBool2(CAR(args), call);
517
518
0
    if(opt_counts == NA_INTEGER) opt_counts = 0;
519
0
    if(opt_fixed == NA_INTEGER) opt_fixed = 1;
520
0
    if(opt_partial == NA_INTEGER) opt_partial = 0;
521
0
    if(opt_icase == NA_INTEGER) opt_icase = 0;
522
0
    if(useBytes == NA_INTEGER) useBytes = 0;
523
524
0
    if(opt_fixed) cflags |= REG_LITERAL;
525
0
    if(opt_icase) cflags |= REG_ICASE;
526
527
0
    if(!opt_fixed && !opt_partial) {
528
0
  warning(_("argument '%s' will be ignored"), "partial = FALSE");
529
0
    }
530
531
0
    if(!opt_partial)
532
0
  return(adist_full(x, y, REAL(opt_costs), opt_counts));
533
534
0
    counts = R_NilValue;  /* -Wall */
535
0
    offsets = R_NilValue; /* -Wall */
536
537
0
    if(!opt_counts) cflags |= REG_NOSUB;
538
539
0
    nx = length(x);
540
0
    ny = length(y);
541
0
    nxy = nx * ny;
542
543
0
    if(!useBytes) {
544
0
  haveBytes = false;
545
0
  for(i = 0; i < nx; i++) {
546
0
      if(IS_BYTES(STRING_ELT(x, i))) {
547
0
    haveBytes = true;
548
0
    break;
549
0
      }
550
0
  }
551
0
  if(!haveBytes) {
552
0
      for(j = 0; j < ny; j++) {
553
0
    if(IS_BYTES(STRING_ELT(y, j))) {
554
0
        haveBytes = true;
555
0
        break;
556
0
    }
557
0
      }
558
0
  }
559
0
  if(haveBytes) useBytes = true;
560
0
    }
561
562
0
    if(!useBytes) {
563
0
  for(i = 0; i < nx; i++) {
564
0
      if(STRING_ELT(x, i) == NA_STRING) continue;
565
0
      if(!IS_ASCII(STRING_ELT(x, i))) {
566
0
    useWC = true;
567
0
    break;
568
0
      }
569
0
  }
570
0
  if(!useWC) {
571
0
      for(j = 0; j < ny; j++) {
572
0
    if(STRING_ELT(y, j) == NA_STRING) continue;
573
0
    if(!IS_ASCII(STRING_ELT(y, j))) {
574
0
        useWC = true;
575
0
        break;
576
0
    }
577
0
      }
578
0
  }
579
0
    }
580
581
0
    tre_regaparams_default(&params);
582
0
    params.max_cost = INT_MAX;
583
0
    params.cost_ins = INTEGER(opt_costs)[0];;
584
0
    params.cost_del = INTEGER(opt_costs)[1];
585
0
    params.cost_subst = INTEGER(opt_costs)[2];
586
587
0
    PROTECT(ans = allocMatrix(REALSXP, nx, ny));
588
0
    if(opt_counts) {
589
0
  PROTECT(counts = alloc3DArray(INTSXP, nx, ny, 3));
590
0
  PROTECT(offsets = alloc3DArray(INTSXP, nx, ny, 2));
591
0
    }
592
593
    /* wtransChar and translateChar can R_alloc */
594
0
    vmax = vmaxget();
595
0
    for(i = 0; i < nx; i++) {
596
0
  elt = STRING_ELT(x, i);
597
0
  if(elt == NA_STRING) {
598
0
      for(j = 0; j < ny; j++) {
599
0
    ANS(i, j) = NA_REAL;
600
0
    if(opt_counts) {
601
0
        for(m = 0; m < 3; m++) {
602
0
      COUNTS(i, j, m) = NA_INTEGER;
603
0
        }
604
0
        OFFSETS(i, j, 0) = -1;
605
0
        OFFSETS(i, j, 1) = -1;
606
0
    }
607
0
      }
608
0
  } else {
609
0
      if(useBytes)
610
0
    rc = tre_regcompb(&reg, CHAR(elt), cflags);
611
0
      else if(useWC) {
612
0
    rc = tre_regwcomp(&reg, wtransChar(elt), cflags);
613
0
    vmaxset(vmax);
614
0
      } else {
615
0
    s = translateChar(elt);
616
0
    if(mbcslocale && !mbcsValid(s)) {
617
0
        error(_("input string x[%d] is invalid in this locale"),
618
0
        i + 1);
619
0
    }
620
0
    rc = tre_regcomp(&reg, s, cflags);
621
0
    vmaxset(vmax);
622
0
      }
623
0
      if(rc) {
624
0
    char errbuf[1001];
625
0
    tre_regerror(rc, &reg, errbuf, 1001);
626
0
    error(_("regcomp error:  '%s'"), errbuf);
627
0
      }
628
0
      if(opt_counts) {
629
0
    nmatch = reg.re_nsub + 1;
630
0
    pmatch = (regmatch_t *) malloc(nmatch * sizeof(regmatch_t));
631
0
    if (pmatch == NULL) error("allocation failure in adist");
632
0
      }
633
634
0
      for(j = 0; j < ny; j++) {
635
0
    elt = STRING_ELT(y, j);
636
0
    if(elt == NA_STRING) {
637
0
        ANS(i, j) = NA_REAL;
638
0
        if(opt_counts) {
639
0
      for(m = 0; m < 3; m++) {
640
0
          COUNTS(i, j, m) = NA_INTEGER;
641
0
      }
642
0
      OFFSETS(i, j, 0) = -1;
643
0
      OFFSETS(i, j, 1) = -1;
644
0
        }
645
0
    }
646
0
    else {
647
        /* Perform match. */
648
        /* undocumented, must be zeroed */
649
0
        memset(&match, 0, sizeof(match));
650
0
        if(opt_counts) {
651
0
      match.nmatch = nmatch;
652
0
      match.pmatch = pmatch;
653
0
        }
654
0
        if(useBytes)
655
0
      rc = tre_regaexecb(&reg, CHAR(elt),
656
0
             &match, params, 0);
657
0
        else if(useWC) {
658
0
      rc = tre_regawexec(&reg, wtransChar(elt),
659
0
             &match, params, 0);
660
0
      vmaxset(vmax);
661
0
        } else {
662
0
      t = translateChar(elt);
663
0
      if(mbcslocale && !mbcsValid(t)) {
664
0
          error(_("input string y[%d] is invalid in this locale"),
665
0
          j + 1);
666
0
      }
667
0
      rc = tre_regaexec(&reg, t,
668
0
            &match, params, 0);
669
0
      vmaxset(vmax);
670
0
        }
671
0
        if(rc == REG_OK) {
672
0
      ANS(i, j) = (double) match.cost;
673
0
      if(opt_counts) {
674
0
          COUNTS(i, j, 0) = match.num_ins;
675
0
          COUNTS(i, j, 1) = match.num_del;
676
0
          COUNTS(i, j, 2) = match.num_subst;
677
0
          OFFSETS(i, j, 0) = match.pmatch[0].rm_so + 1;
678
0
          OFFSETS(i, j, 1) = match.pmatch[0].rm_eo;
679
0
      }
680
0
        } else {
681
      /* Should maybe check for REG_NOMATCH? */
682
0
      ANS(i, j) = R_PosInf;
683
0
      if(opt_counts) {
684
0
          for(m = 0; m < 3; m++) {
685
0
        COUNTS(i, j, m) = NA_INTEGER;
686
0
          }
687
0
          OFFSETS(i, j, 0) = -1;
688
0
          OFFSETS(i, j, 1) = -1;
689
0
      }
690
0
        }
691
0
    }
692
0
      }
693
0
      if(opt_counts)
694
0
    free(pmatch);
695
0
      tre_regfree(&reg);
696
0
  }
697
0
    }
698
699
0
    PROTECT(x = getAttrib(x, R_NamesSymbol));
700
0
    PROTECT(y = getAttrib(y, R_NamesSymbol));
701
0
    if(!isNull(x) || !isNull(y)) {
702
0
  PROTECT(dimnames = allocVector(VECSXP, 2));
703
0
  SET_VECTOR_ELT(dimnames, 0, x);
704
0
  SET_VECTOR_ELT(dimnames, 1, y);
705
0
  setAttrib(ans, R_DimNamesSymbol, dimnames);
706
0
  UNPROTECT(1); /* dimnames */
707
0
    }
708
0
    if(opt_counts) {
709
0
  PROTECT(dimnames = allocVector(VECSXP, 3));
710
0
  PROTECT(names = allocVector(STRSXP, 3));
711
0
  SET_STRING_ELT(names, 0, mkChar("ins"));
712
0
  SET_STRING_ELT(names, 1, mkChar("del"));
713
0
  SET_STRING_ELT(names, 2, mkChar("sub"));
714
0
  SET_VECTOR_ELT(dimnames, 0, x);
715
0
  SET_VECTOR_ELT(dimnames, 1, y);
716
0
  SET_VECTOR_ELT(dimnames, 2, names);
717
0
  setAttrib(counts, R_DimNamesSymbol, dimnames);
718
0
  setAttrib(ans, install("counts"), counts);
719
0
  UNPROTECT(2); /* names, dimnames */
720
0
  PROTECT(dimnames = allocVector(VECSXP, 3));
721
0
  PROTECT(names = allocVector(STRSXP, 2));
722
0
  SET_STRING_ELT(names, 0, mkChar("first"));
723
0
  SET_STRING_ELT(names, 1, mkChar("last"));
724
0
  SET_VECTOR_ELT(dimnames, 0, x);
725
0
  SET_VECTOR_ELT(dimnames, 1, y);
726
0
  SET_VECTOR_ELT(dimnames, 2, names);
727
0
  setAttrib(offsets, R_DimNamesSymbol, dimnames);
728
0
  setAttrib(ans, install("offsets"), offsets);
729
0
  UNPROTECT(4); /* names, dimnames, counts, offsets */
730
0
    }
731
732
0
    UNPROTECT(3); /* y, x, counts */
733
0
    return ans;
734
0
}
735
736
attribute_hidden SEXP do_aregexec(SEXP call, SEXP op, SEXP args, SEXP env)
737
0
{
738
0
    SEXP pat, vec, ans, matchpos, matchlen;
739
0
    SEXP opt_bounds, opt_costs;
740
0
    int opt_icase, opt_fixed, useBytes;
741
742
0
    bool haveBytes, useWC = false;
743
0
    const char *s, *t;
744
0
    const void *vmax = NULL;
745
746
0
    regex_t reg;
747
0
    size_t nmatch;
748
0
    regmatch_t *pmatch;
749
0
    regaparams_t params;
750
0
    regamatch_t match;
751
0
    int so, patlen;
752
0
    int rc, cflags = REG_EXTENDED;
753
754
0
    checkArity(op, args);
755
756
0
    pat = CAR(args); args = CDR(args);
757
0
    vec = CAR(args); args = CDR(args);
758
0
    opt_bounds = CAR(args); args = CDR(args);
759
0
    opt_costs = CAR(args); args = CDR(args);
760
0
    opt_icase = asLogical(CAR(args)); args = CDR(args);
761
0
    opt_fixed = asLogical(CAR(args)); args = CDR(args);
762
0
    useBytes = asLogical(CAR(args));
763
764
0
    if(opt_icase == NA_INTEGER) opt_icase = 0;
765
0
    if(opt_fixed == NA_INTEGER) opt_fixed = 0;
766
0
    if(useBytes == NA_INTEGER) useBytes = 0;
767
0
    if(opt_fixed && opt_icase) {
768
0
  warning(_("argument '%s' will be ignored"),
769
0
    "ignore.case = TRUE");
770
0
  opt_icase = 0;
771
0
    }
772
0
    if(opt_fixed) cflags |= REG_LITERAL;
773
0
    if(opt_icase) cflags |= REG_ICASE;
774
775
0
    if(!isString(pat) ||
776
0
       (length(pat) < 1) ||
777
0
       (STRING_ELT(pat, 0) == NA_STRING))
778
0
  error(_("invalid '%s' argument"), "pattern");
779
0
    if(length(pat) > 1)
780
0
  warning(_("argument '%s' has length > 1 and only the first element will be used"), "pattern");
781
782
0
    if(!isString(vec))
783
0
  error(_("invalid '%s' argument"), "text");
784
785
0
    R_xlen_t n = XLENGTH(vec);
786
787
0
    if(!useBytes) {
788
0
  haveBytes = IS_BYTES(STRING_ELT(pat, 0));
789
0
  if(!haveBytes)
790
0
      for(R_xlen_t i = 0; i < n; i++) {
791
0
    if(IS_BYTES(STRING_ELT(vec, i))) {
792
0
        haveBytes = true;
793
0
        break;
794
0
    }
795
0
      }
796
0
  if(haveBytes) useBytes = true;
797
0
    }
798
799
0
    if(!useBytes) {
800
0
  useWC = !IS_ASCII(STRING_ELT(pat, 0));
801
0
  if(!useWC) {
802
0
      for(R_xlen_t i = 0 ; i < n ; i++) {
803
0
    if(STRING_ELT(vec, i) == NA_STRING) continue;
804
0
    if(!IS_ASCII(STRING_ELT(vec, i))) {
805
0
        useWC = true;
806
0
        break;
807
0
    }
808
0
      }
809
0
  }
810
0
    }
811
812
0
    SEXP s_nchar = install("nchar");
813
0
    if(useBytes)
814
0
  PROTECT(call = lang3(s_nchar, pat,
815
0
           ScalarString(mkChar("bytes"))));
816
0
    else
817
0
  PROTECT(call = lang3(s_nchar, pat,
818
0
           ScalarString(mkChar("chars"))));
819
0
    patlen = asInteger(eval(call, env));
820
0
    UNPROTECT(1);
821
0
    if(!patlen)
822
0
  error(_("'pattern' must be a non-empty character string"));
823
824
0
    if(useBytes)
825
0
  rc = tre_regcompb(&reg, CHAR(STRING_ELT(pat, 0)), cflags);
826
0
    else if(useWC)
827
0
  rc = tre_regwcomp(&reg, wtransChar(STRING_ELT(pat, 0)), cflags);
828
0
    else {
829
0
  s = translateChar(STRING_ELT(pat, 0));
830
0
  if(mbcslocale && !mbcsValid(s))
831
0
      error(_("regular expression is invalid in this locale"));
832
0
  rc = tre_regcomp(&reg, s, cflags);
833
0
    }
834
0
    if(rc) {
835
0
  char errbuf[1001];
836
0
  tre_regerror(rc, &reg, errbuf, 1001);
837
0
  error(_("regcomp error: '%s'"), errbuf);
838
0
    }
839
840
0
    nmatch = reg.re_nsub + 1;
841
842
0
    pmatch = (regmatch_t *) malloc(nmatch * sizeof(regmatch_t));
843
0
    if(pmatch == NULL) error("allocation failure in aregexec");
844
    
845
0
    tre_regaparams_default(&params);
846
0
    amatch_regaparams(&params, patlen,
847
0
          REAL(opt_bounds), INTEGER(opt_costs));
848
849
0
    PROTECT(ans = allocVector(VECSXP, n));
850
851
0
    for(R_xlen_t i = 0; i < n; i++) {
852
//  if ((i+1) % NINTERRUPT == 0) R_CheckUserInterrupt();
853
0
  if(STRING_ELT(vec, i) == NA_STRING) {
854
0
      PROTECT(matchpos = ScalarInteger(NA_INTEGER));
855
0
      SEXP s_match_length = install("match.length");
856
0
      setAttrib(matchpos, s_match_length,
857
0
          ScalarInteger(NA_INTEGER));
858
0
      SET_VECTOR_ELT(ans, i, matchpos);
859
0
      UNPROTECT(1);
860
0
  } else {
861
0
      vmax = vmaxget();
862
      /* Perform match. */
863
0
      memset(&match, 0, sizeof(match));
864
0
      match.nmatch = nmatch;
865
0
      match.pmatch = pmatch;
866
0
      if(useBytes)
867
0
    rc = tre_regaexecb(&reg, CHAR(STRING_ELT(vec, i)),
868
0
           &match, params, 0);
869
0
      else if(useWC) {
870
0
    rc = tre_regawexec(&reg, wtransChar(STRING_ELT(vec, i)),
871
0
           &match, params, 0);
872
0
    vmaxset(vmax);
873
0
      }
874
0
      else {
875
0
    t = translateChar(STRING_ELT(vec, i));
876
0
    if(mbcslocale && !mbcsValid(t))
877
0
        error(_("input string %lld is invalid in this locale"),
878
0
        (long long)i + 1);
879
0
    rc = tre_regaexec(&reg, t,
880
0
          &match, params, 0);
881
0
    vmaxset(vmax);
882
0
      }
883
0
      if(rc == REG_OK) {
884
0
    PROTECT(matchpos = allocVector(INTSXP, nmatch));
885
0
    PROTECT(matchlen = allocVector(INTSXP, nmatch));
886
0
    for(R_xlen_t j = 0; j < match.nmatch; j++) {
887
0
        so = match.pmatch[j].rm_so;
888
0
        INTEGER(matchpos)[j] = so + 1;
889
0
        INTEGER(matchlen)[j] = match.pmatch[j].rm_eo - so;
890
0
    }
891
0
    setAttrib(matchpos, install("match.length"), matchlen);
892
0
    if(useBytes)
893
0
        setAttrib(matchpos, install("useBytes"),
894
0
            ScalarLogical(true));
895
0
    SET_VECTOR_ELT(ans, i, matchpos);
896
0
    UNPROTECT(2);
897
0
      } else {
898
    /* No match (or could there be an error?). */
899
    /* Alternatively, could return nmatch -1 values.
900
    */
901
0
    PROTECT(matchpos = ScalarInteger(-1));
902
0
    PROTECT(matchlen = ScalarInteger(-1));
903
0
    setAttrib(matchpos, install("match.length"), matchlen);
904
0
    SET_VECTOR_ELT(ans, i, matchpos);
905
0
    UNPROTECT(2);
906
0
      }
907
0
  }
908
0
    }
909
910
0
    free(pmatch);
911
912
0
    tre_regfree(&reg);
913
914
0
    UNPROTECT(1);
915
916
0
    return ans;
917
0
}