Debian Codegraph @

rhino/src/org/mozilla/javascript/regexp/RegExpImpl.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.regexp;
8
9 import org.mozilla.javascript.*;
10
11 /**
12 *
13 */
14 public class RegExpImpl implements RegExpProxy {
15
16 public boolean isRegExp(Scriptable obj) {
17 return obj instanceof NativeRegExp;
18 }
19
20 public Object compileRegExp(Context cx, String source, String flags)
21 {
22 return NativeRegExp.compileRE(cx, source, flags, false);
23 }
24
25 public Scriptable wrapRegExp(Context cx, Scriptable scope,
26 Object compiled)
27 {
28 return new NativeRegExp(scope, (RECompiled) compiled);
29 }
30
31 public Object action(Context cx, Scriptable scope,
32 Scriptable thisObj, Object[] args,
33 int actionType)
34 {
35 GlobData data = new GlobData();
36 data.mode = actionType;
37 data.str = ScriptRuntime.toString(thisObj);
38
39 switch (actionType) {
40 case RA_MATCH:
41 {
42 NativeRegExp re = createRegExp(cx, scope, args, 1, false);
43 Object rval = matchOrReplace(cx, scope, thisObj, args,
44 this, data, re);
45 return data.arrayobj == null ? rval : data.arrayobj;
46 }
47
48 case RA_SEARCH:
49 {
50 NativeRegExp re = createRegExp(cx, scope, args, 1, false);
51 return matchOrReplace(cx, scope, thisObj, args,
52 this, data, re);
53 }
54
55 case RA_REPLACE:
56 {
57 boolean useRE = (args.length > 0 && args[0] instanceof NativeRegExp)
58 || args.length > 2;
59 NativeRegExp re = null;
60 String search = null;
61 if (useRE) {
62 re = createRegExp(cx, scope, args, 2, true);
63 } else {
64 Object arg0 = args.length < 1 ? Undefined.instance : args[0];
65 search = ScriptRuntime.toString(arg0);
66 }
67
68 Object arg1 = args.length < 2 ? Undefined.instance : args[1];
69 String repstr = null;
70 Function lambda = null;
71 if (arg1 instanceof Function) {
72 lambda = (Function) arg1;
73 } else {
74 repstr = ScriptRuntime.toString(arg1);
75 }
76
77 data.lambda = lambda;
78 data.repstr = repstr;
79 data.dollar = repstr == null ? -1 : repstr.indexOf('$');
80 data.charBuf = null;
81 data.leftIndex = 0;
82
83 Object val;
84 if (useRE) {
85 val = matchOrReplace(cx, scope, thisObj, args,
86 this, data, re);
87 } else {
88 String str = data.str;
89 int index = str.indexOf(search);
90 if (index >= 0) {
91 int slen = search.length();
92 this.lastParen = null;
93 this.leftContext = new SubString(str, 0, index);
94 this.lastMatch = new SubString(str, index, slen);
95 this.rightContext = new SubString(str, index + slen, str.length() - index - slen);
96 val = Boolean.TRUE;
97 } else {
98 val = Boolean.FALSE;
99 }
100 }
101
102 if (data.charBuf == null) {
103 if (data.global || val == null
104 || !val.equals(Boolean.TRUE))
105 {
106 /* Didn't match even once. */
107 return data.str;
108 }
109 SubString lc = this.leftContext;
110 replace_glob(data, cx, scope, this, lc.index, lc.length);
111 }
112 SubString rc = this.rightContext;
113 data.charBuf.append(rc.str, rc.index, rc.index + rc.length);
114 return data.charBuf.toString();
115 }
116
117 default:
118 throw Kit.codeBug();
119 }
120 }
121
122 private static NativeRegExp createRegExp(Context cx, Scriptable scope,
123 Object[] args, int optarg,
124 boolean forceFlat)
125 {
126 NativeRegExp re;
127 Scriptable topScope = ScriptableObject.getTopLevelScope(scope);
128 if (args.length == 0 || args[0] == Undefined.instance) {
129 RECompiled compiled = NativeRegExp.compileRE(cx, "", "", false);
130 re = new NativeRegExp(topScope, compiled);
131 } else if (args[0] instanceof NativeRegExp) {
132 re = (NativeRegExp) args[0];
133 } else {
134 String src = ScriptRuntime.toString(args[0]);
135 String opt;
136 if (optarg < args.length) {
137 args[0] = src;
138 opt = ScriptRuntime.toString(args[optarg]);
139 } else {
140 opt = null;
141 }
142 RECompiled compiled = NativeRegExp.compileRE(cx, src, opt, forceFlat);
143 re = new NativeRegExp(topScope, compiled);
144 }
145 return re;
146 }
147
148 /**
149 * Analog of C match_or_replace.
150 */
151 private static Object matchOrReplace(Context cx, Scriptable scope,
152 Scriptable thisObj, Object[] args,
153 RegExpImpl reImpl,
154 GlobData data, NativeRegExp re)
155 {
156 String str = data.str;
157 data.global = (re.getFlags() & NativeRegExp.JSREG_GLOB) != 0;
158 int[] indexp = { 0 };
159 Object result = null;
160 if (data.mode == RA_SEARCH) {
161 result = re.executeRegExp(cx, scope, reImpl,
162 str, indexp, NativeRegExp.TEST);
163 if (result != null && result.equals(Boolean.TRUE))
164 result = Integer.valueOf(reImpl.leftContext.length);
165 else
166 result = Integer.valueOf(-1);
167 } else if (data.global) {
168 re.lastIndex = 0d;
169 for (int count = 0; indexp[0] <= str.length(); count++) {
170 result = re.executeRegExp(cx, scope, reImpl,
171 str, indexp, NativeRegExp.TEST);
172 if (result == null || !result.equals(Boolean.TRUE))
173 break;
174 if (data.mode == RA_MATCH) {
175 match_glob(data, cx, scope, count, reImpl);
176 } else {
177 if (data.mode != RA_REPLACE) Kit.codeBug();
178 SubString lastMatch = reImpl.lastMatch;
179 int leftIndex = data.leftIndex;
180 int leftlen = lastMatch.index - leftIndex;
181 data.leftIndex = lastMatch.index + lastMatch.length;
182 replace_glob(data, cx, scope, reImpl, leftIndex, leftlen);
183 }
184 if (reImpl.lastMatch.length == 0) {
185 if (indexp[0] == str.length())
186 break;
187 indexp[0]++;
188 }
189 }
190 } else {
191 result = re.executeRegExp(cx, scope, reImpl, str, indexp,
192 ((data.mode == RA_REPLACE)
193 ? NativeRegExp.TEST
194 : NativeRegExp.MATCH));
195 }
196
197 return result;
198 }
199
200
201
202 public int find_split(Context cx, Scriptable scope, String target,
203 String separator, Scriptable reObj,
204 int[] ip, int[] matchlen,
205 boolean[] matched, String[][] parensp)
206 {
207 int i = ip[0];
208 int length = target.length();
209 int result;
210
211 int version = cx.getLanguageVersion();
212 NativeRegExp re = (NativeRegExp) reObj;
213 again:
214 while (true) { // imitating C label
215 /* JS1.2 deviated from Perl by never matching at end of string. */
216 int ipsave = ip[0]; // reuse ip to save object creation
217 ip[0] = i;
218 Object ret = re.executeRegExp(cx, scope, this, target, ip,
219 NativeRegExp.TEST);
220 if (ret != Boolean.TRUE) {
221 // Mismatch: ensure our caller advances i past end of string.
222 ip[0] = ipsave;
223 matchlen[0] = 1;
224 matched[0] = false;
225 return length;
226 }
227 i = ip[0];
228 ip[0] = ipsave;
229 matched[0] = true;
230
231 SubString sep = this.lastMatch;
232 matchlen[0] = sep.length;
233 if (matchlen[0] == 0) {
234 /*
235 * Empty string match: never split on an empty
236 * match at the start of a find_split cycle. Same
237 * rule as for an empty global match in
238 * match_or_replace.
239 */
240 if (i == ip[0]) {
241 /*
242 * "Bump-along" to avoid sticking at an empty
243 * match, but don't bump past end of string --
244 * our caller must do that by adding
245 * sep->length to our return value.
246 */
247 if (i == length) {
248 if (version == Context.VERSION_1_2) {
249 matchlen[0] = 1;
250 result = i;
251 }
252 else
253 result = -1;
254 break;
255 }
256 i++;
257 continue again; // imitating C goto
258 }
259 }
260 // PR_ASSERT((size_t)i >= sep->length);
261 result = i - matchlen[0];
262 break;
263 }
264 int size = (parens == null) ? 0 : parens.length;
265 parensp[0] = new String[size];
266 for (int num = 0; num < size; num++) {
267 SubString parsub = getParenSubString(num);
268 parensp[0][num] = parsub.toString();
269 }
270 return result;
271 }
272
273 /**
274 * Analog of REGEXP_PAREN_SUBSTRING in C jsregexp.h.
275 * Assumes zero-based; i.e., for $3, i==2
276 */
277 SubString getParenSubString(int i)
278 {
279 if (parens != null && i < parens.length) {
280 SubString parsub = parens[i];
281 if (parsub != null) {
282 return parsub;
283 }
284 }
285 return SubString.emptySubString;
286 }
287
288 /*
289 * Analog of match_glob() in jsstr.c
290 */
291 private static void match_glob(GlobData mdata, Context cx,
292 Scriptable scope, int count,
293 RegExpImpl reImpl)
294 {
295 if (mdata.arrayobj == null) {
296 mdata.arrayobj = cx.newArray(scope, 0);
297 }
298 SubString matchsub = reImpl.lastMatch;
299 String matchstr = matchsub.toString();
300 mdata.arrayobj.put(count, mdata.arrayobj, matchstr);
301 }
302
303 /*
304 * Analog of replace_glob() in jsstr.c
305 */
306 private static void replace_glob(GlobData rdata, Context cx,
307 Scriptable scope, RegExpImpl reImpl,
308 int leftIndex, int leftlen)
309 {
310 int replen;
311 String lambdaStr;
312 if (rdata.lambda != null) {
313 // invoke lambda function with args lastMatch, $1, $2, ... $n,
314 // leftContext.length, whole string.
315 SubString[] parens = reImpl.parens;
316 int parenCount = (parens == null) ? 0 : parens.length;
317 Object[] args = new Object[parenCount + 3];
318 args[0] = reImpl.lastMatch.toString();
319 for (int i=0; i < parenCount; i++) {
320 SubString sub = parens[i];
321 if (sub != null) {
322 args[i+1] = sub.toString();
323 } else {
324 args[i+1] = Undefined.instance;
325 }
326 }
327 args[parenCount+1] = Integer.valueOf(reImpl.leftContext.length);
328 args[parenCount+2] = rdata.str;
329 // This is a hack to prevent expose of reImpl data to
330 // JS function which can run new regexps modifing
331 // regexp that are used later by the engine.
332 // TODO: redesign is necessary
333 if (reImpl != ScriptRuntime.getRegExpProxy(cx)) Kit.codeBug();
334 RegExpImpl re2 = new RegExpImpl();
335 re2.multiline = reImpl.multiline;
336 re2.input = reImpl.input;
337 ScriptRuntime.setRegExpProxy(cx, re2);
338 try {
339 Scriptable parent = ScriptableObject.getTopLevelScope(scope);
340 Object result = rdata.lambda.call(cx, parent, parent, args);
341 lambdaStr = ScriptRuntime.toString(result);
342 } finally {
343 ScriptRuntime.setRegExpProxy(cx, reImpl);
344 }
345 replen = lambdaStr.length();
346 } else {
347 lambdaStr = null;
348 replen = rdata.repstr.length();
349 if (rdata.dollar >= 0) {
350 int[] skip = new int[1];
351 int dp = rdata.dollar;
352 do {
353 SubString sub = interpretDollar(cx, reImpl, rdata.repstr,
354 dp, skip);
355 if (sub != null) {
356 replen += sub.length - skip[0];
357 dp += skip[0];
358 } else {
359 ++dp;
360 }
361 dp = rdata.repstr.indexOf('$', dp);
362 } while (dp >= 0);
363 }
364 }
365
366 int growth = leftlen + replen + reImpl.rightContext.length;
367 StringBuilder charBuf = rdata.charBuf;
368 if (charBuf == null) {
369 charBuf = new StringBuilder(growth);
370 rdata.charBuf = charBuf;
371 } else {
372 charBuf.ensureCapacity(rdata.charBuf.length() + growth);
373 }
374
375 charBuf.append(reImpl.leftContext.str, leftIndex, leftIndex + leftlen);
376 if (rdata.lambda != null) {
377 charBuf.append(lambdaStr);
378 } else {
379 do_replace(rdata, cx, reImpl);
380 }
381 }
382
383 private static SubString interpretDollar(Context cx, RegExpImpl res,
384 String da, int dp, int[] skip)
385 {
386 char dc;
387 int num, tmp;
388
389 if (da.charAt(dp) != '$') Kit.codeBug();
390
391 /* Allow a real backslash (literal "\\") to escape "$1" etc. */
392 int version = cx.getLanguageVersion();
393 if (version != Context.VERSION_DEFAULT
394 && version <= Context.VERSION_1_4)
395 {
396 if (dp > 0 && da.charAt(dp - 1) == '\\')
397 return null;
398 }
399 int daL = da.length();
400 if (dp + 1 >= daL)
401 return null;
402 /* Interpret all Perl match-induced dollar variables. */
403 dc = da.charAt(dp + 1);
404 if (NativeRegExp.isDigit(dc)) {
405 int cp;
406 if (version != Context.VERSION_DEFAULT
407 && version <= Context.VERSION_1_4)
408 {
409 if (dc == '0')
410 return null;
411 /* Check for overflow to avoid gobbling arbitrary decimal digits. */
412 num = 0;
413 cp = dp;
414 while (++cp < daL && NativeRegExp.isDigit(dc = da.charAt(cp)))
415 {
416 tmp = 10 * num + (dc - '0');
417 if (tmp < num)
418 break;
419 num = tmp;
420 }
421 }
422 else { /* ECMA 3, 1-9 or 01-99 */
423 int parenCount = (res.parens == null) ? 0 : res.parens.length;
424 num = dc - '0';
425 if (num > parenCount)
426 return null;
427 cp = dp + 2;
428 if ((dp + 2) < daL) {
429 dc = da.charAt(dp + 2);
430 if (NativeRegExp.isDigit(dc)) {
431 tmp = 10 * num + (dc - '0');
432 if (tmp <= parenCount) {
433 cp++;
434 num = tmp;
435 }
436 }
437 }
438 if (num == 0) return null; /* $0 or $00 is not valid */
439 }
440 /* Adjust num from 1 $n-origin to 0 array-index-origin. */
441 num--;
442 skip[0] = cp - dp;
443 return res.getParenSubString(num);
444 }
445
446 skip[0] = 2;
447 switch (dc) {
448 case '$':
449 return new SubString("$");
450 case '&':
451 return res.lastMatch;
452 case '+':
453 return res.lastParen;
454 case '`':
455 if (version == Context.VERSION_1_2) {
456 /*
457 * JS1.2 imitated the Perl4 bug where left context at each step
458 * in an iterative use of a global regexp started from last match,
459 * not from the start of the target string. But Perl4 does start
460 * $` at the beginning of the target string when it is used in a
461 * substitution, so we emulate that special case here.
462 */
463 res.leftContext.index = 0;
464 res.leftContext.length = res.lastMatch.index;
465 }
466 return res.leftContext;
467 case '\'':
468 return res.rightContext;
469 }
470 return null;
471 }
472
473 /**
474 * Analog of do_replace in jsstr.c
475 */
476 private static void do_replace(GlobData rdata, Context cx,
477 RegExpImpl regExpImpl)
478 {
479 StringBuilder charBuf = rdata.charBuf;
480 int cp = 0;
481 String da = rdata.repstr;
482 int dp = rdata.dollar;
483 if (dp != -1) {
484 int[] skip = new int[1];
485 do {
486 int len = dp - cp;
487 charBuf.append(da.substring(cp, dp));
488 cp = dp;
489 SubString sub = interpretDollar(cx, regExpImpl, da,
490 dp, skip);
491 if (sub != null) {
492 len = sub.length;
493 if (len > 0) {
494 charBuf.append(sub.str, sub.index, sub.index + len);
495 }
496 cp += skip[0];
497 dp += skip[0];
498 } else {
499 ++dp;
500 }
501 dp = da.indexOf('$', dp);
502 } while (dp >= 0);
503 }
504 int daL = da.length();
505 if (daL > cp) {
506 charBuf.append(da.substring(cp, daL));
507 }
508 }
509
510 /*
511 * See ECMA 15.5.4.8. Modified to match JS 1.2 - optionally takes
512 * a limit argument and accepts a regular expression as the split
513 * argument.
514 */
515 public Object js_split(Context cx, Scriptable scope,
516 String target, Object[] args)
517 {
518 // create an empty Array to return;
519 Scriptable result = cx.newArray(scope, 0);
520
521 // Use the second argument as the split limit, if given.
522 boolean limited = (args.length > 1) && (args[1] != Undefined.instance);
523 long limit = 0; // Initialize to avoid warning.
524 if (limited) {
525 /* Clamp limit between 0 and 1 + string length. */
526 limit = ScriptRuntime.toUint32(args[1]);
527 if (limit > target.length())
528 limit = 1 + target.length();
529 }
530
531 // return an array consisting of the target if no separator given
532 if (args.length < 1 || args[0] == Undefined.instance) {
533 result.put(0, result, target);
534 return result;
535 }
536
537 String separator = null;
538 int[] matchlen = new int[1];
539 Scriptable re = null;
540 RegExpProxy reProxy = null;
541 if (args[0] instanceof Scriptable) {
542 reProxy = ScriptRuntime.getRegExpProxy(cx);
543 if (reProxy != null) {
544 Scriptable test = (Scriptable)args[0];
545 if (reProxy.isRegExp(test)) {
546 re = test;
547 }
548 }
549 }
550 if (re == null) {
551 separator = ScriptRuntime.toString(args[0]);
552 matchlen[0] = separator.length();
553 }
554
555 // split target with separator or re
556 int[] ip = { 0 };
557 int match;
558 int len = 0;
559 boolean[] matched = { false };
560 String[][] parens = { null };
561 int version = cx.getLanguageVersion();
562 while ((match = find_split(cx, scope, target, separator, version,
563 reProxy, re, ip, matchlen, matched, parens))
564 >= 0)
565 {
566 if ((limited && len >= limit) || (match > target.length()))
567 break;
568
569 String substr;
570 if (target.length() == 0)
571 substr = target;
572 else
573 substr = target.substring(ip[0], match);
574
575 result.put(len, result, substr);
576 len++;
577 /*
578 * Imitate perl's feature of including parenthesized substrings
579 * that matched part of the delimiter in the new array, after the
580 * split substring that was delimited.
581 */
582 if (re != null && matched[0]) {
583 int size = parens[0].length;
584 for (int num = 0; num < size; num++) {
585 if (limited && len >= limit)
586 break;
587 result.put(len, result, parens[0][num]);
588 len++;
589 }
590 matched[0] = false;
591 }
592 ip[0] = match + matchlen[0];
593
594 if (version < Context.VERSION_1_3
595 && version != Context.VERSION_DEFAULT)
596 {
597 /*
598 * Deviate from ECMA to imitate Perl, which omits a final
599 * split unless a limit argument is given and big enough.
600 */
601 if (!limited && ip[0] == target.length())
602 break;
603 }
604 }
605 return result;
606 }
607
608 /*
609 * Used by js_split to find the next split point in target,
610 * starting at offset ip and looking either for the given
611 * separator substring, or for the next re match. ip and
612 * matchlen must be reference variables (assumed to be arrays of
613 * length 1) so they can be updated in the leading whitespace or
614 * re case.
615 *
616 * Return -1 on end of string, >= 0 for a valid index of the next
617 * separator occurrence if found, or the string length if no
618 * separator is found.
619 */
620 private static int find_split(Context cx, Scriptable scope, String target,
621 String separator, int version,
622 RegExpProxy reProxy, Scriptable re,
623 int[] ip, int[] matchlen, boolean[] matched,
624 String[][] parensp)
625 {
626 int i = ip[0];
627 int length = target.length();
628
629 /*
630 * Perl4 special case for str.split(' '), only if the user has selected
631 * JavaScript1.2 explicitly. Split on whitespace, and skip leading w/s.
632 * Strange but true, apparently modeled after awk.
633 */
634 if (version == Context.VERSION_1_2 &&
635 re == null && separator.length() == 1 && separator.charAt(0) == ' ')
636 {
637 /* Skip leading whitespace if at front of str. */
638 if (i == 0) {
639 while (i < length && Character.isWhitespace(target.charAt(i)))
640 i++;
641 ip[0] = i;
642 }
643
644 /* Don't delimit whitespace at end of string. */
645 if (i == length)
646 return -1;
647
648 /* Skip over the non-whitespace chars. */
649 while (i < length
650 && !Character.isWhitespace(target.charAt(i)))
651 i++;
652
653 /* Now skip the next run of whitespace. */
654 int j = i;
655 while (j < length && Character.isWhitespace(target.charAt(j)))
656 j++;
657
658 /* Update matchlen to count delimiter chars. */
659 matchlen[0] = j - i;
660 return i;
661 }
662
663 /*
664 * Stop if past end of string. If at end of string, we will
665 * return target length, so that
666 *
667 * "ab,".split(',') => new Array("ab", "")
668 *
669 * and the resulting array converts back to the string "ab,"
670 * for symmetry. NB: This differs from perl, which drops the
671 * trailing empty substring if the LIMIT argument is omitted.
672 */
673 if (i > length)
674 return -1;
675
676 /*
677 * Match a regular expression against the separator at or
678 * above index i. Return -1 at end of string instead of
679 * trying for a match, so we don't get stuck in a loop.
680 */
681 if (re != null) {
682 return reProxy.find_split(cx, scope, target, separator, re,
683 ip, matchlen, matched, parensp);
684 }
685
686 /*
687 * Deviate from ECMA by never splitting an empty string by any separator
688 * string into a non-empty array (an array of length 1 that contains the
689 * empty string).
690 */
691 if (version != Context.VERSION_DEFAULT && version < Context.VERSION_1_3
692 && length == 0)
693 return -1;
694
695 /*
696 * Special case: if sep is the empty string, split str into
697 * one character substrings. Let our caller worry about
698 * whether to split once at end of string into an empty
699 * substring.
700 *
701 * For 1.2 compatibility, at the end of the string, we return the length as
702 * the result, and set the separator length to 1 -- this allows the caller
703 * to include an additional null string at the end of the substring list.
704 */
705 if (separator.length() == 0) {
706 if (version == Context.VERSION_1_2) {
707 if (i == length) {
708 matchlen[0] = 1;
709 return i;
710 }
711 return i + 1;
712 }
713 return (i == length) ? -1 : i + 1;
714 }
715
716 /* Punt to j.l.s.indexOf; return target length if separator is
717 * not found.
718 */
719 if (ip[0] >= length)
720 return length;
721
722 i = target.indexOf(separator, ip[0]);
723
724 return (i != -1) ? i : length;
725 }
726
727 protected String input; /* input string to match (perl $_, GC root) */
728 protected boolean multiline; /* whether input contains newlines (perl $*) */
729 protected SubString[] parens; /* Vector of SubString; last set of parens
730 matched (perl $1, $2) */
731 protected SubString lastMatch; /* last string matched (perl $&) */
732 protected SubString lastParen; /* last paren matched (perl $+) */
733 protected SubString leftContext; /* input to left of last match (perl $`) */
734 protected SubString rightContext; /* input to right of last match (perl $') */
735 }
736
737
738 final class GlobData
739 {
740 int mode; /* input: return index, match object, or void */
741 boolean global; /* output: whether regexp was global */
742 String str; /* output: 'this' parameter object as string */
743
744 // match-specific data
745
746 Scriptable arrayobj;
747
748 // replace-specific data
749
750 Function lambda; /* replacement function object or null */
751 String repstr; /* replacement string */
752 int dollar = -1; /* -1 or index of first $ in repstr */
753 StringBuilder charBuf; /* result characters, null initially */
754 int leftIndex; /* leftContext index, always 0 for JS1.2 */
755 }