~ubuntu-branches/ubuntu/karmic/rhino/karmic

« back to all changes in this revision

Viewing changes to src/org/mozilla/javascript/regexp/RegExpImpl.java

  • Committer: Bazaar Package Importer
  • Author(s): Jerry Haltom
  • Date: 2005-03-19 16:56:07 UTC
  • mto: (11.1.1 squeeze)
  • mto: This revision was merged to the branch mainline in revision 3.
  • Revision ID: james.westby@ubuntu.com-20050319165607-geu3j3fnqlkpqkh1
Tags: upstream-1.6.R1
ImportĀ upstreamĀ versionĀ 1.6.R1

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2
 
 *
3
 
 * The contents of this file are subject to the Netscape Public
4
 
 * License Version 1.1 (the "License"); you may not use this file
5
 
 * except in compliance with the License. You may obtain a copy of
6
 
 * the License at http://www.mozilla.org/NPL/
7
 
 *
8
 
 * Software distributed under the License is distributed on an "AS
9
 
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
10
 
 * implied. See the License for the specific language governing
11
 
 * rights and limitations under the License.
12
 
 *
13
 
 * The Original Code is Rhino code, released
14
 
 * May 6, 1998.
15
 
 *
16
 
 * The Initial Developer of the Original Code is Netscape
17
 
 * Communications Corporation.  Portions created by Netscape are
18
 
 * Copyright (C) 1997-1999 Netscape Communications Corporation. All
19
 
 * Rights Reserved.
20
 
 *
21
 
 * Contributor(s): 
22
 
 *
23
 
 * Alternatively, the contents of this file may be used under the
24
 
 * terms of the GNU Public License (the "GPL"), in which case the
25
 
 * provisions of the GPL are applicable instead of those above.
26
 
 * If you wish to allow use of your version of this file only
27
 
 * under the terms of the GPL and not to allow others to use your
28
 
 * version of this file under the NPL, indicate your decision by
29
 
 * deleting the provisions above and replace them with the notice
30
 
 * and other provisions required by the GPL.  If you do not delete
31
 
 * the provisions above, a recipient may use your version of this
32
 
 * file under either the NPL or the GPL.
33
 
 */
34
 
 
35
 
package org.mozilla.javascript.regexp;
36
 
 
37
 
import org.mozilla.javascript.*;
38
 
import java.util.Vector;
39
 
 
40
 
/**
41
 
 * 
42
 
 */
43
 
public class RegExpImpl implements RegExpProxy {
44
 
    
45
 
    public RegExpImpl() {
46
 
        parens = new Vector(9);
47
 
    }
48
 
    
49
 
    public boolean isRegExp(Object obj) {
50
 
        return obj instanceof NativeRegExp;
51
 
    }
52
 
 
53
 
    public Object newRegExp(Context cx, Scriptable scope, String source, 
54
 
                                                String global, boolean flat)
55
 
    {
56
 
        return new NativeRegExp(cx, scope, source, global, flat);
57
 
    }
58
 
    
59
 
    public Object match(Context cx, Scriptable scope, 
60
 
                        Scriptable thisObj, Object[] args)
61
 
        throws JavaScriptException
62
 
    {
63
 
        MatchData mdata = new MatchData();
64
 
        mdata.optarg = 1;
65
 
        mdata.mode = GlobData.GLOB_MATCH;
66
 
        mdata.parent = ScriptableObject.getTopLevelScope(scope);
67
 
        Object rval = matchOrReplace(cx, scope, thisObj, args,
68
 
                                     this, mdata, false);
69
 
        return mdata.arrayobj == null ? rval : mdata.arrayobj;
70
 
    }
71
 
 
72
 
    public Object search(Context cx, Scriptable scope,
73
 
                         Scriptable thisObj, Object[] args)
74
 
        throws JavaScriptException
75
 
    {
76
 
        MatchData mdata = new MatchData();
77
 
        mdata.optarg = 1;
78
 
        mdata.mode = GlobData.GLOB_SEARCH;
79
 
        mdata.parent = ScriptableObject.getTopLevelScope(scope);
80
 
        return matchOrReplace(cx, scope, thisObj, args, this, mdata, false);
81
 
    }
82
 
 
83
 
    public Object replace(Context cx, Scriptable scope, 
84
 
                          Scriptable thisObj, Object[] args)
85
 
        throws JavaScriptException
86
 
    {
87
 
        Object arg1 = args.length < 2 ? Undefined.instance : args[1];
88
 
        String repstr = null;
89
 
        Function lambda = null;
90
 
        if (arg1 instanceof Function) {
91
 
            lambda = (Function) arg1;
92
 
        } else {
93
 
            repstr = ScriptRuntime.toString(arg1);
94
 
        }
95
 
 
96
 
        ReplaceData rdata = new ReplaceData();
97
 
        rdata.optarg = 2;
98
 
        rdata.mode = GlobData.GLOB_REPLACE;
99
 
        rdata.lambda = lambda;
100
 
        rdata.repstr = repstr == null ? null : repstr.toCharArray();
101
 
        rdata.dollar = repstr == null ? -1 : repstr.indexOf('$');
102
 
        rdata.charArray = null;
103
 
        rdata.length = 0;
104
 
        rdata.index = 0;
105
 
        rdata.leftIndex = 0;
106
 
        Object val = matchOrReplace(cx, scope, thisObj, args,
107
 
                                    this, rdata, true);
108
 
        char[] charArray;
109
 
 
110
 
        if (rdata.charArray == null) {
111
 
            if (rdata.global || val == null || !val.equals(Boolean.TRUE)) {
112
 
                /* Didn't match even once. */
113
 
                return rdata.str;
114
 
            }
115
 
            int leftlen = this.leftContext.length;
116
 
            int length = leftlen + rdata.findReplen(cx, this);
117
 
            charArray = new char[length];
118
 
            SubString leftContext = this.leftContext;
119
 
            System.arraycopy(leftContext.charArray, leftContext.index,
120
 
                             charArray, 0, leftlen);
121
 
            rdata.doReplace(cx, this, charArray, leftlen);
122
 
            rdata.charArray = charArray;
123
 
            rdata.length = length;
124
 
        }
125
 
 
126
 
        SubString rc = this.rightContext;
127
 
        int rightlen = rc.length;
128
 
        int length = rdata.length + rightlen;
129
 
        charArray = new char[length];
130
 
        System.arraycopy(rdata.charArray, 0,
131
 
                         charArray, 0, rdata.charArray.length);
132
 
        System.arraycopy(rc.charArray, rc.index, charArray,
133
 
                         rdata.length, rightlen);
134
 
        return new String(charArray, 0, length);
135
 
    }
136
 
 
137
 
