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