| 1 | /* $Header$ */ |
| 2 | |
| 3 | /* Copyright (c) 2012 by Michael J. Roberts. All Rights Reserved. */ |
| 4 | /* |
| 5 | Name |
| 6 | vmfindrep.h - find/replace common code template |
| 7 | Function |
| 8 | Defines the common code template for String.findReplace() and rexReplace(). |
| 9 | The two functions are very similar, but have some slight interface |
| 10 | differences. Implementing as a common subroutine has a measurable |
| 11 | negative impact on performance; typical TADS games make heavy use of |
| 12 | these functions, so optimizing them for speed is beneficial. By using |
| 13 | a common code template, we can avoid the extra calls and run-time |
| 14 | condition checking that's necessary in a common subroutine; in the |
| 15 | template version, we essentially unroll the code and apply the conditions |
| 16 | and test the conditions statically. This makes for larger but faster |
| 17 | code. |
| 18 | Notes |
| 19 | |
| 20 | Modified |
| 21 | 06/17/12 MJRoberts - Creation |
| 22 | */ |
| 23 | |
| 24 | #ifndef VMFINDREP_H |
| 25 | #define VMFINDREP_H |
| 26 | |
| 27 | /* ------------------------------------------------------------------------ */ |
| 28 | /* |
| 29 | * re_replace flags |
| 30 | */ |
| 31 | |
| 32 | /* replace all matches (if omitted, replaces only the first match) */ |
| 33 | #define VMBIFTADS_REPLACE_ALL 0x0001 |
| 34 | |
| 35 | /* ignore case in matching the search string */ |
| 36 | #define VMBIFTADS_REPLACE_NOCASE 0x0002 |
| 37 | |
| 38 | /* |
| 39 | * follow case: lower-case characters in the the replacement text are |
| 40 | * converted to follow the case pattern of the matched text (all lower, |
| 41 | * initial capital, or all capitals) |
| 42 | */ |
| 43 | #define VMBIFTADS_REPLACE_FOLLOW_CASE 0x0004 |
| 44 | |
| 45 | /* |
| 46 | * serial replacement: when a list of search patterns is used, we replace |
| 47 | * each occurrence of the first pattern over the whole string, then we |
| 48 | * start over with the result and scan for occurrences of the second |
| 49 | * pattern, replacing each of these, and so on. If this flag isn't |
| 50 | * specified, the default is parallel scanning: we find the leftmost |
| 51 | * occurrence of any of the patterns and replace it; then we scan the |
| 52 | * remainder of the string for the leftmost occurrence of any pattern, and |
| 53 | * replace that one; and so on. The serial case is equivalent to making a |
| 54 | * series of calls to this function with the individual search patterns. |
| 55 | */ |
| 56 | #define VMBIFTADS_REPLACE_SERIAL 0x0008 |
| 57 | |
| 58 | /* |
| 59 | * Replace only the first occurrence. |
| 60 | */ |
| 61 | #define VMBIFTADS_REPLACE_ONCE 0x0010 |
| 62 | |
| 63 | |
| 64 | /* |
| 65 | * re_replace pattern/replacement structure. This is used to handle arrays |
| 66 | * of arguments: each element represents one pattern->replacement mapping. |
| 67 | */ |
| 68 | struct re_replace_arg |
| 69 | { |
| 70 | re_replace_arg() |
| 71 | { |
| 72 | s = 0; |
| 73 | pat = 0; |
| 74 | pat_str = 0; |
| 75 | rpl_func.set_nil(); |
| 76 | match_valid = FALSE; |
| 77 | } |
| 78 | |
| 79 | ~re_replace_arg() |
| 80 | { |
| 81 | /* if we created the pattern object, delete it */ |
| 82 | if (pat != 0 && our_pat) |
| 83 | CRegexParser::free_pattern(pat); |
| 84 | if (s != 0) |
| 85 | delete s; |
| 86 | } |
| 87 | |
| 88 | void set(VMG_ const vm_val_t *patv, const vm_val_t *rplv, |
| 89 | int str_to_pat, int32_t flags) |
| 90 | { |
| 91 | /* save the flags */ |
| 92 | this->flags = flags; |
| 93 | |
| 94 | /* retrieve the compiled RexPattern or uncompiled pattern string */ |
| 95 | const char *str; |
| 96 | if (patv->typ == VM_OBJ |
| 97 | && CVmObjPattern::is_pattern_obj(vmg_ patv->val.obj)) |
| 98 | { |
| 99 | /* create the searcher, if we haven't already */ |
| 100 | create_searcher(vmg0_); |
| 101 | |
| 102 | /* it's a pattern object - get its compiled pattern structure */ |
| 103 | pat = ((CVmObjPattern *)vm_objp(vmg_ patv->val.obj)) |
| 104 | ->get_pattern(vmg0_); |
| 105 | |
| 106 | /* we didn't create the pattern object */ |
| 107 | our_pat = FALSE; |
| 108 | } |
| 109 | else if ((str = patv->get_as_string(vmg0_)) != 0) |
| 110 | { |
| 111 | /* it's a string - decide how to treat it */ |
| 112 | if (str_to_pat) |
| 113 | { |
| 114 | /* create the searcher */ |
| 115 | create_searcher(vmg0_); |
| 116 | |
| 117 | /* we treat strings as regular expressions - compile it */ |
| 118 | re_status_t stat; |
| 119 | stat = G_bif_tads_globals->rex_parser->compile_pattern( |
| 120 | str + VMB_LEN, vmb_get_len(str), &pat); |
| 121 | |
| 122 | /* if that failed, we don't have a pattern */ |
| 123 | if (stat != RE_STATUS_SUCCESS) |
| 124 | pat = 0; |
| 125 | |
| 126 | /* make a note that we allocated the pattern */ |
| 127 | our_pat = TRUE; |
| 128 | } |
| 129 | else |
| 130 | { |
| 131 | /* we treat strings as simple literal search strings */ |
| 132 | pat_str = str; |
| 133 | } |
| 134 | } |
| 135 | else |
| 136 | { |
| 137 | /* invalid type */ |
| 138 | err_throw(VMERR_BAD_TYPE_BIF); |
| 139 | } |
| 140 | |
| 141 | /* |
| 142 | * Save the replacement value. This can be a string, nil (which we |
| 143 | * treat like an empty string), or a callback function. |
| 144 | */ |
| 145 | if (rplv->typ == VM_NIL) |
| 146 | { |
| 147 | /* treat it as an empty string */ |
| 148 | rpl_str = "\000\000"; |
| 149 | } |
| 150 | else if ((str = rplv->get_as_string(vmg0_)) != 0) |
| 151 | { |
| 152 | /* save the string value */ |
| 153 | rpl_str = str; |
| 154 | } |
| 155 | else if (rplv->is_func_ptr(vmg0_)) |
| 156 | { |
| 157 | /* it's a function or invokable object */ |
| 158 | rpl_str = 0; |
| 159 | rpl_func = *rplv; |
| 160 | |
| 161 | /* get the number of arguments it expects */ |
| 162 | CVmFuncPtr f(vmg_ rplv); |
| 163 | rpl_argc = f.is_varargs() ? -1 : f.get_max_argc(); |
| 164 | } |
| 165 | else |
| 166 | { |
| 167 | /* invalid type */ |
| 168 | err_throw(VMERR_BAD_TYPE_BIF); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /* create the regex searcher */ |
| 173 | void create_searcher(VMG0_) |
| 174 | { |
| 175 | /* create our searcher if we haven't yet */ |
| 176 | if (s == 0) |
| 177 | { |
| 178 | /* create the searcher object */ |
| 179 | s = new CRegexSearcherSimple(G_bif_tads_globals->rex_parser); |
| 180 | |
| 181 | /* turn off case sensitivity in the searcher if desired */ |
| 182 | if ((flags & VMBIFTADS_REPLACE_NOCASE) != 0) |
| 183 | s->set_default_case_sensitive(FALSE); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | void search(VMG_ const char *str, int start_idx, const char *last_str) |
| 188 | { |
| 189 | /* if we have a pattern, search for it */ |
| 190 | if (pat_str != 0) |
| 191 | { |
| 192 | /* |
| 193 | * whether or not we find a match, the search will be valid |
| 194 | * when we return |
| 195 | */ |
| 196 | match_valid = TRUE; |
| 197 | match_len = 0; |
| 198 | |
| 199 | /* set up a pointer to the current position */ |
| 200 | utf8_ptr p((char *)str + VMB_LEN + start_idx); |
| 201 | |
| 202 | /* figure the number of bytes left in the string */ |
| 203 | size_t rem = vmb_get_len(str) - start_idx; |
| 204 | |
| 205 | /* note the length of the search string */ |
| 206 | size_t pat_len = vmb_get_len(pat_str); |
| 207 | |
| 208 | /* scan for a match, according to case sensitivity */ |
| 209 | if (!(flags & VMBIFTADS_REPLACE_NOCASE)) |
| 210 | { |
| 211 | /* case sensitive - scan for a match */ |
| 212 | for ( ; rem >= pat_len ; p.inc(&rem)) |
| 213 | { |
| 214 | /* no case folding, so simply compare byte by byte */ |
| 215 | if (memcmp(p.getptr(), pat_str + VMB_LEN, pat_len) == 0) |
| 216 | { |
| 217 | /* success - remember the match length and position */ |
| 218 | match_len = pat_len; |
| 219 | match_idx = p.getptr() - (str + VMB_LEN); |
| 220 | |
| 221 | /* we're done */ |
| 222 | return; |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | else |
| 227 | { |
| 228 | /* case-insensitive - scan for a match */ |
| 229 | for ( ; rem >= pat_len ; p.inc(&rem)) |
| 230 | { |
| 231 | /* compare with case folding */ |
| 232 | size_t ml; |
| 233 | if (t3_compare_case_fold( |
| 234 | pat_str + VMB_LEN, pat_len, |
| 235 | p.getptr(), rem, &ml) == 0) |
| 236 | { |
| 237 | /* success - set the match index, and we're done */ |
| 238 | match_idx = p.getptr() - (str + VMB_LEN); |
| 239 | match_len = ml; |
| 240 | return; |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /* we didn't a match - set the match index to so indicate */ |
| 246 | match_idx = -1; |
| 247 | } |
| 248 | if (pat != 0) |
| 249 | { |
| 250 | /* search for the regular expression */ |
| 251 | match_idx = s->search_for_pattern( |
| 252 | pat, str + VMB_LEN, last_str, |
| 253 | vmb_get_len(str) - start_idx, &match_len); |
| 254 | |
| 255 | /* if we found it, adjust to the absolute offset in the string */ |
| 256 | if (match_idx >= 0) |
| 257 | match_idx += start_idx; |
| 258 | } |
| 259 | else |
| 260 | { |
| 261 | /* no pattern -> no match */ |
| 262 | match_idx = -1; |
| 263 | } |
| 264 | |
| 265 | /* whether or not we matched, our result is now valid */ |
| 266 | match_valid = TRUE; |
| 267 | } |
| 268 | |
| 269 | /* our search pattern, or null if we're searching for a literal string */ |
| 270 | re_compiled_pattern *pat; |
| 271 | |
| 272 | /* our search string, or null if we're searching for a pattern */ |
| 273 | const char *pat_str; |
| 274 | |
| 275 | /* Did we create the pattern? If so, delete it on destruction. */ |
| 276 | int our_pat; |
| 277 | |
| 278 | /* our replacement string, or null if it's a callback function */ |
| 279 | const char *rpl_str; |
| 280 | |
| 281 | /* our replacement function, in lieu of a string */ |
| 282 | vm_val_t rpl_func; |
| 283 | |
| 284 | /* the number of arguments rpl_func expects, or -1 for varargs */ |
| 285 | int rpl_argc; |
| 286 | |
| 287 | /* search flags */ |
| 288 | int32_t flags; |
| 289 | |
| 290 | /* the byte index and length in the source string of our last match */ |
| 291 | int match_idx; |
| 292 | int match_len; |
| 293 | |
| 294 | /* |
| 295 | * Is this last match data valid? This is false if we haven't done the |
| 296 | * first search yet, or if the last replacement overlapped our matching |
| 297 | * text at all. |
| 298 | */ |
| 299 | int match_valid; |
| 300 | |
| 301 | /* searcher - this holds the group registers for the last match */ |
| 302 | CRegexSearcherSimple *s; |
| 303 | }; |
| 304 | |
| 305 | /* ------------------------------------------------------------------------ */ |
| 306 | /* |
| 307 | * <mode> values for vm_find_replace<mode> |
| 308 | */ |
| 309 | #define VMFINDREPLACE_StringFindReplace 0 |
| 310 | #define VMFINDREPLACE_rexReplace 1 |
| 311 | |
| 312 | /* |
| 313 | * Common find-and-replace handler for String.findReplace() and |
| 314 | * rexReplace(). The two functions are essentially the same; the only |
| 315 | * differences are: |
| 316 | * |
| 317 | * 1. The arguments are in a slightly different order. |
| 318 | *. rexReplace(pattern, subject, replacement, flags?, index?) |
| 319 | *. subject.findReplace(pattern, replacement, flags?, index?) |
| 320 | * |
| 321 | * Note the placement of the subject string argument; it moves outside the |
| 322 | * argument list to the target object position in the String method call |
| 323 | * version, so the subsequent arguments all move down one position. |
| 324 | * |
| 325 | * 2. In String.findReplace(), the 'pattern' argument is taken as literal |
| 326 | * text if a string value is passed. In rexReplace(), a string value for |
| 327 | * 'pattern' is taken as an uncompiled regular expression. For either |
| 328 | * function, a RexPattern object can be passed, in which case it's treated |
| 329 | * as a regular expression (obviously). |
| 330 | * |
| 331 | * 3. If 'pattern' is a literal string, 'replacement' is also treated as |
| 332 | * literal text; if 'pattern' is a regular expression (either explicitly as |
| 333 | * a RexPattern object, or as a string taken to be an uncompiled regular |
| 334 | * expression in rexReplace()), '%' sequences are used for group |
| 335 | * replacements; e.g., '%1' is replaced with the matching text for the |
| 336 | * first parenthesized group in the regex, '%2' by the second group's |
| 337 | * matching text, etc. |
| 338 | */ |
| 339 | template<int mode> inline void vm_find_replace( |
| 340 | VMG_ vm_val_t *result, int argc, |
| 341 | const vm_val_t *subj, const char *subj_str) |
| 342 | { |
| 343 | int i; |
| 344 | vm_rcdesc rc; |
| 345 | const int new_str_ofs = |
| 346 | (mode == VMFINDREPLACE_StringFindReplace ? 1 : 2); |
| 347 | const int pat_str_is_regex = (mode == VMFINDREPLACE_rexReplace); |
| 348 | |
| 349 | /* remember the original subject string */ |
| 350 | const vm_val_t *orig_subj = subj; |
| 351 | |
| 352 | /* get the flags; use ReplaceAll if omitted */ |
| 353 | int32_t flags = VMBIFTADS_REPLACE_ALL; |
| 354 | const vm_val_t *flagp; |
| 355 | if (new_str_ofs + 1 < argc && |
| 356 | (flagp = G_stk->get(new_str_ofs + 1))->typ != VM_NIL) |
| 357 | { |
| 358 | /* check the type */ |
| 359 | if (flagp->typ != VM_INT) |
| 360 | err_throw(VMERR_INT_VAL_REQD); |
| 361 | |
| 362 | /* retrieve the value */ |
| 363 | flags = flagp->val.intval; |
| 364 | } |
| 365 | |
| 366 | /* |
| 367 | * Check for old flags. Before 3.1, there was only one flag bit |
| 368 | * defined: ALL=1. This means there were only two valid values for |
| 369 | * 'flags': 0 for ONCE mode, 1 for ALL mode. |
| 370 | * |
| 371 | * In 3.1, we added a bunch of new flags. At the same time, we made |
| 372 | * the default ALL mode, because this is the more common case. |
| 373 | * Unfortunately, this creates a compatibility issue. A new program |
| 374 | * that specifies one of the new flags might leave out the ONCE or ALL |
| 375 | * bits, since ALL is the default. However, we can't just take the |
| 376 | * absence of the ONCE bit as meaning ALL, because that would hose old |
| 377 | * programs that explicitly specify ONCE as 0 (no bits set). |
| 378 | * |
| 379 | * Here's how we deal with this: we prohibit new programs from passing |
| 380 | * 0 for the flags, requiring them to specify at least one bit. So if |
| 381 | * the flags value is zero, we must have an old program that passed |
| 382 | * ONCE. In this case, explicitly set the ONCE bit. If we have any |
| 383 | * non-zero value, we must have either a new program OR an old program |
| 384 | * that included the ALL bit. In either case, ALL is the default, so |
| 385 | * if the ONCE bit ISN'T set, explicitly set the ALL bit. |
| 386 | */ |
| 387 | if (flags == 0) |
| 388 | { |
| 389 | /* old program with the old ONCE flag - set the new ONCE flag */ |
| 390 | flags = VMBIFTADS_REPLACE_ONCE; |
| 391 | } |
| 392 | else if (!(flags & VMBIFTADS_REPLACE_ONCE)) |
| 393 | { |
| 394 | /* |
| 395 | * new program without the ONCE flag, OR an old program with the |
| 396 | * ALL flag - explicitly set the ALL flag |
| 397 | */ |
| 398 | flags |= VMBIFTADS_REPLACE_ALL; |
| 399 | } |
| 400 | |
| 401 | /* assume that the limit is one or infinity, per the 'flags' value */ |
| 402 | int limit = ((flags & VMBIFTADS_REPLACE_ONCE) != 0 ? 1 : -1); |
| 403 | |
| 404 | /* if there's an explicit 'limit' argument, fetch it */ |
| 405 | if (new_str_ofs + 3 < argc) |
| 406 | { |
| 407 | /* nil means explicitly unlimited; otherwise it's an int */ |
| 408 | vm_val_t *limitp = G_stk->get(new_str_ofs + 3); |
| 409 | if (limitp->typ == VM_NIL) |
| 410 | { |
| 411 | /* unlimited - signify with -1 */ |
| 412 | limit = -1; |
| 413 | } |
| 414 | else if (limitp->typ == VM_INT) |
| 415 | { |
| 416 | /* get the limit, and make sure it's non-negative */ |
| 417 | if ((limit = limitp->val.intval) < 0) |
| 418 | err_throw(VMERR_BAD_VAL_BIF); |
| 419 | |
| 420 | /* |
| 421 | * if the limit is zero, the result string will obviously be |
| 422 | * identical to the source string, so just return it now |
| 423 | */ |
| 424 | if (limit == 0) |
| 425 | { |
| 426 | *result = *subj; |
| 427 | return; |
| 428 | } |
| 429 | } |
| 430 | else |
| 431 | err_throw(VMERR_INT_VAL_REQD); |
| 432 | } |
| 433 | |
| 434 | /* get the search substring or pattern value */ |
| 435 | const vm_val_t *pat = G_stk->get(0); |
| 436 | |
| 437 | /* assume we have a single pattern to search for */ |
| 438 | int pat_cnt = 1; |
| 439 | int pat_is_list = FALSE; |
| 440 | |
| 441 | /* |
| 442 | * if we're treating strings as literals (rather than uncompiled |
| 443 | * regular expressions), assume we won't have any REs to search for |
| 444 | */ |
| 445 | int have_pat = pat_str_is_regex; |
| 446 | |
| 447 | /* check whether the pattern is given as an array or as a single value */ |
| 448 | if (pat->is_listlike(vmg0_) |
| 449 | && (pat_cnt = pat->ll_length(vmg0_)) >= 0) |
| 450 | { |
| 451 | /* It's a list. Check first to see if it's empty. */ |
| 452 | if (pat_cnt == 0) |
| 453 | { |
| 454 | /* |
| 455 | * empty list, so there's no work to do - simply return the |
| 456 | * original subject string unchanged |
| 457 | */ |
| 458 | *result = *subj; |
| 459 | return; |
| 460 | } |
| 461 | |
| 462 | /* flag it as a list */ |
| 463 | pat_is_list = TRUE; |
| 464 | } |
| 465 | |
| 466 | /* get the replacement value from the stack */ |
| 467 | const vm_val_t *rpl = G_stk->get(new_str_ofs); |
| 468 | |
| 469 | /* assume we have a single replacement value */ |
| 470 | int rpl_cnt = 1; |
| 471 | int rpl_is_list = FALSE; |
| 472 | |
| 473 | /* check to see if the replacement is a list */ |
| 474 | if (rpl->is_listlike(vmg0_) |
| 475 | && (rpl_cnt = rpl->ll_length(vmg0_)) >= 0) |
| 476 | { |
| 477 | /* flag it as a list */ |
| 478 | rpl_is_list = TRUE; |
| 479 | } |
| 480 | |
| 481 | /* allocate the argument array */ |
| 482 | re_replace_arg *pats = new re_replace_arg[pat_cnt]; |
| 483 | |
| 484 | /* catch any errors so that we can free our arg array on the way out */ |
| 485 | err_try |
| 486 | { |
| 487 | /* assume we won't need a recursive callback context */ |
| 488 | int need_rc = FALSE; |
| 489 | |
| 490 | /* set up the pattern/replacement array from the arguments */ |
| 491 | for (i = 0 ; i < pat_cnt ; ++i) |
| 492 | { |
| 493 | /* get the next pattern from the list, or the single pattern */ |
| 494 | vm_val_t patele; |
| 495 | if (pat_is_list) |
| 496 | { |
| 497 | /* we have a list - get the next element */ |
| 498 | pat->ll_index(vmg_ &patele, i + 1); |
| 499 | } |
| 500 | else |
| 501 | { |
| 502 | /* we have a single pattern item */ |
| 503 | patele = *pat; |
| 504 | } |
| 505 | |
| 506 | /* |
| 507 | * Get the next replacement from the list, or the single |
| 508 | * replacement. If we have a single value for the replacement, |
| 509 | * every pattern has the same replacement. If we have a list, |
| 510 | * the pattern has the replacement at the corresponding index. |
| 511 | * If it's a list and we're past the last replacement index, |
| 512 | * use an empty string. |
| 513 | */ |
| 514 | vm_val_t rplele; |
| 515 | if (rpl_is_list) |
| 516 | { |
| 517 | /* |
| 518 | * we have a list - if we have an item at the current |
| 519 | * index, it's the corresponding replacement for the |
| 520 | * current pattern; if we've exhausted the replacement |
| 521 | * list, use an empty string as the replacement |
| 522 | */ |
| 523 | if (i < rpl_cnt) |
| 524 | rpl->ll_index(vmg_ &rplele, i + 1); |
| 525 | else |
| 526 | rplele.set_nil(); |
| 527 | } |
| 528 | else |
| 529 | { |
| 530 | /* single replacement item - it applies to all patterns */ |
| 531 | rplele = *rpl; |
| 532 | } |
| 533 | |
| 534 | /* fill in this argument item */ |
| 535 | pats[i].set(vmg_ &patele, &rplele, pat_str_is_regex, flags); |
| 536 | |
| 537 | /* note if we have a regex */ |
| 538 | have_pat |= (pats[i].pat != 0); |
| 539 | |
| 540 | /* we need a callback context if the replacement is a function */ |
| 541 | need_rc |= (pats[i].rpl_str == 0); |
| 542 | } |
| 543 | |
| 544 | /* initialize the recursive callback context if needed */ |
| 545 | if (need_rc) |
| 546 | { |
| 547 | if (mode == VMFINDREPLACE_StringFindReplace) |
| 548 | rc.init(vmg_ "String.findReplace", orig_subj, 11, |
| 549 | G_stk->get(0), argc); |
| 550 | else |
| 551 | rc.init(vmg_ "rexReplace", CVmBifTADS::bif_table, 12, |
| 552 | G_stk->get(0), argc); |
| 553 | } |
| 554 | |
| 555 | /* get the starting index, if present; use index 1 if not present */ |
| 556 | int start_char_idx = 1; |
| 557 | const vm_val_t *idxp; |
| 558 | if (new_str_ofs + 2 < argc |
| 559 | && (idxp = G_stk->get(new_str_ofs + 2))->typ != VM_NIL) |
| 560 | { |
| 561 | /* check the type */ |
| 562 | if (idxp->typ != VM_INT) |
| 563 | err_throw(VMERR_INT_VAL_REQD); |
| 564 | |
| 565 | /* get the value */ |
| 566 | start_char_idx = idxp->val.intval; |
| 567 | } |
| 568 | |
| 569 | /* |
| 570 | * push a nil placeholder for the result value (we keep it on the |
| 571 | * stack for gc protection) |
| 572 | */ |
| 573 | G_stk->push()->set_nil(); |
| 574 | |
| 575 | /* if this is a serial search, we'll start at the first pattern */ |
| 576 | int serial_idx = 0; |
| 577 | |
| 578 | /* make sure the search string is indeed a string */ |
| 579 | const char *str = subj_str; |
| 580 | if (str == 0 && (str = subj->get_as_string(vmg0_)) == 0) |
| 581 | err_throw(VMERR_STRING_VAL_REQD); |
| 582 | |
| 583 | /* set up a utf8 pointer to the search string */ |
| 584 | utf8_ptr strp((char *)str + VMB_LEN); |
| 585 | |
| 586 | /* adjust the starting index */ |
| 587 | start_char_idx += (start_char_idx < 0 |
| 588 | ? (int)strp.len(vmb_get_len(str)) : -1); |
| 589 | |
| 590 | restart_search: |
| 591 | /* |
| 592 | * remember the last search string globally, for group extraction; |
| 593 | * and forget any old group registers, since they'd point into the |
| 594 | * old string we're superseding |
| 595 | */ |
| 596 | G_bif_tads_globals->last_rex_str->val = *subj; |
| 597 | if (have_pat) |
| 598 | G_bif_tads_globals->rex_searcher->clear_group_regs(); |
| 599 | |
| 600 | /* |
| 601 | * don't allocate anything for the result yet - we'll wait to do |
| 602 | * that until we actually find a match, so that we don't allocate |
| 603 | * memory unnecessarily |
| 604 | */ |
| 605 | vm_obj_id_t ret_obj = VM_INVALID_OBJ; |
| 606 | CVmObjString *ret_str = 0; |
| 607 | |
| 608 | /* set up a null output string pointer for now */ |
| 609 | utf8_ptr dstp; |
| 610 | dstp.set((char *)0); |
| 611 | |
| 612 | /* |
| 613 | * figure out how many bytes at the start of the string to skip |
| 614 | * before our first replacement |
| 615 | */ |
| 616 | utf8_ptr p; |
| 617 | size_t rem; |
| 618 | for (p.set((char *)str + VMB_LEN), rem = vmb_get_len(str), i = 0 ; |
| 619 | i < start_char_idx && rem != 0 ; ++i, p.inc(&rem)) ; |
| 620 | |
| 621 | /* the current offset in the string is the byte skip offset */ |
| 622 | int skip_bytes = p.getptr() - (str + VMB_LEN); |
| 623 | |
| 624 | /* |
| 625 | * Start searching from the beginning of the string. Build the |
| 626 | * result string as we go. |
| 627 | */ |
| 628 | int start_idx; |
| 629 | for (start_idx = skip_bytes ; (size_t)start_idx < vmb_get_len(str) ; ) |
| 630 | { |
| 631 | /* figure out where the next search starts */ |
| 632 | const char *last_str = str + VMB_LEN + start_idx; |
| 633 | |
| 634 | /* we haven't found a matching pattern yet */ |
| 635 | int best_pat = -1; |
| 636 | |
| 637 | /* do the next serial or parallel search */ |
| 638 | if ((flags & VMBIFTADS_REPLACE_SERIAL) != 0) |
| 639 | { |
| 640 | /* |
| 641 | * Serial search: search for one item at a time. If we're |
| 642 | * out of items, we're done. |
| 643 | */ |
| 644 | if (serial_idx >= pat_cnt) |
| 645 | break; |
| 646 | |
| 647 | /* search for the next item */ |
| 648 | pats[serial_idx].search(vmg_ str, start_idx, last_str); |
| 649 | |
| 650 | /* if we didn't get a match, we're done */ |
| 651 | if (pats[serial_idx].match_idx < 0) |
| 652 | break; |
| 653 | |
| 654 | /* this is our replacement match */ |
| 655 | best_pat = serial_idx; |
| 656 | } |
| 657 | else |
| 658 | { |
| 659 | /* |
| 660 | * Parallel search: search for all of the items, and |
| 661 | * replace the leftmost match. We might still have valid |
| 662 | * search results for some items on past iterations, but |
| 663 | * others might have overlapped replacement text, in which |
| 664 | * case we'll have to refresh them. So do a search for |
| 665 | * each item that's marked as invalid. |
| 666 | */ |
| 667 | |
| 668 | /* search for each item */ |
| 669 | for (i = 0 ; i < pat_cnt ; ++i) |
| 670 | { |
| 671 | /* refresh this search, if it's invalid */ |
| 672 | if (!pats[i].match_valid) |
| 673 | pats[i].search(vmg_ str, start_idx, last_str); |
| 674 | |
| 675 | /* if this is the leftmost result so far, remember it */ |
| 676 | if (pats[i].match_idx >= 0 |
| 677 | && (best_pat < 0 |
| 678 | || pats[i].match_idx < pats[best_pat].match_idx)) |
| 679 | best_pat = i; |
| 680 | } |
| 681 | |
| 682 | /* if we didn't find a match, we're done */ |
| 683 | if (best_pat < 0) |
| 684 | break; |
| 685 | } |
| 686 | |
| 687 | /* |
| 688 | * Keep the leftmost pattern we matched. Note that we want a |
| 689 | * relative offset from last_str, so adjust from the absolute |
| 690 | * offset in the string that the pats[] entry uses. |
| 691 | */ |
| 692 | int match_idx = pats[best_pat].match_idx - start_idx; |
| 693 | int match_len = pats[best_pat].match_len; |
| 694 | const char *rplstr = pats[best_pat].rpl_str; |
| 695 | vm_val_t rplfunc = pats[best_pat].rpl_func; |
| 696 | |
| 697 | /* |
| 698 | * if we have the 'follow case' flag, note the capitalization |
| 699 | * pattern of the match |
| 700 | */ |
| 701 | int match_has_upper = FALSE, match_has_lower = FALSE; |
| 702 | if ((flags & VMBIFTADS_REPLACE_FOLLOW_CASE) != 0) |
| 703 | { |
| 704 | /* scan the match text */ |
| 705 | for (p.set((char *)last_str + match_idx), rem = match_len ; |
| 706 | rem != 0 ; p.inc(&rem)) |
| 707 | { |
| 708 | /* get this character */ |
| 709 | wchar_t ch = p.getch(); |
| 710 | |
| 711 | /* note whether it's upper or lower case */ |
| 712 | match_has_upper |= t3_is_upper(ch); |
| 713 | match_has_lower |= t3_is_lower(ch); |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | /* remember the group info, if we have a regex pattern */ |
| 718 | int group_cnt = 0; |
| 719 | if (pats[best_pat].pat != 0) |
| 720 | { |
| 721 | /* note the group count */ |
| 722 | group_cnt = pats[best_pat].pat->group_cnt; |
| 723 | |
| 724 | /* copy the group registers to the global searcher registers */ |
| 725 | G_bif_tads_globals->rex_searcher->copy_group_regs( |
| 726 | pats[best_pat].s); |
| 727 | } |
| 728 | |
| 729 | /* if we have a replacement limit, count this against the limit */ |
| 730 | if (limit > 0) |
| 731 | --limit; |
| 732 | |
| 733 | /* |
| 734 | * If we haven't allocated a result string yet, do so now, |
| 735 | * since we finally know we actually need one. |
| 736 | */ |
| 737 | if (ret_obj == VM_INVALID_OBJ) |
| 738 | { |
| 739 | /* |
| 740 | * We don't know yet how much space we'll need for the |
| 741 | * result, so this is only a temporary allocation. As a |
| 742 | * rough guess, use three times the length of the input |
| 743 | * string. We'll expand this as needed as we build the |
| 744 | * string, and shrink it down to the real size when we're |
| 745 | * done. |
| 746 | */ |
| 747 | ret_obj = CVmObjString::create(vmg_ FALSE, vmb_get_len(str)*3); |
| 748 | |
| 749 | /* save it in our stack slot, for gc protection */ |
| 750 | G_stk->get(0)->set_obj(ret_obj); |
| 751 | |
| 752 | /* get the string object pointer */ |
| 753 | ret_str = (CVmObjString *)vm_objp(vmg_ ret_obj); |
| 754 | |
| 755 | /* get a pointer to the result buffer */ |
| 756 | dstp.set(ret_str->cons_get_buf()); |
| 757 | |
| 758 | /* copy the initial part that we skipped */ |
| 759 | if (skip_bytes != 0) |
| 760 | { |
| 761 | memcpy(dstp.getptr(), str + VMB_LEN, skip_bytes); |
| 762 | dstp.set(dstp.getptr() + skip_bytes); |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | /* copy the part up to the start of the matched text, if any */ |
| 767 | if (match_idx > 0) |
| 768 | { |
| 769 | /* ensure space */ |
| 770 | dstp.set(ret_str->cons_ensure_space( |
| 771 | vmg_ dstp.getptr(), match_idx, 512)); |
| 772 | |
| 773 | /* copy the part from the last match to this match */ |
| 774 | memcpy(dstp.getptr(), last_str, match_idx); |
| 775 | |
| 776 | /* advance the output pointer */ |
| 777 | dstp.set(dstp.getptr() + match_idx); |
| 778 | } |
| 779 | |
| 780 | /* apply the replacement text */ |
| 781 | if (rplstr != 0) |
| 782 | { |
| 783 | /* get the length of the string */ |
| 784 | size_t rpllen = vmb_get_len(rplstr); |
| 785 | |
| 786 | /* we haven't substituted any alphabetic character yet */ |
| 787 | int alpha_rpl_cnt = 0; |
| 788 | |
| 789 | /* note whether we have a literal search string or a regex */ |
| 790 | int pat_is_str = (pats[best_pat].pat == 0); |
| 791 | |
| 792 | /* |
| 793 | * if we're replacing a string pattern (not a regex), and |
| 794 | * there's no case following, we can plop in the whole |
| 795 | * replacement string without examining it |
| 796 | */ |
| 797 | if (pat_is_str |
| 798 | && !(flags & VMBIFTADS_REPLACE_FOLLOW_CASE)) |
| 799 | { |
| 800 | /* ensure space */ |
| 801 | dstp.set(ret_str->cons_ensure_space( |
| 802 | vmg_ dstp.getptr(), rpllen, 512)); |
| 803 | |
| 804 | /* copy the replacement text */ |
| 805 | memcpy(dstp.getptr(), rplstr + VMB_LEN, rpllen); |
| 806 | |
| 807 | /* advance the pointer */ |
| 808 | dstp.set(dstp.getptr() + rpllen); |
| 809 | } |
| 810 | else |
| 811 | { |
| 812 | /* |
| 813 | * copy the replacement string into the output string, |
| 814 | * expanding group substitutions if we have a regex |
| 815 | */ |
| 816 | for (p.set((char *)rplstr + VMB_LEN), |
| 817 | rem = rpllen ; rem != 0 ; p.inc(&rem)) |
| 818 | { |
| 819 | /* fetch the character */ |
| 820 | wchar_t ch = p.getch(); |
| 821 | |
| 822 | /* if replacing a regex, check for '%' sequences */ |
| 823 | if (pat_is_str || ch != '%' || rem == 1) |
| 824 | { |
| 825 | /* |
| 826 | * ensure we have space for this character (one |
| 827 | * UTF8 needs 3 bytes max) |
| 828 | */ |
| 829 | dstp.set(ret_str->cons_ensure_space( |
| 830 | vmg_ dstp.getptr(), 3, 512)); |
| 831 | |
| 832 | /* |
| 833 | * if we're in 'follow case' mode, adjust the |
| 834 | * case of lower-case literal letters in the |
| 835 | * replacement text |
| 836 | */ |
| 837 | const wchar_t *u = 0; |
| 838 | if ((flags & VMBIFTADS_REPLACE_FOLLOW_CASE) != 0 |
| 839 | && t3_is_lower(ch)) |
| 840 | { |
| 841 | /* |
| 842 | * Check the mode: if we have all |
| 843 | * upper-case in the match, convert the |
| 844 | * replacement to all caps; all lower-case |
| 845 | * in the match -> all lower in the |
| 846 | * replacement; mixed -> capitalize the |
| 847 | * first letter only |
| 848 | */ |
| 849 | if (match_has_upper && !match_has_lower) |
| 850 | { |
| 851 | /* all upper -> convert to upper */ |
| 852 | u = t3_to_upper(ch); |
| 853 | } |
| 854 | else if (match_has_upper && match_has_lower |
| 855 | && alpha_rpl_cnt++ == 0) |
| 856 | { |
| 857 | /* mixed case -> use title case */ |
| 858 | u = t3_to_title(ch); |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | /* if we found a case conversion, apply it */ |
| 863 | if (u != 0) |
| 864 | { |
| 865 | /* ensure we have room for the conversion */ |
| 866 | size_t need = utf8_ptr::s_wstr_size(u); |
| 867 | dstp.set(ret_str->cons_ensure_space( |
| 868 | vmg_ dstp.getptr(), need, 512)); |
| 869 | |
| 870 | /* store the converted characters */ |
| 871 | dstp.setwcharsz(u, need); |
| 872 | } |
| 873 | else |
| 874 | { |
| 875 | /* no case conversion - copy it as-is */ |
| 876 | dstp.setch(ch); |
| 877 | } |
| 878 | } |
| 879 | else |
| 880 | { |
| 881 | /* skip the '%' and see what follows */ |
| 882 | p.inc(&rem); |
| 883 | switch(p.getch()) |
| 884 | { |
| 885 | case '1': |
| 886 | case '2': |
| 887 | case '3': |
| 888 | case '4': |
| 889 | case '5': |
| 890 | case '6': |
| 891 | case '7': |
| 892 | case '8': |
| 893 | case '9': |
| 894 | { |
| 895 | /* get the group number */ |
| 896 | int groupno = |
| 897 | value_of_digit(p.getch()) - 1; |
| 898 | |
| 899 | /* if the group is valid, add its length */ |
| 900 | if (groupno < group_cnt) |
| 901 | { |
| 902 | /* get the register */ |
| 903 | const re_group_register *reg = |
| 904 | G_bif_tads_globals->rex_searcher |
| 905 | ->get_group_reg(groupno); |
| 906 | |
| 907 | /* if it's been set, add its text */ |
| 908 | if (reg->start_ofs != -1 |
| 909 | && reg->end_ofs != -1) |
| 910 | { |
| 911 | /* get the group length */ |
| 912 | size_t glen = |
| 913 | reg->end_ofs - reg->start_ofs; |
| 914 | |
| 915 | /* ensure space */ |
| 916 | dstp.set( |
| 917 | ret_str->cons_ensure_space( |
| 918 | vmg_ dstp.getptr(), |
| 919 | glen, 512)); |
| 920 | |
| 921 | /* copy the data */ |
| 922 | memcpy(dstp.getptr(), |
| 923 | str + VMB_LEN + reg->start_ofs, |
| 924 | glen); |
| 925 | |
| 926 | /* advance past it */ |
| 927 | dstp.set(dstp.getptr() + glen); |
| 928 | } |
| 929 | } |
| 930 | } |
| 931 | break; |
| 932 | |
| 933 | case '*': |
| 934 | /* ensure space */ |
| 935 | dstp.set(ret_str->cons_ensure_space( |
| 936 | vmg_ dstp.getptr(), match_len, 512)); |
| 937 | |
| 938 | /* add the entire matched string */ |
| 939 | memcpy(dstp.getptr(), last_str + match_idx, |
| 940 | match_len); |
| 941 | dstp.set(dstp.getptr() + match_len); |
| 942 | break; |
| 943 | |
| 944 | case '%': |
| 945 | /* ensure space (the '%' is just one byte) */ |
| 946 | dstp.set(ret_str->cons_ensure_space( |
| 947 | vmg_ dstp.getptr(), 1, 512)); |
| 948 | |
| 949 | /* add a single '%' */ |
| 950 | dstp.setch('%'); |
| 951 | break; |
| 952 | |
| 953 | default: |
| 954 | /* |
| 955 | * ensure space (we need 1 byte for the |
| 956 | * '%', up to 3 for the other character) |
| 957 | */ |
| 958 | dstp.set(ret_str->cons_ensure_space( |
| 959 | vmg_ dstp.getptr(), 4, 512)); |
| 960 | |
| 961 | /* add the entire sequence unchanged */ |
| 962 | dstp.setch('%'); |
| 963 | dstp.setch(p.getch()); |
| 964 | break; |
| 965 | } |
| 966 | } |
| 967 | } |
| 968 | } |
| 969 | } |
| 970 | else |
| 971 | { |
| 972 | /* push the callback args - matchStr, matchIdx, subject */ |
| 973 | const int pushed_argc = 3; |
| 974 | G_stk->push(orig_subj); |
| 975 | G_interpreter->push_int( |
| 976 | vmg_ strp.len(start_idx + match_idx) + 1); |
| 977 | G_interpreter->push_obj(vmg_ CVmObjString::create( |
| 978 | vmg_ FALSE, last_str + match_idx, match_len)); |
| 979 | |
| 980 | /* adjust argc for what the callback actually wants */ |
| 981 | int fargc = pats[best_pat].rpl_argc; |
| 982 | if (fargc < 0 || fargc > pushed_argc) |
| 983 | fargc = pushed_argc; |
| 984 | |
| 985 | /* call the callback */ |
| 986 | G_interpreter->call_func_ptr(vmg_ &rplfunc, fargc, &rc, 0); |
| 987 | |
| 988 | /* discard extra arguments */ |
| 989 | G_stk->discard(pushed_argc - fargc); |
| 990 | |
| 991 | /* if the return value isn't nil, copy it into the result */ |
| 992 | if (G_interpreter->get_r0()->typ != VM_NIL) |
| 993 | { |
| 994 | /* get the string */ |
| 995 | const char *r = |
| 996 | G_interpreter->get_r0()->get_as_string(vmg0_); |
| 997 | if (r == 0) |
| 998 | err_throw(VMERR_STRING_VAL_REQD); |
| 999 | |
| 1000 | /* ensure space for it in the result */ |
| 1001 | dstp.set(ret_str->cons_ensure_space( |
| 1002 | vmg_ dstp.getptr(), vmb_get_len(r), 512)); |
| 1003 | |
| 1004 | /* store it */ |
| 1005 | memcpy(dstp.getptr(), r + VMB_LEN, vmb_get_len(r)); |
| 1006 | dstp.set(dstp.getptr() + vmb_get_len(r)); |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | /* advance past this matched string for the next search */ |
| 1011 | start_idx += match_idx + match_len; |
| 1012 | |
| 1013 | /* skip to the next character if it was a zero-length match */ |
| 1014 | if (match_len == 0 && (size_t)start_idx < vmb_get_len(str)) |
| 1015 | { |
| 1016 | /* ensure space */ |
| 1017 | dstp.set(ret_str->cons_ensure_space( |
| 1018 | vmg_ dstp.getptr(), 3, 512)); |
| 1019 | |
| 1020 | /* copy the character we're skipping to the output */ |
| 1021 | p.set((char *)str + VMB_LEN + start_idx); |
| 1022 | dstp.setch(p.getch()); |
| 1023 | |
| 1024 | /* move on to the next character */ |
| 1025 | start_idx += 1; |
| 1026 | } |
| 1027 | |
| 1028 | /* |
| 1029 | * In a parallel search, discard any match that started before |
| 1030 | * the new starting point. Those are no longer valid because |
| 1031 | * they matched original text that was wholly or partially |
| 1032 | * replaced by the current iteration. |
| 1033 | */ |
| 1034 | for (i = 0 ; i < pat_cnt ; ++i) |
| 1035 | { |
| 1036 | /* invalidate this match if it's before the replacement */ |
| 1037 | if (pats[i].match_idx >= 0 && pats[i].match_idx < start_idx) |
| 1038 | pats[i].match_valid = FALSE; |
| 1039 | } |
| 1040 | |
| 1041 | /* if we've reached the replacement limit, stop now */ |
| 1042 | if (limit == 0) |
| 1043 | break; |
| 1044 | } |
| 1045 | |
| 1046 | /* if we did any replacements on this round, finish the string */ |
| 1047 | if (ret_obj != VM_INVALID_OBJ) |
| 1048 | { |
| 1049 | /* ensure space for the remainder after the last match */ |
| 1050 | dstp.set(ret_str->cons_ensure_space( |
| 1051 | vmg_ dstp.getptr(), vmb_get_len(str) - start_idx, 512)); |
| 1052 | |
| 1053 | /* add the part after the end of the matched text */ |
| 1054 | if ((size_t)start_idx < vmb_get_len(str)) |
| 1055 | { |
| 1056 | memcpy(dstp.getptr(), str + VMB_LEN + start_idx, |
| 1057 | vmb_get_len(str) - start_idx); |
| 1058 | dstp.set(dstp.getptr() + vmb_get_len(str) - start_idx); |
| 1059 | } |
| 1060 | |
| 1061 | /* set the actual length of the string */ |
| 1062 | ret_str->cons_shrink_buffer(vmg_ dstp.getptr()); |
| 1063 | |
| 1064 | /* return the string */ |
| 1065 | result->set_obj(ret_obj); |
| 1066 | } |
| 1067 | else |
| 1068 | { |
| 1069 | /* we didn't replace anything, so keep the original string */ |
| 1070 | *result = *subj; |
| 1071 | } |
| 1072 | |
| 1073 | /* |
| 1074 | * If this is a serial search, and we have another item in the |
| 1075 | * search list, go back and start over with the current result as |
| 1076 | * the new search string. Exception: if we've reached the |
| 1077 | * replacement count limit, we're done. |
| 1078 | */ |
| 1079 | if ((flags & VMBIFTADS_REPLACE_SERIAL) != 0 |
| 1080 | && limit != 0 |
| 1081 | && ++serial_idx < pat_cnt) |
| 1082 | { |
| 1083 | /* use the return value as the new search value */ |
| 1084 | subj = result; |
| 1085 | *G_stk->get(2) = *subj; |
| 1086 | |
| 1087 | /* get the string again in case we're doing a serial iteration */ |
| 1088 | str = subj->get_as_string(vmg0_); |
| 1089 | |
| 1090 | /* go back for a brand new round */ |
| 1091 | goto restart_search; |
| 1092 | } |
| 1093 | |
| 1094 | /* discard our gc protection */ |
| 1095 | G_stk->discard(1); |
| 1096 | } |
| 1097 | err_finally |
| 1098 | { |
| 1099 | /* if we allocated an argument array, delete it */ |
| 1100 | if (pats != 0) |
| 1101 | delete [] pats; |
| 1102 | } |
| 1103 | err_end; |
| 1104 | } |
| 1105 | |
| 1106 | #endif /* VMFINDREP_H */ |