    /**
138
 
     * Analog of C match_or_replace.
139
 
     */
140
 
    private static Object matchOrReplace(Context cx, Scriptable scope,
141
 
                                         Scriptable thisObj, Object[] args, 
142
 
                                         RegExpImpl reImpl,
143
 
                                         GlobData data, boolean forceFlat)
144
 
        throws JavaScriptException
145
 
    {
146
 
        NativeRegExp re;
147
 
 
148
 
        String str = ScriptRuntime.toString(thisObj);
149
 
        data.str = str;
150
 
        Scriptable topScope = ScriptableObject.getTopLevelScope(scope);
151
 
        
152
 
        if (args.length == 0)
153
 
            re = new NativeRegExp(cx, topScope, "", "", false);
154
 
        else
155
 
            if (args[0] instanceof NativeRegExp) {
156
 
                re = (NativeRegExp) args[0];
157
 
            } else {
158
 
                String src = ScriptRuntime.toString(args[0]);
159
 
                String opt;
160
 
                if (data.optarg < args.length) {
161
 
                    args[0] = src;
162
 
                    opt = ScriptRuntime.toString(args[data.optarg]);
163
 
                } else {
164
 
                    opt = null;
165
 
                }                
166
 
                re = new NativeRegExp(cx, topScope, src, opt, forceFlat);
167
 
            }
168
 
        data.regexp = re;
169
 
 
170
 
        data.global = (re.getFlags() & NativeRegExp.GLOB) != 0;
171
 
        int[] indexp = { 0 };
172
 
        Object result = null;
173
 
        if (data.mode == GlobData.GLOB_SEARCH) {
174
 
            result = re.executeRegExp(cx, scope, reImpl,
175
 
                                      str, indexp, NativeRegExp.TEST);
176
 
            if (result != null && result.equals(Boolean.TRUE))
177
 
                result = new Integer(reImpl.leftContext.length);
178
 
            else
179
 
                result = new Integer(-1);
180
 
        } else if (data.global) {
181
 
            re.setLastIndex(0);
182
 
            for (int count = 0; indexp[0] <= str.length(); count++) {
183
 
                result = re.executeRegExp(cx, scope, reImpl,
184
 
                                          str, indexp, NativeRegExp.TEST);
185
 
                if (result == null || !result.equals(Boolean.TRUE))
186
 
                    break;
187
 
                data.doGlobal(cx, scope, count, reImpl);
188
 
                if (reImpl.lastMatch.length == 0) {
189
 
                    if (indexp[0] == str.length())
190
 
                        break;
191
 
                    indexp[0]++;
192
 
                }
193
 
            }
194
 
        } else {
195
 
            result = re.executeRegExp(cx, scope, reImpl, str, indexp,
196
 
                                      ((data.mode == GlobData.GLOB_REPLACE) 
197
 
                                       ? NativeRegExp.TEST 
198
 
                                       : NativeRegExp.MATCH));
199
 
        }
200
 
 
201
 
        return result;
202
 
    } 
203
 
    
204
 
    
205
 
    
206
 
    public int find_split(Scriptable scope, String target, String separator, 
207
 
                          Object reObj, int[] ip, int[] matchlen, 
208
 
                          boolean[] matched, String[][] parensp)
209
 
    {
210
 
        int i = ip[0];
211
 
        int length = target.length();
212
 
        int result;
213
 
        Context cx = Context.getCurrentContext();
214
 
 
215
 
        int version = cx.getLanguageVersion();
216
 
        NativeRegExp re = (NativeRegExp) reObj;
217
 
        again:
218
 
        while (true) {  // imitating C label
219
 
            /* JS1.2 deviated from Perl by never matching at end of string. */
220
 
            int ipsave = ip[0]; // reuse ip to save object creation
221
 
            ip[0] = i;
222
 
            Object ret = re.executeRegExp(cx, scope, this, target, ip,
223
 
                                          NativeRegExp.TEST);
224
 
            if (ret != Boolean.TRUE) {
225
 
                // Mismatch: ensure our caller advances i past end of string.
226
 
                ip[0] = ipsave;
227
 
                matchlen[0] = 1;
228
 
                matched[0] = false;
229
 
                return length;
230
 
            }
231
 
            i = ip[0];
232
 
            ip[0] = ipsave;
233
 
            matched[0] = true;
234
 
 
235
 
            SubString sep = this.lastMatch;
236
 
            matchlen[0] = sep.length;
237
 
            if (matchlen[0] == 0) {
238
 
                /*
239
 
                 * Empty string match: never split on an empty
240
 
                 * match at the start of a find_split cycle.  Same
241
 
                 * rule as for an empty global match in
242
 
                 * match_or_replace.
243
 
                 */
244
 
                if (i == ip[0]) {
245
 
                    /*
246
 
                     * "Bump-along" to avoid sticking at an empty
247
 
                     * match, but don't bump past end of string --
248
 
                     * our caller must do that by adding
249
 
                     * sep->length to our return value.
250
 
                     */
251
 
                    if (i == length) {
252
 
                        if (version == Context.VERSION_1_2) {
253
 
                            matchlen[0] = 1;
254
 
                            result = i;
255
 
                        }
256
 
                        else
257
 
                            result = -1;
258
 
                        break;
259
 
                    }
260
 
                    i++;
261
 
                    continue again; // imitating C goto
262
 
                }
263
 
            }
264
 
            // PR_ASSERT((size_t)i >= sep->length);
265
 
            result = i - matchlen[0];
266
 
            break;
267
 
        }
268
 
        int size = parens.size();
269
 
        parensp[0] = new String[size];
270
 
        for (int num = 0; num < size; num++) {
271
 
            SubString parsub = getParenSubString(num);
272
 
            parensp[0][num] = parsub.toString();
273
 
        }
274
 
        return result;
275
 
    }
276
 
    
277
 
