minor bug fixes from moving interfaces
[org.ibex.js.git] / src / org / ibex / js / JSRegexp.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.js;
6
7 /** A JavaScript regular expression object */
8 public class JSRegexp extends JS.Immutable {
9     private static final JS.Method METHOD = new JS.Method();
10
11     private boolean global;
12     private GnuRegexp.RE re;
13     private int lastIndex;
14
15     private JS pattern;
16     private int flags;
17     
18     public JSRegexp(JS arg0, JS arg1) throws JSExn {
19         if(arg0 instanceof JSRegexp) {
20             JSRegexp r = (JSRegexp) arg0;
21             this.global = r.global;
22             this.re = r.re;
23             this.lastIndex = r.lastIndex;
24             this.pattern = r.pattern;
25             this.flags = r.flags;
26         } else {
27             String pattern = Script.toString(arg0);
28             String sFlags = null;
29             int flags = 0;
30             if(arg1 != null) sFlags = Script.toString(arg1);
31             if(sFlags == null) sFlags = "";
32             for(int i=0;i<sFlags.length();i++) {
33                 switch(sFlags.charAt(i)) {
34                     case 'i': flags |= GnuRegexp.RE.REG_ICASE; break;
35                     case 'm': flags |= GnuRegexp.RE.REG_MULTILINE; break;
36                     case 'g': global = true; break;
37                     default: throw new JSExn("Invalid flag in regexp \"" + sFlags.charAt(i) + "\"");
38                 }
39             }
40             re = newRE(pattern,flags);
41             this.pattern = Script.S(pattern);
42             this.flags = flags;
43         }
44     }
45
46     public JS call(JS method, JS[] args) throws JSExn {
47         switch(args.length) {
48             case 1: {
49                 //#switch(Script.str(method))
50                 case "exec": {
51                     String s = Script.toString(args[0]);
52                     int start = global ? lastIndex : 0;
53                     if(start < 0 || start >= s.length()) { lastIndex = 0; return null; }
54                     GnuRegexp.REMatch match = re.getMatch(s,start);
55                     if(global) lastIndex = match == null ? s.length() : match.getEndIndex();
56                     return match == null ? null : matchToExecResult(match,re,s);
57                 }
58                 case "test": {
59                     String s = Script.toString(args[0]);
60                     if (!global) return Script.B(re.getMatch(s) != null);
61                     int start = global ? lastIndex : 0;
62                     if(start < 0 || start >= s.length()) { lastIndex = 0; return null; }
63                     GnuRegexp.REMatch match = re.getMatch(s,start);
64                     lastIndex = match != null ? s.length() : match.getEndIndex();
65                     return Script.B(match != null);
66                 }
67                 case "toString": return Script.S(args[0].coerceToString());
68                 //#end
69                 break;
70             }
71             case 2: {
72                 //#switch(Script.str(method))
73                 case "stringMatch": return stringMatch(args[0], args[1]);
74                 case "stringSearch": return stringSearch(args[0], args[1]);
75                 //#end
76                 break;
77             }
78             case 3: {
79                 //#switch(Script.str(method))
80                 case "stringReplace": return stringReplace(args[0], args[1], args[2]);
81                 //#end
82                 break;
83             }
84         }
85         return super.call(method, args);
86     }
87     
88     public JS get(JS key) throws JSExn {
89         //#switch(Script.str(key))
90         case "exec": return METHOD;
91         case "test": return METHOD;
92         case "toString": return METHOD;
93         case "lastIndex": return Script.N(lastIndex);
94         case "source": return pattern;
95         case "global": return Script.B(global);
96         case "ignoreCase": return Script.B(flags & GnuRegexp.RE.REG_ICASE);
97         case "multiline": return Script.B(flags & GnuRegexp.RE.REG_MULTILINE);
98         //#end
99         return super.get(key);
100     }
101     
102     public void put(JS key, JS value) throws JSExn {
103         if(Script.isString(key)) {
104             if(Script.toString(key).equals("lastIndex")) {
105                 lastIndex = Script.toInt(value);
106                 return;
107             }
108         }
109         super.put(key,value);
110     }
111   
112     private static JS matchToExecResult(GnuRegexp.REMatch match, GnuRegexp.RE re, String s) {
113         try {
114             JS ret = new JS.Obj();
115             ret.put(Script.S("index"), Script.N(match.getStartIndex()));
116             ret.put(Script.S("input"), Script.S(s));
117             int n = re.getNumSubs();
118             ret.put(Script.S("length"), Script.N(n+1));
119             ret.put(Script.ZERO, Script.S(match.toString()));
120             for(int i=1;i<=n;i++) ret.put(Script.N(i),Script.S(match.toString(i)));
121             return ret;
122         } catch (JSExn e) {
123             throw new Error("this should never happen");
124         }
125     }
126     
127     public String coerceToString() {
128         StringBuffer sb = new StringBuffer();
129         sb.append('/');
130         sb.append(pattern);
131         sb.append('/');
132         if(global) sb.append('g');
133         if((flags & GnuRegexp.RE.REG_ICASE) != 0) sb.append('i');
134         if((flags & GnuRegexp.RE.REG_MULTILINE) != 0) sb.append('m');
135         return sb.toString();
136     }
137     
138     private static final JS[] execarg = new JS[1];
139     static JS stringMatch(JS o, JS arg0) throws JSExn {
140         String s = Script.toString(o);
141         GnuRegexp.RE re;
142         JSRegexp regexp = null;
143         if(arg0 instanceof JSRegexp) {
144             regexp = (JSRegexp) arg0;
145             re = regexp.re;
146         } else {
147             re = newRE(Script.toString(arg0),0);
148         }
149         
150         if(regexp == null) {
151             GnuRegexp.REMatch match = re.getMatch(s);
152             return matchToExecResult(match,re,s);
153         }
154         try {
155             execarg[0] = o;
156             if(!regexp.global) return regexp.call(Script.S("exec"), execarg);
157         } finally { execarg[0] = null; }
158
159         GnuRegexp.REMatch[] matches = re.getAllMatches(s);
160         JSArray ret = new JSArray(matches.length);
161         for(int i=0;i<matches.length;i++) ret.add(Script.S(matches[i].toString()));
162         regexp.lastIndex = matches.length > 0 ? matches[matches.length-1].getEndIndex() : s.length();
163         return ret;
164     }
165     
166     static JS stringSearch(JS o, JS arg0) throws JSExn  {
167         String s = Script.toString(o);
168         GnuRegexp.RE re = arg0 instanceof JSRegexp ? ((JSRegexp)arg0).re : newRE(Script.toString(arg0),0);
169         GnuRegexp.REMatch match = re.getMatch(s);
170         return match == null ? Script.N(-1) : Script.N(match.getStartIndex());
171     }
172     
173     static JS stringReplace(JS o, JS arg0, JS arg1) throws JSExn {
174         String s = Script.toString(o);
175         GnuRegexp.RE re;
176         JSFunction replaceFunc = null;
177         String replaceString = null;
178         JSRegexp regexp = null;
179         if(arg0 instanceof JSRegexp) {
180             regexp = (JSRegexp) arg0;
181             re = regexp.re;
182         } else {
183             re = newRE(arg0.toString(),0);
184         }
185         if(arg1 instanceof JSFunction)
186             replaceFunc = (JSFunction) arg1;
187         else
188             replaceString = Script.toString(arg1);
189         GnuRegexp.REMatch[] matches;
190         if(regexp != null && regexp.global) {
191             matches = re.getAllMatches(s);
192             if(regexp != null) {
193                 if(matches.length > 0)
194                     regexp.lastIndex = matches[matches.length-1].getEndIndex();
195                 else
196                     regexp.lastIndex = s.length();
197             }
198         } else {
199             GnuRegexp.REMatch match = re.getMatch(s);
200             if(match != null)
201                 matches = new GnuRegexp.REMatch[]{ match };
202             else
203                 matches = new GnuRegexp.REMatch[0];
204         }
205         
206         StringBuffer sb = new StringBuffer(s.length());
207         int pos = 0;
208         char[] sa = s.toCharArray();
209         for(int i=0;i<matches.length;i++) {
210             GnuRegexp.REMatch match = matches[i];
211             sb.append(sa,pos,match.getStartIndex()-pos);
212             pos = match.getEndIndex();
213             if(replaceFunc != null) {
214                 int n = (regexp == null ? 0 : re.getNumSubs());
215                 int numArgs = 3 + n;
216                 JS[] args = new JS[3 + n];
217                 args[0] = Script.S(match.toString());
218                 args[1] = null;
219                 args[2] = null;
220                 for(int j=1;j<=n;j++) args[j] = Script.S(match.toString(j));
221                 args[args.length - 2] = Script.N(match.getStartIndex());
222                 args[args.length - 1] = Script.S(s);
223
224                 // note: can't perform pausing operations in here
225                 sb.append(Script.toString(replaceFunc.call(args)));
226
227             } else {
228                 sb.append(mySubstitute(match,replaceString,s));
229             }
230         }
231         int end = matches.length == 0 ? 0 : matches[matches.length-1].getEndIndex();
232         sb.append(sa,end,sa.length-end);
233         return Script.S(sb.toString());
234     }
235     
236     private static String mySubstitute(GnuRegexp.REMatch match, String s, String source) {
237         StringBuffer sb = new StringBuffer();
238         int i,n;
239         char c,c2;
240         for(i=0;i<s.length()-1;i++) {
241            c = s.charAt(i);
242             if(c != '$') {
243                 sb.append(c);
244                 continue;
245             }
246             i++;
247             c = s.charAt(i);
248             switch(c) {
249                 case '0': case '1': case '2': case '3': case '4':
250                 case '5': case '6': case '7': case '8': case '9':
251                     if(i < s.length()-1 && (c2 = s.charAt(i+1)) >= '0' && c2 <= '9') {
252                         n = (c - '0') * 10 + (c2 - '0');
253                         i++;
254                     } else {
255                         n = c - '0';
256                     }
257                     if(n > 0)
258                         sb.append(match.toString(n));
259                     break;
260                 case '$':
261                     sb.append('$'); break;
262                 case '&':
263                     sb.append(match.toString()); break;
264                 case '`':
265                     sb.append(source.substring(0,match.getStartIndex())); break;
266                 case '\'':
267                     sb.append(source.substring(match.getEndIndex())); break;
268                 default:
269                     sb.append('$');
270                     sb.append(c);
271             }
272         }
273         if(i < s.length()) sb.append(s.charAt(i));
274         return sb.toString();
275     }
276                     
277     
278     static JS stringSplit(JS s_, JS arg0, JS arg1, int nargs) throws JSExn {
279         String s = Script.toString(s_);
280         int limit = nargs < 2 ? Integer.MAX_VALUE : Script.toInt(arg1);
281         if(limit < 0) limit = Integer.MAX_VALUE;
282         if(limit == 0) return new JSArray(0);
283         
284         GnuRegexp.RE re = null;
285         JSRegexp regexp = null;
286         String sep = null;
287         JSArray ret = new JSArray();
288         int p = 0;
289         
290         if(arg0 instanceof JSRegexp) {
291             regexp = (JSRegexp) arg0;
292             re = regexp.re;
293         } else {
294             sep = Script.toString(arg0);
295         }
296         
297         // special case this for speed. additionally, the code below doesn't properly handle
298         // zero length strings
299         if(sep != null && sep.length()==0) {
300             int len = s.length();
301             for(int i=0;i<len;i++)
302                 ret.add(Script.S(s.substring(i,i+1)));
303             return ret;
304         }
305         
306         OUTER: while(p < s.length()) {
307             if(re != null) {
308                 GnuRegexp.REMatch m = re.getMatch(s,p);
309                 if(m == null) break OUTER;
310                 boolean zeroLength = m.getStartIndex() == m.getEndIndex();
311                 ret.add(Script.S(s.substring(p,zeroLength ? m.getStartIndex()+1 : m.getStartIndex())));
312                 p = zeroLength ? p + 1 : m.getEndIndex();
313                 if(!zeroLength) {
314                     for(int i=1;i<=re.getNumSubs();i++) {
315                         ret.add(Script.S(m.toString(i)));
316                         if(ret.size() == limit) break OUTER;
317                     }
318                 }
319             } else {
320                 int x = s.indexOf(sep,p);
321                 if(x == -1) break OUTER;
322                 ret.add(Script.S(s.substring(p,x)));
323                 p = x + sep.length();
324             }
325             if(ret.size() == limit) break;
326         }
327         if(p < s.length() && ret.size() != limit)
328             ret.add(Script.S(s.substring(p)));
329         return ret;
330     }
331    
332     public static GnuRegexp.RE newRE(String pattern, int flags) throws JSExn {
333         try {
334             return new GnuRegexp.RE(pattern,flags,GnuRegexp.RESyntax.RE_SYNTAX_PERL5);
335         } catch(GnuRegexp.REException e) {
336             throw new JSExn(e.toString());
337         }
338     }
339 }