Debian Codegraph @

src/com/google/javascript/rhino/ScriptRuntime.java

raw symbols SCIP
1 /*
2 *
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is Rhino code, released
17 * May 6, 1999.
18 *
19 * The Initial Developer of the Original Code is
20 * Netscape Communications Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 1997-2000
22 * the Initial Developer. All Rights Reserved.
23 *
24 * Contributor(s):
25 * Patrick Beard
26 * Norris Boyd
27 * Igor Bukanov
28 * Ethan Hugg
29 * Roger Lawrence
30 * Terry Lucas
31 * Frank Mitchell
32 * Milen Nankov
33 * Andrew Wason
34 *
35 * Alternatively, the contents of this file may be used under the terms of
36 * the GNU General Public License Version 2 or later (the "GPL"), in which
37 * case the provisions of the GPL are applicable instead of those above. If
38 * you wish to allow use of your version of this file only under the terms of
39 * the GPL and not to allow others to use your version of this file under the
40 * MPL, indicate your decision by deleting the provisions above and replacing
41 * them with the notice and other provisions required by the GPL. If you do
42 * not delete the provisions above, a recipient may use your version of this
43 * file under either the MPL or the GPL.
44 *
45 * ***** END LICENSE BLOCK ***** */
46
47 package com.google.javascript.rhino;
48
49 import java.text.MessageFormat;
50 import java.util.Locale;
51 import java.util.ResourceBundle;
52
53 /**
54 * This is the class that implements the run-time.
55 *
56 */
57
58 public class ScriptRuntime {
59
60 /**
61 * No instances should be created.
62 */
63 protected ScriptRuntime() {
64 }
65
66 // It is public so NativeRegExp can access it .
67 public static boolean isJSLineTerminator(int c) {
68 // Optimization for faster check for EOL character:
69 // they do not have 0xDFD0 bits set
70 if ((c & 0xDFD0) != 0) {
71 return false;
72 }
73 return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029;
74 }
75
76 // Can not use Double.NaN defined as 0.0d / 0.0 as under the Microsoft VM,
77 // versions 2.01 and 3.0P1, that causes some uses (returns at least) of
78 // Double.NaN to be converted to 1.0.
79 // So we use ScriptRuntime.NaN instead of Double.NaN.
80 public static final double
81 NaN = Double.longBitsToDouble(0x7ff8000000000000L);
82
83 // A similar problem exists for negative zero.
84 public static final double
85 negativeZero = Double.longBitsToDouble(0x8000000000000000L);
86
87 /*
88 * Helper function for toNumber, parseInt, and TokenStream.getToken.
89 */
90 @SuppressWarnings("fallthrough")
91 static double stringToNumber(String s, int start, int radix) {
92 char digitMax = '9';
93 char lowerCaseBound = 'a';
94 char upperCaseBound = 'A';
95 int len = s.length();
96 if (radix < 10) {
97 digitMax = (char) ('0' + radix - 1);
98 }
99 if (radix > 10) {
100 lowerCaseBound = (char) ('a' + radix - 10);
101 upperCaseBound = (char) ('A' + radix - 10);
102 }
103 int end;
104 double sum = 0.0;
105 for (end=start; end < len; end++) {
106 char c = s.charAt(end);
107 int newDigit;
108 if ('0' <= c && c <= digitMax)
109 newDigit = c - '0';
110 else if ('a' <= c && c < lowerCaseBound)
111 newDigit = c - 'a' + 10;
112 else if ('A' <= c && c < upperCaseBound)
113 newDigit = c - 'A' + 10;
114 else
115 break;
116 sum = sum*radix + newDigit;
117 }
118 if (start == end) {
119 return NaN;
120 }
121 if (sum >= 9007199254740992.0) {
122 if (radix == 10) {
123 /* If we're accumulating a decimal number and the number
124 * is >= 2^53, then the result from the repeated multiply-add
125 * above may be inaccurate. Call Java to get the correct
126 * answer.
127 */
128 try {
129 return Double.valueOf(s.substring(start, end)).doubleValue();
130 } catch (NumberFormatException nfe) {
131 return NaN;
132 }
133 } else if (radix == 2 || radix == 4 || radix == 8 ||
134 radix == 16 || radix == 32) {
135 /* The number may also be inaccurate for one of these bases.
136 * This happens if the addition in value*radix + digit causes
137 * a round-down to an even least significant mantissa bit
138 * when the first dropped bit is a one. If any of the
139 * following digits in the number (which haven't been added
140 * in yet) are nonzero then the correct action would have
141 * been to round up instead of down. An example of this
142 * occurs when reading the number 0x1000000000000081, which
143 * rounds to 0x1000000000000000 instead of 0x1000000000000100.
144 */
145 int bitShiftInChar = 1;
146 int digit = 0;
147
148 final int SKIP_LEADING_ZEROS = 0;
149 final int FIRST_EXACT_53_BITS = 1;
150 final int AFTER_BIT_53 = 2;
151 final int ZEROS_AFTER_54 = 3;
152 final int MIXED_AFTER_54 = 4;
153
154 int state = SKIP_LEADING_ZEROS;
155 int exactBitsLimit = 53;
156 double factor = 0.0;
157 boolean bit53 = false;
158 // bit54 is the 54th bit (the first dropped from the mantissa)
159 boolean bit54 = false;
160
161 for (;;) {
162 if (bitShiftInChar == 1) {
163 if (start == end)
164 break;
165 digit = s.charAt(start++);
166 if ('0' <= digit && digit <= '9')
167 digit -= '0';
168 else if ('a' <= digit && digit <= 'z')
169 digit -= 'a' - 10;
170 else
171 digit -= 'A' - 10;
172 bitShiftInChar = radix;
173 }
174 bitShiftInChar >>= 1;
175 boolean bit = (digit & bitShiftInChar) != 0;
176
177 switch (state) {
178 case SKIP_LEADING_ZEROS:
179 if (bit) {
180 --exactBitsLimit;
181 sum = 1.0;
182 state = FIRST_EXACT_53_BITS;
183 }
184 break;
185 case FIRST_EXACT_53_BITS:
186 sum *= 2.0;
187 if (bit)
188 sum += 1.0;
189 --exactBitsLimit;
190 if (exactBitsLimit == 0) {
191 bit53 = bit;
192 state = AFTER_BIT_53;
193 }
194 break;
195 case AFTER_BIT_53:
196 bit54 = bit;
197 factor = 2.0;
198 state = ZEROS_AFTER_54;
199 break;
200 case ZEROS_AFTER_54:
201 if (bit) {
202 state = MIXED_AFTER_54;
203 }
204 // fallthrough
205 case MIXED_AFTER_54:
206 factor *= 2;
207 break;
208 }
209 }
210 switch (state) {
211 case SKIP_LEADING_ZEROS:
212 sum = 0.0;
213 break;
214 case FIRST_EXACT_53_BITS:
215 case AFTER_BIT_53:
216 // do nothing
217 break;
218 case ZEROS_AFTER_54:
219 // x1.1 -> x1 + 1 (round up)
220 // x0.1 -> x0 (round down)
221 if (bit54 & bit53)
222 sum += 1.0;
223 sum *= factor;
224 break;
225 case MIXED_AFTER_54:
226 // x.100...1.. -> x + 1 (round up)
227 // x.0anything -> x (round down)
228 if (bit54)
229 sum += 1.0;
230 sum *= factor;
231 break;
232 }
233 }
234 /* We don't worry about inaccurate numbers for any other base. */
235 }
236 return sum;
237 }
238
239 public static String escapeString(String s) {
240 return escapeString(s, '"');
241 }
242
243 /**
244 * For escaping strings printed by object and array literals; not quite
245 * the same as 'escape.'
246 */
247 public static String escapeString(String s, char escapeQuote) {
248 if (!(escapeQuote == '"' || escapeQuote == '\'')) {
249 throw new IllegalStateException("unexpected quote char:" + escapeQuote);
250 }
251 StringBuffer sb = null;
252
253 for(int i = 0, L = s.length(); i != L; ++i) {
254 int c = s.charAt(i);
255
256 if (' ' <= c && c <= '~' && c != escapeQuote && c != '\\') {
257 // an ordinary print character (like C isprint()) and not "
258 // or \ .
259 if (sb != null) {
260 sb.append((char)c);
261 }
262 continue;
263 }
264 if (sb == null) {
265 sb = new StringBuffer(L + 3);
266 sb.append(s);
267 sb.setLength(i);
268 }
269
270 int escape = -1;
271 switch (c) {
272 case '\b': escape = 'b'; break;
273 case '\f': escape = 'f'; break;
274 case '\n': escape = 'n'; break;
275 case '\r': escape = 'r'; break;
276 case '\t': escape = 't'; break;
277 case 0xb: escape = 'v'; break; // Java lacks \v.
278 case ' ': escape = ' '; break;
279 case '\\': escape = '\\'; break;
280 }
281 if (escape >= 0) {
282 // an \escaped sort of character
283 sb.append('\\');
284 sb.append((char)escape);
285 } else if (c == escapeQuote) {
286 sb.append('\\');
287 sb.append(escapeQuote);
288 } else {
289 int hexSize;
290 if (c < 256) {
291 // 2-digit hex
292 sb.append("\\x");
293 hexSize = 2;
294 } else {
295 // Unicode.
296 sb.append("\\u");
297 hexSize = 4;
298 }
299 // append hexadecimal form of c left-padded with 0
300 for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) {
301 int digit = 0xf & (c >> shift);
302 int hc = (digit < 10) ? '0' + digit : 'a' - 10 + digit;
303 sb.append((char)hc);
304 }
305 }
306 }
307 return (sb == null) ? s : sb.toString();
308 }
309
310 static boolean isValidIdentifierName(String s) {
311 int L = s.length();
312 if (L == 0)
313 return false;
314 if (!Character.isJavaIdentifierStart(s.charAt(0)))
315 return false;
316 for (int i = 1; i != L; ++i) {
317 if (!Character.isJavaIdentifierPart(s.charAt(i)))
318 return false;
319 }
320 return !TokenStream.isKeyword(s);
321 }
322
323 /**
324 * If str is a decimal presentation of Uint32 value, return it as long.
325 * Otherwise, return -1L;
326 */
327 public static long testUint32String(String str) {
328 // The length of the decimal string representation of
329 // UINT32_MAX_VALUE, 4294967296
330 final int MAX_VALUE_LENGTH = 10;
331
332 int len = str.length();
333 if (1 <= len && len <= MAX_VALUE_LENGTH) {
334 int c = str.charAt(0);
335 c -= '0';
336 if (c == 0) {
337 // Note that 00,01 etc. are not valid Uint32 presentations
338 return (len == 1) ? 0L : -1L;
339 }
340 if (1 <= c && c <= 9) {
341 long v = c;
342 for (int i = 1; i != len; ++i) {
343 c = str.charAt(i) - '0';
344 if (!(0 <= c && c <= 9)) {
345 return -1;
346 }
347 v = 10 * v + c;
348 }
349 // Check for overflow
350 if ((v >>> 32) == 0) {
351 return v;
352 }
353 }
354 }
355 return -1;
356 }
357
358 static boolean isSpecialProperty(String s) {
359 return s.equals("__proto__") || s.equals("__parent__");
360 }
361
362 // ------------------
363 // Statements
364 // ------------------
365
366 public static String getMessage0(String messageId) {
367 return getMessage(messageId, null);
368 }
369
370 public static String getMessage1(String messageId, Object arg1) {
371 Object[] arguments = {arg1};
372 return getMessage(messageId, arguments);
373 }
374
375 /* OPT there's a noticeable delay for the first error! Maybe it'd
376 * make sense to use a ListResourceBundle instead of a properties
377 * file to avoid (synchronized) text parsing.
378 */
379 public static String getMessage(String messageId, Object[] arguments) {
380 final String defaultResource
381 = "rhino_ast.java.com.google.javascript.rhino.Messages";
382
383 Locale locale = Locale.getDefault();
384
385 // ResourceBundle does caching.
386 ResourceBundle rb = ResourceBundle.getBundle(defaultResource, locale);
387
388 String formatString;
389 try {
390 formatString = rb.getString(messageId);
391 } catch (java.util.MissingResourceException mre) {
392 throw new RuntimeException
393 ("no message resource found for message property "+ messageId);
394 }
395
396 /*
397 * It's OK to format the string, even if 'arguments' is null;
398 * we need to format it anyway, to make double ''s collapse to
399 * single 's.
400 */
401 // TODO: MessageFormat is not available on pJava
402 MessageFormat formatter = new MessageFormat(formatString);
403 return formatter.format(arguments);
404 }
405 }