    /**
278
 
     * Analog of REGEXP_PAREN_SUBSTRING in C jsregexp.h.
279
 
     * Assumes zero-based; i.e., for $3, i==2
280
 
     */
281
 
    SubString getParenSubString(int i) {
282
 
        if (i >= parens.size())
283
 
            return SubString.emptySubString;
284
 
        return (SubString) parens.elementAt(i);
285
 
    }
286
 
 
287
 
    String          input;         /* input string to match (perl $_, GC root) */
288
 
    boolean         multiline;     /* whether input contains newlines (perl $*) */
289
 
    Vector          parens;        /* Vector of SubString; last set of parens
290
 
                                      matched (perl $1, $2) */
291
 
    SubString       lastMatch;     /* last string matched (perl $&) */
292
 
    SubString       lastParen;     /* last paren matched (perl $+) */
293
 
    SubString       leftContext;   /* input to left of last match (perl $`) */
294
 
    SubString       rightContext;  /* input to right of last match (perl $') */
295
 
}
296
 
 
297
 
 
298
 
abstract class GlobData {
299
 
    static final int GLOB_MATCH =      1;
300
 
    static final int GLOB_REPLACE =    2;
301
 
    static final int GLOB_SEARCH =     3;
302
 
 
303
 
    abstract void doGlobal(Context cx, Scriptable scope, int count, 
304
 
                           RegExpImpl reImpl) 
305
 
        throws JavaScriptException;
306
 
 
307
 
    byte     mode;      /* input: return index, match object, or void */
308
 
    int      optarg;    /* input: index of optional flags argument */
309
 
    boolean  global;    /* output: whether regexp was global */
310
 
    String   str;       /* output: 'this' parameter object as string */
311
 
    NativeRegExp regexp;/* output: regexp parameter object private data */
312
 
    Scriptable parent;
313
 
}
314
 
 
315
 
 
316
 
class MatchData extends GlobData {
317
 
 
318
 
    /*
319
 
     * Analog of match_glob() in jsstr.c
320
 
     */
321
 
    void doGlobal(Context cx, Scriptable scope, int count, RegExpImpl reImpl) 
322
 
        throws JavaScriptException 
323
 
    {
324
 
        MatchData mdata;
325
 
        Object v;
326
 
 
327
 
        mdata = this;
328
 
        if (arrayobj == null) {
329
 
            Scriptable s = ScriptableObject.getTopLevelScope(scope);
330
 
            arrayobj = ScriptRuntime.newObject(cx, s, "Array", null);
331
 
        }
332
 
        SubString matchsub = reImpl.lastMatch;
333
 
        String matchstr = matchsub.toString();
334
 
        arrayobj.put(count, arrayobj, matchstr);
335
 
    }
336
 
 
337
 
    Scriptable arrayobj;
338
 
}
339
 
 
340
 
 
341
 
class ReplaceData extends GlobData {
342
 
 
343
 
    ReplaceData() {
344
 
        dollar = -1;
345
 
    }
346
 
 
347
 
    /*
348
 
     * Analog of replace_glob() in jsstr.c
349
 
     */
350
 
    void doGlobal(Context cx, Scriptable scope, int count, RegExpImpl reImpl) 
351
 
        throws JavaScriptException
352
 
    {
353
 
        ReplaceData rdata = this;
354
 
 
355
 
        SubString lc = reImpl.leftContext;
356
 
 
357
 
        char[] leftArray = lc.charArray;
358
 
        int leftIndex = rdata.leftIndex;
359
 
        
360
 
        int leftlen = reImpl.lastMatch.index - leftIndex;
361
 
        rdata.leftIndex = reImpl.lastMatch.index + reImpl.lastMatch.length;
362
 
        int replen = findReplen(cx, reImpl);
363
 
        int growth = leftlen + replen;
364
 
        char[] charArray;
365
 
        if (rdata.charArray != null) {
366
 
            charArray = new char[rdata.length + growth];
367
 
            System.arraycopy(rdata.charArray, 0, charArray, 0, rdata.length);
368
 
        } else {
369
 
            charArray = new char[growth];
370
 
        }
371
 
 
372
 
        rdata.charArray = charArray;
373
 
        rdata.length += growth;
374
 
        int index = rdata.index;
375
 
        rdata.index += growth;
376
 
        System.arraycopy(leftArray, leftIndex, charArray, index, leftlen);
377
 
        index += leftlen;
378
 
        doReplace(cx, reImpl, charArray, index);
379
 
    }
380
 
 
381
 
    static SubString dollarStr = new SubString("$");
382
 
 
383
 
    static SubString interpretDollar(Context cx, RegExpImpl res, 
384
 
                                     char[] da, int dp, int bp, int[] skip)
385
 
