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