    {
386
 
        char[] ca;
387
 
        int cp;
388
 
        char dc;
389
 
        int num, tmp;
390
 
 
391
 
        /* Allow a real backslash (literal "\\") to escape "$1" etc. */
392
 
        if (da[dp] != '$')
393
 
            throw new RuntimeException();
394
 
        if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
395
 
                 && (cx.getLanguageVersion() <= Context.VERSION_1_4))
396
 
            if (dp > bp && da[dp-1] == '\\')
397
 
                return null;
398
 
 
399
 
        /* Interpret all Perl match-induced dollar variables. */
400
 
        dc = da[dp+1];
401
 
        if (NativeRegExp.isDigit(dc)) {            
402
 
            if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
403
 
                     && (cx.getLanguageVersion() <= Context.VERSION_1_4)) {
404
 
                if (dc == '0')
405
 
                    return null;
406
 
                /* Check for overflow to avoid gobbling arbitrary decimal digits. */
407
 
                num = 0;
408
 
                ca = da;
409
 
                cp = dp;
410
 
                while (++cp < ca.length && NativeRegExp.isDigit(dc = ca[cp])) {
411
 
                    tmp = 10 * num + NativeRegExp.unDigit(dc);
412
 
                    if (tmp < num)
413
 
                        break;
414
 
                    num = tmp;
415
 
                }
416
 
            }
417
 
            else {  /* ECMA 3, 1-9 or 01-99 */
418
 
                num = NativeRegExp.unDigit(dc);
419
 
                cp = dp + 2;
420
 
                if ((dp + 2) < da.length) {
421
 
                    dc = da[dp + 2];
422
 
                    if (NativeRegExp.isDigit(dc)) {
423
 
                        num = 10 * num + NativeRegExp.unDigit(dc);
424
 
                        cp++;
425
 
                    }
426
 
                }
427
 
                if (num == 0) return null;  /* $0 or $00 is not valid */
428
 
            }
429
 
            /* Adjust num from 1 $n-origin to 0 array-index-origin. */
430
 
            num--;
431
 
            skip[0] = cp - dp;
432
 
            return res.getParenSubString(num);
433
 
        }
434
 
 
435
 
        skip[0] = 2;
436
 
        switch (dc) {
437
 
          case '$':
438
 
            return dollarStr;
439
 
          case '&':
440
 
            return res.lastMatch;
441
 
          case '+':
442
 
            return res.lastParen;
443
 
          case '`':
444
 
            if (cx.getLanguageVersion() == Context.VERSION_1_2) {
445
 
                /*
446
 
                 * JS1.2 imitated the Perl4 bug where left context at each step
447
 
                 * in an iterative use of a global regexp started from last match,
448
 
                 * not from the start of the target string.  But Perl4 does start
449
 
                 * $` at the beginning of the target string when it is used in a
450
 
                 * substitution, so we emulate that special case here.
451
 
                 */
452
 
                res.leftContext.index = 0;
453
 
                res.leftContext.length = res.lastMatch.index;
454
 
            }
455
 
            return res.leftContext;
456
 
          case '\'':
457
 
            return res.rightContext;
458
 
        }
459
 
        return null;
460
 
    }
461
 
 
462
 
    /**
463
 
     * Corresponds to find_replen in jsstr.c. rdata is 'this', and
464
 
     * the result parameter sizep is the return value (errors are
465
 
     * propagated with exceptions).
466
 
     */
467
 
    int findReplen(Context cx, RegExpImpl reImpl)
468
 
        throws JavaScriptException
469
 
    {
470
 
        if (lambda != null) {
471
 
            // invoke lambda function with args lastMatch, $1, $2, ... $n,
472
 
            // leftContext.length, whole string.
473
 
            Vector parens = reImpl.parens;
474
 
            int parenCount = parens.size();
475
 
            Object[] args = new Object[parenCount + 3];
476
 
            args[0] = reImpl.lastMatch.toString();
477
 
            for (int i=0; i < parenCount; i++) {
478
 
                SubString sub = (SubString) parens.elementAt(i);
479
 
                args[i+1] = sub.toString();
480
 
            }
481
 
            args[parenCount+1] = new Integer(reImpl.leftContext.length);
482
 
            args[parenCount+2] = str;
483
 
            Scriptable parent = lambda.getParentScope();
484
 
            Object result = lambda.call(cx, parent, parent, args);
485
 
 
486
 
            this.repstr = ScriptRuntime.toString(result).toCharArray();
487
 
            return this.repstr.length;
488
 
        }
489
 
 
490
 
        int replen = this.repstr.length;
491
 
        if (dollar == -1)
492
 
            return replen;
493
 
 
494
 
        int bp = 0;
495
 
        for (int dp = dollar; dp < this.repstr.length ; ) {
496
 
            char c = this.repstr[dp];
497
 
            if (c != '$') {
498
 
                dp++;
499
 
                continue;
500
 
            }
501
 
            int[] skip = { 0 };
502
 
            SubString sub = interpretDollar(cx, reImpl, this.repstr, dp,
503
 
                                            bp, skip);
504
 
            if (sub != null) {
505
 
                replen += sub.length - skip[0];
506
 
                dp += skip[0];
507
 
            }
508
 
            else
509
 
                dp++;
510
 
        }
511
 
        return replen;
512
 
    }
513
 
 
514
 
    /**
515
 
     * Analog of do_replace in jsstr.c
516
 
     */
517
 
    void doReplace(Context cx, RegExpImpl regExpImpl, char[] charArray,
518
 
                   int arrayIndex)
519
 
    {
520
 
        int cp = 0;
521
 
        char[] da = repstr;
522
 
        int dp = this.dollar;
523
 
        int bp = cp;
524
 
        if (dp != -1) {
525
 
          outer:
526
 
            for (;;) {
527
 
                int len = dp - cp;
528
 
                System.arraycopy(repstr, cp, charArray, arrayIndex,
529
 
                                 len);
530
 
                arrayIndex += len;
531
 
                cp = dp;
532
 
                int[] skip = { 0 };
533
 
                SubString sub = interpretDollar(cx, regExpImpl, da,
534
 
                                                dp, bp, skip);
535
 
                if (sub != null) {
536
 
                    len = sub.length;
537
 
                    if (len > 0) {
538
 
                        System.arraycopy(sub.charArray, sub.index, charArray,
539
 
                                         arrayIndex, len);
540
 
                    }
541
 
                    arrayIndex += len;
542
 
                    cp += skip[0];
543
 
                    dp += skip[0];
544
 
                }
545
 
                else
546
 
                    dp++;
547
 
                if (dp >= repstr.length) break;
548
 
                while (repstr[dp] != '$') {
549
 
                    dp++;
550
 
                    if (dp >= repstr.length) break outer;
551
 
                }
552
 
            }
553
 
        }
554
 
        if (repstr.length > cp) {
555
 
            System.arraycopy(repstr, cp, charArray, arrayIndex,
556
 
                             repstr.length - cp);
557
 
        }
558
 
    }
559
 
 
560
 
    Function    lambda;        /* replacement function object or null */
561
 
    char[]      repstr;        /* replacement string */
562
 
    int         dollar;        /* -1 or index of first $ in repstr */
563
 
    char[]      charArray;     /* result characters, null initially */
564
 
    int         length;        /* result length, 0 initially */
565
 
    int         index;         /* index in result of next replacement */
566
 
    int         leftIndex;     /* leftContext index, always 0 for JS1.2 */
567
 
}
 
1
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 
2
 *
 
3
 * The contents of this file are subject to the Netscape Public
 
4
 * License Version 1.1 (the "License"); you may not use this file
 
5
 * except in compliance with the License. You may obtain a copy of
 
6
 * the License at http://www.mozilla.org/NPL/
 
7
 *
 
8
 * Software distributed under the License is distributed on an "AS
 
9
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 
10
 * implied. See the License for the specific language governing
 
11
 * rights and limitations under the License.
 
12
 *
 
13
 * The Original Code is Rhino code, released
 
14
 * May 6, 1998.
 
15
 *
 
16
 * The Initial Developer of the Original Code is Netscape
 
17
 * Communications Corporation.  Portions created by Netscape are
 
18
 * Copyright (C) 1997-1999 Netscape Communications Corporation. All
 
19
 * Rights Reserved.
 
20
 *
 
21
 * Contributor(s):
 
22
 *
 
23
 * Alternatively, the contents of this file may be used under the
 
24
 * terms of the GNU Public License (the "GPL"), in which case the
 
25
 * provisions of the GPL are applicable instead of those above.
 
26
 * If you wish to allow use of your version of this file only
 
27
 * under the terms of the GPL and not to allow others to use your
 
28
 * version of this file under the NPL, indicate your decision by
 
29
 * deleting the provisions above and replace them with the notice
 
30
 * and other provisions required by the GPL.  If you do not delete
 
31
 * the provisions above, a recipient may use your version of this
 
32
 * file under either the NPL or the GPL.
 
33
 */
 
34
 
 
35
package org.mozilla.javascript.regexp;
 
36
 
 
37
import org.mozilla.javascript.*;
 
38
 
 
39
/**
 
40
 *
 
41
 */
 
42
public class RegExpImpl implements RegExpProxy {
 
43
 
 
44
    public boolean isRegExp(Scriptable obj) {
 
45
        return obj instanceof NativeRegExp;
 
46
    }
 
47
 
 
48
    public Object compileRegExp(Context cx, String source, String flags)
 
49
    {
 
50
        return NativeRegExp.compileRE(source, flags, false);
 
51
    }
 
52
 
 
53
    public Scriptable wrapRegExp(Context cx, Scriptable scope,
 
54
                                 Object compiled)
 
55
    {
 
56
        return new NativeRegExp(scope, compiled);
 
57
    }
 
58
 
 
59
    public Object action(Context cx, Scriptable scope,
 
60
                         Scriptable thisObj, Object[] args,
 
61
                         int actionType)
 
62
    {
 
63
        GlobData data = new GlobData();
 
64
        data.mode = actionType;
 
65
 
 
66
        switch (actionType) {
 
67
          case RA_MATCH:
 
68
            {
 
69
                Object rval;
 
70
                data.optarg = 1;
 
71
                rval = matchOrReplace(cx, scope, thisObj, args,
 
72
                                      this, data, false);
 
73
                return data.arrayobj == null ? rval : data.arrayobj;
 
74
            }
 
75
 
 
76
          case RA_SEARCH:
 
77
            data.optarg = 1;
 
78
            return matchOrReplace(cx, scope, thisObj, args,
 
79
                                  this, data, false);
 
80
 
 
81
          case RA_REPLACE:
 
82
            {
 
83
                Object arg1 = args.length < 2 ? Undefined.instance : args[1];
 
84
                String repstr = null;
 
85
                Function lambda = null;
 
86
                if (arg1 instanceof Function) {
 
87
                    lambda = (Function) arg1;
 
88
                } else {
 
89
                    repstr = ScriptRuntime.toString(arg1);
 
90
                }
 
91
 
 
92
                data.optarg = 2;
 
93
                data.lambda = lambda;
 
94
                data.repstr = repstr;
 
95
                data.dollar = repstr == null ? -1 : repstr.indexOf('$');
 
96
                data.charBuf = null;
 
97
                data.leftIndex = 0;
 
98
                Object val = matchOrReplace(cx, scope, thisObj, args,
 
99
                                            this, data, true);
 
100
                SubString rc = this.rightContext;
 
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
                data.charBuf.append(rc.charArray, rc.index, rc.length);
 
113
                return data.charBuf.toString();
 
114
            }
 
115
 
 
116
          default:
 
117
            throw Kit.codeBug();
 
118
        }
 
119
    }
 
120
 
 
121
    /**
 
122
     * Analog of C match_or_replace.
 
123
     */
 
124
    private static Object matchOrReplace(Context cx, Scriptable scope,
 
125
                                         Scriptable thisObj, Object[] args,
 
126
                                         RegExpImpl reImpl,
 
127
                                         GlobData data, boolean forceFlat)
 
128
    {
 
129
        NativeRegExp re;
 
130
 
 
131
        String str = ScriptRuntime.toString(thisObj);
 
132
        data.str = str;
 
133
        Scriptable topScope = ScriptableObject.getTopLevelScope(scope);
 
134
 
 
135
        if (args.length == 0) {
 
136
            Object compiled = NativeRegExp.compileRE("", "", false);
 
137
            re = new NativeRegExp(topScope, compiled);
 
138
        } else if (args[0] instanceof NativeRegExp) {
 
139
            re = (NativeRegExp) args[0];
 
140
        } else {
 
141
            String src = ScriptRuntime.toString(args[0]);
 
142
            String opt;
 
143
            if (data.optarg < args.length) {
 
144
                args[0] = src;
 
145
                opt = ScriptRuntime.toString(args[data.optarg]);
 
146
            } else {
 
147
                opt = null;
 
148
            }
 
149
            Object compiled = NativeRegExp.compileRE(src, opt, forceFlat);
 
150
            re = new NativeRegExp(topScope, compiled);
 
151
        }
 
152
        data.regexp = re;
 
153
 
 
154
        data.global = (re.getFlags() & NativeRegExp.JSREG_GLOB) != 0;
 
155
        int[] indexp = { 0 };
 
156
        Object result = null;
 
157
        if (data.mode == RA_SEARCH) {
 
158
            result = re.executeRegExp(cx, scope, reImpl,
 
159
                                      str, indexp, NativeRegExp.TEST);
 
160
            if (result != null && result.equals(Boolean.TRUE))
 
161
                result = new Integer(reImpl.leftContext.length);
 
162
            else
 
163
                result = new Integer(-1);
 
164
        } else if (data.global) {
 
165
            re.lastIndex = 0;
 
166
            for (int count = 0; indexp[0] <= str.length(); count++) {
 
167
                result = re.executeRegExp(cx, scope, reImpl,
 
168
                                          str, indexp, NativeRegExp.TEST);
 
169
                if (result == null || !result.equals(Boolean.TRUE))
 
170
                    break;
 
171
                if (data.mode == RA_MATCH) {
 
172
                    match_glob(data, cx, scope, count, reImpl);
 
173
                } else {
 
174
                    if (data.mode != RA_REPLACE) Kit.codeBug();
 
175
                    SubString lastMatch = reImpl.lastMatch;
 
176
                    int leftIndex = data.leftIndex;
 
177
                    int leftlen = lastMatch.index - leftIndex;
 
178
                    data.leftIndex = lastMatch.index + lastMatch.length;
 
179
                    replace_glob(data, cx, scope, reImpl, leftIndex, leftlen);
 
180
                }
 
181
                if (reImpl.lastMatch.length == 0) {
 
182
                    if (indexp[0] == str.length())
 
183
                        break;
 
184
                    indexp[0]++;
 
185
                }
 
186
            }
 
187
        } else {
 
188
            result = re.executeRegExp(cx, scope, reImpl, str, indexp,
 
189
                                      ((data.mode == RA_REPLACE)
 
190
                                       ? NativeRegExp.TEST
 
191
                                       : NativeRegExp.MATCH));
 
192
        }
 
193
 
 
194
        return result;
 
195
    }
 
196
 
 
197
 
 
198
 
 
199
    public int find_split(Context cx, Scriptable scope, String target,
 
200
                          String separator, Scriptable reObj,
 
201
                          int[] ip, int[] matchlen,
 
202
                          boolean[] matched, String[][] parensp)
 
203
    {
 
204
        int i = ip[0];
 
205
        int length = target.length();
 
206
        int result;
 
207
 
 
208
        int version = cx.getLanguageVersion();
 
209
        NativeRegExp re = (NativeRegExp) reObj;
 
210
        again:
 
211
        while (true) {  // imitating C label
 
212
            /* JS1.2 deviated from Perl by never matching at end of string. */
 
213
            int ipsave = ip[0]; // reuse ip to save object creation
 
214
            ip[0] = i;
 
215
            Object ret = re.executeRegExp(cx, scope, this, target, ip,
 
216
                                          NativeRegExp.TEST);
 
217
            if (ret != Boolean.TRUE) {
 
218
                // Mismatch: ensure our caller advances i past end of string.
 
219
                ip[0] = ipsave;
 
220
                matchlen[0] = 1;
 
221
                matched[0] = false;
 
222
                return length;
 
223
            }
 
224
            i = ip[0];
 
225
            ip[0] = ipsave;
 
226
            matched[0] = true;
 
227
 
 
228
            SubString sep = this.lastMatch;
 
229
            matchlen[0] = sep.length;
 
230
            if (matchlen[0] == 0) {
 
231
                /*
 
232
                 * Empty string match: never split on an empty
 
233
                 * match at the start of a find_split cycle.  Same
 
234
                 * rule as for an empty global match in
 
235
                 * match_or_replace.
 
236
                 */
 
237
                if (i == ip[0]) {
 
238
                    /*
 
239
                     * "Bump-along" to avoid sticking at an empty
 
240
                     * match, but don't bump past end of string --
 
241
                     * our caller must do that by adding
 
242
                     * sep->length to our return value.
 
243
                     */
 
244
                    if (i == length) {
 
245
                        if (version == Context.VERSION_1_2) {
 
246
                            matchlen[0] = 1;
 
247
                            result = i;
 
248
                        }
 
249
                        else
 
250
                            result = -1;
 
251
                        break;
 
252
                    }
 
253
                    i++;
 
254
                    continue again; // imitating C goto
 
255
                }
 
256
            }
 
257
            // PR_ASSERT((size_t)i >= sep->length);
 
258
            result = i - matchlen[0];
 
259
            break;
 
260
        }
 
261
        int size = (parens == null) ? 0 : parens.length;
 
262
        parensp[0] = new String[size];
 
263
        for (int num = 0; num < size; num++) {
 
264
            SubString parsub = getParenSubString(num);
 
265
            parensp[0][num] = parsub.toString();
 
266
        }
 
267
        return result;
 
268
    }
 
269
 
 
270
    /**
 
271
     * Analog of REGEXP_PAREN_SUBSTRING in C jsregexp.h.
 
272
     * Assumes zero-based; i.e., for $3, i==2
 
273
     */
 
274
    SubString getParenSubString(int i)
 
275
    {
 
276
        if (parens != null && i < parens.length) {
 
277
            SubString parsub = parens[i];
 
278
            if (parsub != null) {
 
279
                return parsub;
 
280
            }
 
281
        }
 
282
        return SubString.emptySubString;
 
283
    }
 
284
 
 
285
    /*
 
286
     * Analog of match_glob() in jsstr.c
 
287
     */
 
288
    private static void match_glob(GlobData mdata, Context cx,
 
289
                                   Scriptable scope, int count,
 
290
                                   RegExpImpl reImpl)
 
291
    {
 
292
        if (mdata.arrayobj == null) {
 
293
            Scriptable s = ScriptableObject.getTopLevelScope(scope);
 
294
            mdata.arrayobj = ScriptRuntime.newObject(cx, s, "Array", null);
 
295
        }
 
296
        SubString matchsub = reImpl.lastMatch;
 
297
        String matchstr = matchsub.toString();
 
298
        mdata.arrayobj.put(count, mdata.arrayobj, matchstr);
 
299
    }
 
300
 
 
301
    /*
 
302
     * Analog of replace_glob() in jsstr.c
 
303
     */
 
304
    private static void replace_glob(GlobData rdata, Context cx,
 
305
                                     Scriptable scope, RegExpImpl reImpl,
 
306
                                     int leftIndex, int leftlen)
 
307
    {
 
308
        int replen;
 
309
        String lambdaStr;
 
310
        if (rdata.lambda != null) {
 
311
            // invoke lambda function with args lastMatch, $1, $2, ... $n,
 
312
            // leftContext.length, whole string.
 
313
            SubString[] parens = reImpl.parens;
 
314
            int parenCount = (parens == null) ? 0 : parens.length;
 
315
            Object[] args = new Object[parenCount + 3];
 
316
            args[0] = reImpl.lastMatch.toString();
 
317
            for (int i=0; i < parenCount; i++) {
 
318
                SubString sub = parens[i];
 
319
                if (sub != null) {
 
320
                    args[i+1] = sub.toString();
 
321
                } else {
 
322
                    args[i+1] = Undefined.instance;
 
323
                }
 
324
            }
 
325
            args[parenCount+1] = new Integer(reImpl.leftContext.length);
 
326
            args[parenCount+2] = rdata.str;
 
327
            Scriptable parent = ScriptableObject.getTopLevelScope(scope);
 
328
            Object result = rdata.lambda.call(cx, parent, parent, args);
 
329
            lambdaStr = ScriptRuntime.toString(result);
 
330
            replen = lambdaStr.length();
 
331
        } else {
 
332
            lambdaStr = null;
 
333
            replen = rdata.repstr.length();
 
334
            if (rdata.dollar >= 0) {
 
335
                int[] skip = new int[1];
 
336
                int dp = rdata.dollar;
 
337
                do {
 
338
                    SubString sub = interpretDollar(cx, reImpl, rdata.repstr,
 
339
                                                    dp, skip);
 
340
                    if (sub != null) {
 
341
                        replen += sub.length - skip[0];
 
342
                        dp += skip[0];
 
343
                    } else {
 
344
                        ++dp;
 
345
                    }
 
346
                    dp = rdata.repstr.indexOf('$', dp);
 
347
                } while (dp >= 0);
 
348
            }
 
349
        }
 
350
 
 
351
        int growth = leftlen + replen + reImpl.rightContext.length;
 
352
        StringBuffer charBuf = rdata.charBuf;
 
353
        if (charBuf == null) {
 
354
            charBuf = new StringBuffer(growth);
 
355
            rdata.charBuf = charBuf;
 
356
        } else {
 
357
            charBuf.ensureCapacity(rdata.charBuf.length() + growth);
 
358
        }
 
359
 
 
360
        charBuf.append(reImpl.leftContext.charArray, leftIndex, leftlen);
 
361
        if (rdata.lambda != null) {
 
362
            charBuf.append(lambdaStr);
 
363
        } else {
 
364
            do_replace(rdata, cx, reImpl);
 
365
        }
 
366
    }
 
367
 
 
368
    private static SubString interpretDollar(Context cx, RegExpImpl res,
 
369
                                             String da, int dp, int[] skip)
 
370
    {
 
371
        char dc;
 
372
        int num, tmp;
 
373
 
 
374
        if (da.charAt(dp) != '$') Kit.codeBug();
 
375
 
 
376
        /* Allow a real backslash (literal "\\") to escape "$1" etc. */
 
377
        int version = cx.getLanguageVersion();
 
378
        if (version != Context.VERSION_DEFAULT
 
379
            && version <= Context.VERSION_1_4)
 
380
        {
 
381
            if (dp > 0 && da.charAt(dp - 1) == '\\')
 
382
                return null;
 
383
        }
 
384
        int daL = da.length();
 
385
        if (dp + 1 >= daL)
 
386
            return null;
 
387
        /* Interpret all Perl match-induced dollar variables. */
 
388
        dc = da.charAt(dp + 1);
 
389
        if (NativeRegExp.isDigit(dc)) {
 
390
            int cp;
 
391
            if (version != Context.VERSION_DEFAULT
 
392
                && version <= Context.VERSION_1_4)
 
393
            {
 
394
                if (dc == '0')
 
395
                    return null;
 
396
                /* Check for overflow to avoid gobbling arbitrary decimal digits. */
 
397
                num = 0;
 
398
                cp = dp;
 
399
                while (++cp < daL && NativeRegExp.isDigit(dc = da.charAt(cp)))
 
400
                {
 
401
                    tmp = 10 * num + (dc - '0');
 
402
                    if (tmp < num)
 
403
                        break;
 
404
                    num = tmp;
 
405
                }
 
406
            }
 
407
            else {  /* ECMA 3, 1-9 or 01-99 */
 
408
                int parenCount = (res.parens == null) ? 0 : res.parens.length;
 
409
                num = dc - '0';
 
410
                if (num > parenCount)
 
411
                    return null;
 
412
                cp = dp + 2;
 
413
                if ((dp + 2) < daL) {
 
414
                    dc = da.charAt(dp + 2);
 
415
                    if (NativeRegExp.isDigit(dc)) {
 
416
                        tmp = 10 * num + (dc - '0');
 
417
                        if (tmp <= parenCount) {
 
418
                            cp++;
 
419
                            num = tmp;
 
420
                        }
 
421
                    }
 
422
                }
 
423
                if (num == 0) return null;  /* $0 or $00 is not valid */
 
424
            }
 
425
            /* Adjust num from 1 $n-origin to 0 array-index-origin. */
 
426
            num--;
 
427
            skip[0] = cp - dp;
 
428
            return res.getParenSubString(num);
 
429
        }
 
430
 
 
431
        skip[0] = 2;
 
432
        switch (dc) {
 
433
          case '$':
 
434
            return new SubString("$");
 
435
          case '&':
 
436
            return res.lastMatch;
 
437
          case '+':
 
438
            return res.lastParen;
 
439
          case '`':
 
440
            if (version == Context.VERSION_1_2) {
 
441
                /*
 
442
                 * JS1.2 imitated the Perl4 bug where left context at each step
 
443
                 * in an iterative use of a global regexp started from last match,
 
444
                 * not from the start of the target string.  But Perl4 does start
 
445
                 * $` at the beginning of the target string when it is used in a
 
446
                 * substitution, so we emulate that special case here.
 
447
                 */
 
448
                res.leftContext.index = 0;
 
449
                res.leftContext.length = res.lastMatch.index;
 
450
            }
 
451
            return res.leftContext;
 
452
          case '\'':
 
453
            return res.rightContext;
 
454
        }
 
455
        return null;
 
456
    }
 
457
 
 
458
    /**
 
459
     * Analog of do_replace in jsstr.c
 
460
     */
 
461
    private static void do_replace(GlobData rdata, Context cx,
 
462
                                   RegExpImpl regExpImpl)
 
463
    {
 
464
        StringBuffer charBuf = rdata.charBuf;
 
465
        int cp = 0;
 
466
        String da = rdata.repstr;
 
467
        int dp = rdata.dollar;
 
468
        if (dp != -1) {
 
469
            int[] skip = new int[1];
 
470
            do {
 
471
                int len = dp - cp;
 
472
                charBuf.append(da.substring(cp, dp));
 
473
                cp = dp;
 
474
                SubString sub = interpretDollar(cx, regExpImpl, da,
 
475
                                                dp, skip);
 
476
                if (sub != null) {
 
477
                    len = sub.length;
 
478
                    if (len > 0) {
 
479
                        charBuf.append(sub.charArray, sub.index, len);
 
480
                    }
 
481
                    cp += skip[0];
 
482
                    dp += skip[0];
 
483
                } else {
 
484
                    ++dp;
 
485
                }
 
486
                dp = da.indexOf('$', dp);
 
487
            } while (dp >= 0);
 
488
        }
 
489
        int daL = da.length();
 
490
        if (daL > cp) {
 
491
            charBuf.append(da.substring(cp, daL));
 
492
        }
 
493
    }
 
494
 
 
495
    String          input;         /* input string to match (perl $_, GC root) */
 
496
    boolean         multiline;     /* whether input contains newlines (perl $*) */
 
497
    SubString[]     parens;        /* Vector of SubString; last set of parens
 
498
                                      matched (perl $1, $2) */
 
499
    SubString       lastMatch;     /* last string matched (perl $&) */
 
500
    SubString       lastParen;     /* last paren matched (perl $+) */
 
501
    SubString       leftContext;   /* input to left of last match (perl $`) */
 
502
    SubString       rightContext;  /* input to right of last match (perl $') */
 
503
}
 
504
 
 
505
 
 
506
final class GlobData
 
507
{
 
508
    int      mode;      /* input: return index, match object, or void */
 
509
    int      optarg;    /* input: index of optional flags argument */
 
510
    boolean  global;    /* output: whether regexp was global */
 
511
    String   str;       /* output: 'this' parameter object as string */
 
512
    NativeRegExp regexp;/* output: regexp parameter object private data */
 
513
 
 
514
    // match-specific data
 
515
 
 
516
    Scriptable arrayobj;
 
517
 
 
518
    // replace-specific data
 
519
 
 
520
    Function      lambda;        /* replacement function object or null */
 
521
    String        repstr;        /* replacement string */
 
522
    int           dollar = -1;   /* -1 or index of first $ in repstr */
 
523
    StringBuffer  charBuf;       /* result characters, null initially */
 
524
    int           leftIndex;     /* leftContext index, always 0 for JS1.2 */
 
525
}