source: webkit/trunk/JavaScriptCore/runtime/JSGlobalObjectFunctions.cpp@ 61623

Last change on this file since 61623 was 60762, checked in by [email protected], 15 years ago

Bug 40214 - Clean up error construction / throwing in JSC.

Reviewed by Sam Weinig.

The one egregious insanity here is that creating an error requires
a VM-entry-esqe-host call (the string argument is wrapped as a JS
object & pushed on the RegisterFile, then unwrapped back to a
UString). Changing this also means you only require a global
object, not an ExecState, to create an error.

The methods to create error objects are also parameterized
requiring a switch on the type, which can be made cleaner and
faster by moving to a separate method per error type. Code to add
divot information to error had been duplicated, and is coalesced
back into a single function.

Convenience methods added to create & throw type & syntax error
with a default error message, since this is a common case.

Also, errors are currently thrown either using
"throwError(exec, error)" or "exec->setException(error)" - unify
on the former, since this is more commonly used. Add
"throwVMError(exec, error)" equivalents, as a convenience for
cases where the result was being wrapped in "JSValue::encode(...)".

JavaScriptCore:

  • API/JSCallbackConstructor.cpp:

(JSC::constructJSCallback):

  • API/JSCallbackFunction.cpp:

(JSC::JSCallbackFunction::call):

  • API/JSCallbackObjectFunctions.h:

(JSC::::getOwnPropertySlot):
(JSC::::put):
(JSC::::deleteProperty):
(JSC::::construct):
(JSC::::hasInstance):
(JSC::::call):
(JSC::::toNumber):
(JSC::::toString):
(JSC::::staticValueGetter):
(JSC::::staticFunctionGetter):
(JSC::::callbackGetter):

  • API/JSObjectRef.cpp:

(JSObjectMakeError):

(JSC::BytecodeGenerator::emitNewError):
(JSC::BytecodeGenerator::emitThrowExpressionTooDeepException):

  • bytecompiler/BytecodeGenerator.h:
  • bytecompiler/NodesCodegen.cpp:

(JSC::ThrowableExpressionData::emitThrowError):
(JSC::RegExpNode::emitBytecode):
(JSC::PostfixErrorNode::emitBytecode):
(JSC::PrefixErrorNode::emitBytecode):
(JSC::AssignErrorNode::emitBytecode):
(JSC::ForInNode::emitBytecode):
(JSC::ContinueNode::emitBytecode):
(JSC::BreakNode::emitBytecode):
(JSC::ReturnNode::emitBytecode):
(JSC::LabelNode::emitBytecode):

  • interpreter/CallFrame.h:
  • interpreter/Interpreter.cpp:

(JSC::Interpreter::throwException):
(JSC::Interpreter::privateExecute):

  • jit/JITStubs.cpp:

(JSC::DEFINE_STUB_FUNCTION):

  • jsc.cpp:

(functionRun):
(functionLoad):
(functionCheckSyntax):

  • parser/Nodes.h:
  • runtime/ArrayConstructor.cpp:

(JSC::constructArrayWithSizeQuirk):

  • runtime/ArrayPrototype.cpp:

(JSC::arrayProtoFuncToString):
(JSC::arrayProtoFuncToLocaleString):
(JSC::arrayProtoFuncJoin):
(JSC::arrayProtoFuncFilter):
(JSC::arrayProtoFuncMap):
(JSC::arrayProtoFuncEvery):
(JSC::arrayProtoFuncForEach):
(JSC::arrayProtoFuncSome):
(JSC::arrayProtoFuncReduce):
(JSC::arrayProtoFuncReduceRight):

  • runtime/BooleanPrototype.cpp:

(JSC::booleanProtoFuncToString):
(JSC::booleanProtoFuncValueOf):

  • runtime/DatePrototype.cpp:

(JSC::dateProtoFuncToString):
(JSC::dateProtoFuncToUTCString):
(JSC::dateProtoFuncToISOString):
(JSC::dateProtoFuncToDateString):
(JSC::dateProtoFuncToTimeString):
(JSC::dateProtoFuncToLocaleString):
(JSC::dateProtoFuncToLocaleDateString):
(JSC::dateProtoFuncToLocaleTimeString):
(JSC::dateProtoFuncGetTime):
(JSC::dateProtoFuncGetFullYear):
(JSC::dateProtoFuncGetUTCFullYear):
(JSC::dateProtoFuncToGMTString):
(JSC::dateProtoFuncGetMonth):
(JSC::dateProtoFuncGetUTCMonth):
(JSC::dateProtoFuncGetDate):
(JSC::dateProtoFuncGetUTCDate):
(JSC::dateProtoFuncGetDay):
(JSC::dateProtoFuncGetUTCDay):
(JSC::dateProtoFuncGetHours):
(JSC::dateProtoFuncGetUTCHours):
(JSC::dateProtoFuncGetMinutes):
(JSC::dateProtoFuncGetUTCMinutes):
(JSC::dateProtoFuncGetSeconds):
(JSC::dateProtoFuncGetUTCSeconds):
(JSC::dateProtoFuncGetMilliSeconds):
(JSC::dateProtoFuncGetUTCMilliseconds):
(JSC::dateProtoFuncGetTimezoneOffset):
(JSC::dateProtoFuncSetTime):
(JSC::setNewValueFromTimeArgs):
(JSC::setNewValueFromDateArgs):
(JSC::dateProtoFuncSetMilliSeconds):
(JSC::dateProtoFuncSetUTCMilliseconds):
(JSC::dateProtoFuncSetSeconds):
(JSC::dateProtoFuncSetUTCSeconds):
(JSC::dateProtoFuncSetMinutes):
(JSC::dateProtoFuncSetUTCMinutes):
(JSC::dateProtoFuncSetHours):
(JSC::dateProtoFuncSetUTCHours):
(JSC::dateProtoFuncSetDate):
(JSC::dateProtoFuncSetUTCDate):
(JSC::dateProtoFuncSetMonth):
(JSC::dateProtoFuncSetUTCMonth):
(JSC::dateProtoFuncSetFullYear):
(JSC::dateProtoFuncSetUTCFullYear):
(JSC::dateProtoFuncSetYear):
(JSC::dateProtoFuncGetYear):
(JSC::dateProtoFuncToJSON):

  • runtime/Error.cpp:

(JSC::createError):
(JSC::createEvalError):
(JSC::createRangeError):
(JSC::createReferenceError):
(JSC::createSyntaxError):
(JSC::createTypeError):
(JSC::createURIError):
(JSC::addErrorSourceInfo):
(JSC::addErrorDivotInfo):
(JSC::addErrorInfo):
(JSC::hasErrorInfo):
(JSC::throwError):
(JSC::throwTypeError):
(JSC::throwSyntaxError):

  • runtime/Error.h:

(JSC::throwVMError):
(JSC::throwVMTypeError):

  • runtime/ErrorConstructor.cpp:

(JSC::constructWithErrorConstructor):
(JSC::callErrorConstructor):

  • runtime/ErrorConstructor.h:
  • runtime/ErrorInstance.cpp:

(JSC::ErrorInstance::ErrorInstance):
(JSC::ErrorInstance::create):

  • runtime/ErrorInstance.h:
  • runtime/ErrorPrototype.cpp:

(JSC::ErrorPrototype::ErrorPrototype):

  • runtime/ExceptionHelpers.cpp:

(JSC::createStackOverflowError):
(JSC::createUndefinedVariableError):
(JSC::createInvalidParamError):
(JSC::createNotAConstructorError):
(JSC::createNotAFunctionError):
(JSC::createNotAnObjectError):
(JSC::throwOutOfMemoryError):

  • runtime/ExceptionHelpers.h:
  • runtime/Executable.cpp:

(JSC::EvalExecutable::compile):
(JSC::ProgramExecutable::checkSyntax):
(JSC::ProgramExecutable::compile):

  • runtime/FunctionConstructor.cpp:

(JSC::constructFunction):

  • runtime/FunctionPrototype.cpp:

(JSC::functionProtoFuncToString):
(JSC::functionProtoFuncApply):
(JSC::functionProtoFuncCall):

  • runtime/Identifier.cpp:

(JSC::Identifier::from):

  • runtime/Identifier.h:
  • runtime/JSArray.cpp:

(JSC::JSArray::put):

  • runtime/JSFunction.cpp:

(JSC::callHostFunctionAsConstructor):

  • runtime/JSGlobalObjectFunctions.cpp:

(JSC::encode):
(JSC::decode):
(JSC::globalFuncEval):

  • runtime/JSONObject.cpp:

(JSC::Stringifier::appendStringifiedValue):
(JSC::Walker::walk):
(JSC::JSONProtoFuncParse):
(JSC::JSONProtoFuncStringify):

  • runtime/JSObject.cpp:

(JSC::throwSetterError):
(JSC::JSObject::put):
(JSC::JSObject::putWithAttributes):
(JSC::JSObject::defaultValue):
(JSC::JSObject::hasInstance):
(JSC::JSObject::defineOwnProperty):

  • runtime/JSObject.h:
  • runtime/JSValue.cpp:

(JSC::JSValue::toObjectSlowCase):
(JSC::JSValue::synthesizeObject):
(JSC::JSValue::synthesizePrototype):

  • runtime/NativeErrorConstructor.cpp:

(JSC::constructWithNativeErrorConstructor):
(JSC::callNativeErrorConstructor):

  • runtime/NativeErrorConstructor.h:
  • runtime/NumberPrototype.cpp:

(JSC::numberProtoFuncToString):
(JSC::numberProtoFuncToLocaleString):
(JSC::numberProtoFuncValueOf):
(JSC::numberProtoFuncToFixed):
(JSC::numberProtoFuncToExponential):
(JSC::numberProtoFuncToPrecision):

  • runtime/ObjectConstructor.cpp:

(JSC::objectConstructorGetPrototypeOf):
(JSC::objectConstructorGetOwnPropertyDescriptor):
(JSC::objectConstructorGetOwnPropertyNames):
(JSC::objectConstructorKeys):
(JSC::toPropertyDescriptor):
(JSC::objectConstructorDefineProperty):
(JSC::objectConstructorDefineProperties):
(JSC::objectConstructorCreate):

  • runtime/ObjectPrototype.cpp:

(JSC::objectProtoFuncDefineGetter):
(JSC::objectProtoFuncDefineSetter):

  • runtime/RegExpConstructor.cpp:

(JSC::constructRegExp):

  • runtime/RegExpObject.cpp:

(JSC::RegExpObject::match):

  • runtime/RegExpPrototype.cpp:

(JSC::regExpProtoFuncTest):
(JSC::regExpProtoFuncExec):
(JSC::regExpProtoFuncCompile):
(JSC::regExpProtoFuncToString):

  • runtime/StringPrototype.cpp:

(JSC::stringProtoFuncToString):

WebCore:

  • WebCore.xcodeproj/project.pbxproj:
  • bindings/js/JSArrayBufferConstructor.h:

(WebCore::construct):

  • bindings/js/JSArrayBufferViewHelper.h:

(WebCore::setWebGLArrayHelper):

  • bindings/js/JSAudioConstructor.cpp:

(WebCore::constructAudio):

  • bindings/js/JSCanvasRenderingContext2DCustom.cpp:

(WebCore::JSCanvasRenderingContext2D::setFillColor):
(WebCore::JSCanvasRenderingContext2D::setStrokeColor):
(WebCore::JSCanvasRenderingContext2D::drawImage):
(WebCore::JSCanvasRenderingContext2D::drawImageFromRect):
(WebCore::JSCanvasRenderingContext2D::setShadow):
(WebCore::JSCanvasRenderingContext2D::createPattern):
(WebCore::JSCanvasRenderingContext2D::fillText):
(WebCore::JSCanvasRenderingContext2D::strokeText):

  • bindings/js/JSClipboardCustom.cpp:

(WebCore::JSClipboard::clearData):
(WebCore::JSClipboard::getData):
(WebCore::JSClipboard::setDragImage):

  • bindings/js/JSDOMBinding.cpp:

(WebCore::setDOMException):
(WebCore::toJSSequence):

  • bindings/js/JSDOMWrapper.cpp:

(WebCore::DOMObject::defineOwnProperty):

  • bindings/js/JSDesktopNotificationsCustom.cpp:

(WebCore::JSNotificationCenter::requestPermission):

  • bindings/js/JSEventSourceConstructor.cpp:

(WebCore::constructEventSource):

  • bindings/js/JSHTMLDocumentCustom.cpp:

(WebCore::JSHTMLDocument::open):

  • bindings/js/JSHTMLInputElementCustom.cpp:

(WebCore::JSHTMLInputElement::selectionStart):
(WebCore::JSHTMLInputElement::setSelectionStart):
(WebCore::JSHTMLInputElement::selectionEnd):
(WebCore::JSHTMLInputElement::setSelectionEnd):
(WebCore::JSHTMLInputElement::setSelectionRange):

  • bindings/js/JSImageConstructor.cpp:

(WebCore::constructImage):

  • bindings/js/JSJavaScriptCallFrameCustom.cpp:

(WebCore::JSJavaScriptCallFrame::evaluate):

  • bindings/js/JSMessageChannelConstructor.cpp:

(WebCore::JSMessageChannelConstructor::construct):

  • bindings/js/JSMessagePortCustom.cpp:

(WebCore::fillMessagePortArray):

  • bindings/js/JSOptionConstructor.cpp:

(WebCore::constructHTMLOptionElement):

  • bindings/js/JSSVGMatrixCustom.cpp:

(WebCore::JSSVGMatrix::multiply):

  • bindings/js/JSSharedWorkerConstructor.cpp:

(WebCore::constructSharedWorker):

  • bindings/js/JSWebGLRenderingContextCustom.cpp:

(WebCore::JSWebGLRenderingContext::bufferData):
(WebCore::JSWebGLRenderingContext::bufferSubData):
(WebCore::getObjectParameter):
(WebCore::JSWebGLRenderingContext::getFramebufferAttachmentParameter):
(WebCore::JSWebGLRenderingContext::getParameter):
(WebCore::JSWebGLRenderingContext::getProgramParameter):
(WebCore::JSWebGLRenderingContext::getShaderParameter):
(WebCore::JSWebGLRenderingContext::getUniform):
(WebCore::JSWebGLRenderingContext::texImage2D):
(WebCore::JSWebGLRenderingContext::texSubImage2D):
(WebCore::dataFunctionf):
(WebCore::dataFunctioni):
(WebCore::dataFunctionMatrix):

  • bindings/js/JSWebSocketConstructor.cpp:

(WebCore::constructWebSocket):

  • bindings/js/JSWebSocketCustom.cpp:

(WebCore::JSWebSocket::send):

  • bindings/js/JSWorkerConstructor.cpp:

(WebCore::constructWorker):

  • bindings/js/JSXMLHttpRequestConstructor.cpp:

(WebCore::constructXMLHttpRequest):

  • bindings/js/JSXMLHttpRequestCustom.cpp:

(WebCore::JSXMLHttpRequest::open):

  • bindings/js/SerializedScriptValue.cpp:

(WebCore::BaseWalker::throwStackOverflow):
(WebCore::BaseWalker::throwInterruptedException):
(WebCore::SerializingTreeWalker::startArray):
(WebCore::SerializingTreeWalker::startObject):

  • bindings/js/WorkerScriptController.cpp:

(WebCore::WorkerScriptController::setException):

  • bindings/scripts/CodeGeneratorJS.pm:
  • bridge/c/c_instance.cpp:

(JSC::Bindings::CInstance::moveGlobalExceptionToExecState):
(JSC::Bindings::CInstance::invokeMethod):
(JSC::Bindings::CInstance::invokeDefaultMethod):
(JSC::Bindings::CInstance::invokeConstruct):

  • bridge/jni/jsc/JNIBridgeJSC.cpp:

(JavaField::dispatchValueFromInstance):
(JavaField::dispatchSetValueToInstance):

  • bridge/jni/jsc/JavaInstanceJSC.cpp:

(JavaInstance::invokeMethod):

  • bridge/objc/objc_instance.mm:

(ObjcInstance::moveGlobalExceptionToExecState):
(ObjcInstance::invokeMethod):

  • bridge/objc/objc_runtime.mm:

(JSC::Bindings::ObjcField::valueFromInstance):
(JSC::Bindings::ObjcField::setValueToInstance):
(JSC::Bindings::ObjcArray::setValueAt):
(JSC::Bindings::ObjcArray::valueAt):
(JSC::Bindings::callObjCFallbackObject):

  • bridge/objc/objc_utility.h:
  • bridge/objc/objc_utility.mm:

(JSC::Bindings::throwError):

  • bridge/runtime_array.cpp:

(JSC::RuntimeArray::put):

  • bridge/runtime_method.cpp:

(JSC::callRuntimeMethod):

  • bridge/runtime_object.cpp:

(JSC::Bindings::RuntimeObject::throwInvalidAccessError):

WebKit/mac:

  • Plugins/Hosted/NetscapePluginInstanceProxy.mm:

(WebKit::NetscapePluginInstanceProxy::moveGlobalExceptionToExecState):

  • Plugins/Hosted/ProxyInstance.mm:

(WebKit::ProxyInstance::invokeMethod):

  • Property svn:eol-style set to native
File size: 13.7 KB
Line 
1/*
2 * Copyright (C) 1999-2002 Harri Porten ([email protected])
3 * Copyright (C) 2001 Peter Kelly ([email protected])
4 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
5 * Copyright (C) 2007 Cameron Zwarich ([email protected])
6 * Copyright (C) 2007 Maks Orlovich
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
17 *
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
22 *
23 */
24
25#include "config.h"
26#include "JSGlobalObjectFunctions.h"
27
28#include "CallFrame.h"
29#include "GlobalEvalFunction.h"
30#include "Interpreter.h"
31#include "JSGlobalObject.h"
32#include "JSString.h"
33#include "JSStringBuilder.h"
34#include "Lexer.h"
35#include "LiteralParser.h"
36#include "Nodes.h"
37#include "Parser.h"
38#include "StringBuilder.h"
39#include "StringExtras.h"
40#include "dtoa.h"
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <wtf/ASCIICType.h>
45#include <wtf/Assertions.h>
46#include <wtf/MathExtras.h>
47#include <wtf/unicode/UTF8.h>
48
49using namespace WTF;
50using namespace Unicode;
51
52namespace JSC {
53
54static JSValue encode(ExecState* exec, const char* doNotEscape)
55{
56 UString str = exec->argument(0).toString(exec);
57 CString cstr = str.UTF8String(true);
58 if (!cstr.data())
59 return throwError(exec, createURIError(exec, "String contained an illegal UTF-16 sequence."));
60
61 JSStringBuilder builder;
62 const char* p = cstr.data();
63 for (size_t k = 0; k < cstr.length(); k++, p++) {
64 char c = *p;
65 if (c && strchr(doNotEscape, c))
66 builder.append(c);
67 else {
68 char tmp[4];
69 snprintf(tmp, 4, "%%%02X", static_cast<unsigned char>(c));
70 builder.append(tmp);
71 }
72 }
73 return builder.build(exec);
74}
75
76static JSValue decode(ExecState* exec, const char* doNotUnescape, bool strict)
77{
78 JSStringBuilder builder;
79 UString str = exec->argument(0).toString(exec);
80 int k = 0;
81 int len = str.size();
82 const UChar* d = str.data();
83 UChar u = 0;
84 while (k < len) {
85 const UChar* p = d + k;
86 UChar c = *p;
87 if (c == '%') {
88 int charLen = 0;
89 if (k <= len - 3 && isASCIIHexDigit(p[1]) && isASCIIHexDigit(p[2])) {
90 const char b0 = Lexer::convertHex(p[1], p[2]);
91 const int sequenceLen = UTF8SequenceLength(b0);
92 if (sequenceLen != 0 && k <= len - sequenceLen * 3) {
93 charLen = sequenceLen * 3;
94 char sequence[5];
95 sequence[0] = b0;
96 for (int i = 1; i < sequenceLen; ++i) {
97 const UChar* q = p + i * 3;
98 if (q[0] == '%' && isASCIIHexDigit(q[1]) && isASCIIHexDigit(q[2]))
99 sequence[i] = Lexer::convertHex(q[1], q[2]);
100 else {
101 charLen = 0;
102 break;
103 }
104 }
105 if (charLen != 0) {
106 sequence[sequenceLen] = 0;
107 const int character = decodeUTF8Sequence(sequence);
108 if (character < 0 || character >= 0x110000)
109 charLen = 0;
110 else if (character >= 0x10000) {
111 // Convert to surrogate pair.
112 builder.append(static_cast<UChar>(0xD800 | ((character - 0x10000) >> 10)));
113 u = static_cast<UChar>(0xDC00 | ((character - 0x10000) & 0x3FF));
114 } else
115 u = static_cast<UChar>(character);
116 }
117 }
118 }
119 if (charLen == 0) {
120 if (strict)
121 return throwError(exec, createURIError(exec, "URI error"));
122 // The only case where we don't use "strict" mode is the "unescape" function.
123 // For that, it's good to support the wonky "%u" syntax for compatibility with WinIE.
124 if (k <= len - 6 && p[1] == 'u'
125 && isASCIIHexDigit(p[2]) && isASCIIHexDigit(p[3])
126 && isASCIIHexDigit(p[4]) && isASCIIHexDigit(p[5])) {
127 charLen = 6;
128 u = Lexer::convertUnicode(p[2], p[3], p[4], p[5]);
129 }
130 }
131 if (charLen && (u == 0 || u >= 128 || !strchr(doNotUnescape, u))) {
132 c = u;
133 k += charLen - 1;
134 }
135 }
136 k++;
137 builder.append(c);
138 }
139 return builder.build(exec);
140}
141
142bool isStrWhiteSpace(UChar c)
143{
144 switch (c) {
145 case 0x0009:
146 case 0x000A:
147 case 0x000B:
148 case 0x000C:
149 case 0x000D:
150 case 0x0020:
151 case 0x00A0:
152 case 0x2028:
153 case 0x2029:
154 return true;
155 default:
156 return c > 0xff && isSeparatorSpace(c);
157 }
158}
159
160static int parseDigit(unsigned short c, int radix)
161{
162 int digit = -1;
163
164 if (c >= '0' && c <= '9')
165 digit = c - '0';
166 else if (c >= 'A' && c <= 'Z')
167 digit = c - 'A' + 10;
168 else if (c >= 'a' && c <= 'z')
169 digit = c - 'a' + 10;
170
171 if (digit >= radix)
172 return -1;
173 return digit;
174}
175
176double parseIntOverflow(const char* s, int length, int radix)
177{
178 double number = 0.0;
179 double radixMultiplier = 1.0;
180
181 for (const char* p = s + length - 1; p >= s; p--) {
182 if (radixMultiplier == Inf) {
183 if (*p != '0') {
184 number = Inf;
185 break;
186 }
187 } else {
188 int digit = parseDigit(*p, radix);
189 number += digit * radixMultiplier;
190 }
191
192 radixMultiplier *= radix;
193 }
194
195 return number;
196}
197
198static double parseInt(const UString& s, int radix)
199{
200 int length = s.size();
201 const UChar* data = s.data();
202 int p = 0;
203
204 while (p < length && isStrWhiteSpace(data[p]))
205 ++p;
206
207 double sign = 1;
208 if (p < length) {
209 if (data[p] == '+')
210 ++p;
211 else if (data[p] == '-') {
212 sign = -1;
213 ++p;
214 }
215 }
216
217 if ((radix == 0 || radix == 16) && length - p >= 2 && data[p] == '0' && (data[p + 1] == 'x' || data[p + 1] == 'X')) {
218 radix = 16;
219 p += 2;
220 } else if (radix == 0) {
221 if (p < length && data[p] == '0')
222 radix = 8;
223 else
224 radix = 10;
225 }
226
227 if (radix < 2 || radix > 36)
228 return NaN;
229
230 int firstDigitPosition = p;
231 bool sawDigit = false;
232 double number = 0;
233 while (p < length) {
234 int digit = parseDigit(data[p], radix);
235 if (digit == -1)
236 break;
237 sawDigit = true;
238 number *= radix;
239 number += digit;
240 ++p;
241 }
242
243 if (number >= mantissaOverflowLowerBound) {
244 if (radix == 10)
245 number = WTF::strtod(s.substr(firstDigitPosition, p - firstDigitPosition).UTF8String().data(), 0);
246 else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32)
247 number = parseIntOverflow(s.substr(firstDigitPosition, p - firstDigitPosition).UTF8String().data(), p - firstDigitPosition, radix);
248 }
249
250 if (!sawDigit)
251 return NaN;
252
253 return sign * number;
254}
255
256static double parseFloat(const UString& s)
257{
258 // Check for 0x prefix here, because toDouble allows it, but we must treat it as 0.
259 // Need to skip any whitespace and then one + or - sign.
260 int length = s.size();
261 const UChar* data = s.data();
262 int p = 0;
263 while (p < length && isStrWhiteSpace(data[p]))
264 ++p;
265
266 if (p < length && (data[p] == '+' || data[p] == '-'))
267 ++p;
268
269 if (length - p >= 2 && data[p] == '0' && (data[p + 1] == 'x' || data[p + 1] == 'X'))
270 return 0;
271
272 return s.toDouble(true /*tolerant*/, false /* NaN for empty string */);
273}
274
275EncodedJSValue JSC_HOST_CALL globalFuncEval(ExecState* exec)
276{
277 JSObject* thisObject = exec->hostThisValue().toThisObject(exec);
278 JSObject* unwrappedObject = thisObject->unwrappedObject();
279 if (!unwrappedObject->isGlobalObject() || static_cast<JSGlobalObject*>(unwrappedObject)->evalFunction() != exec->callee())
280 return throwVMError(exec, createEvalError(exec, "The \"this\" value passed to eval must be the global object from which eval originated"));
281
282 JSValue x = exec->argument(0);
283 if (!x.isString())
284 return JSValue::encode(x);
285
286 UString s = x.toString(exec);
287
288 LiteralParser preparser(exec, s, LiteralParser::NonStrictJSON);
289 if (JSValue parsedObject = preparser.tryLiteralParse())
290 return JSValue::encode(parsedObject);
291
292 RefPtr<EvalExecutable> eval = EvalExecutable::create(exec, makeSource(s));
293 JSObject* error = eval->compile(exec, static_cast<JSGlobalObject*>(unwrappedObject)->globalScopeChain().node());
294 if (error)
295 return throwVMError(exec, error);
296
297 return JSValue::encode(exec->interpreter()->execute(eval.get(), exec, thisObject, static_cast<JSGlobalObject*>(unwrappedObject)->globalScopeChain().node(), exec->exceptionSlot()));
298}
299
300EncodedJSValue JSC_HOST_CALL globalFuncParseInt(ExecState* exec)
301{
302 JSValue value = exec->argument(0);
303 int32_t radix = exec->argument(1).toInt32(exec);
304
305 if (radix != 0 && radix != 10)
306 return JSValue::encode(jsNumber(exec, parseInt(value.toString(exec), radix)));
307
308 if (value.isInt32())
309 return JSValue::encode(value);
310
311 if (value.isDouble()) {
312 double d = value.asDouble();
313 if (isfinite(d))
314 return JSValue::encode(jsNumber(exec, (d > 0) ? floor(d) : ceil(d)));
315 if (isnan(d) || isinf(d))
316 return JSValue::encode(jsNaN(exec));
317 return JSValue::encode(jsNumber(exec, 0));
318 }
319
320 return JSValue::encode(jsNumber(exec, parseInt(value.toString(exec), radix)));
321}
322
323EncodedJSValue JSC_HOST_CALL globalFuncParseFloat(ExecState* exec)
324{
325 return JSValue::encode(jsNumber(exec, parseFloat(exec->argument(0).toString(exec))));
326}
327
328EncodedJSValue JSC_HOST_CALL globalFuncIsNaN(ExecState* exec)
329{
330 return JSValue::encode(jsBoolean(isnan(exec->argument(0).toNumber(exec))));
331}
332
333EncodedJSValue JSC_HOST_CALL globalFuncIsFinite(ExecState* exec)
334{
335 double n = exec->argument(0).toNumber(exec);
336 return JSValue::encode(jsBoolean(!isnan(n) && !isinf(n)));
337}
338
339EncodedJSValue JSC_HOST_CALL globalFuncDecodeURI(ExecState* exec)
340{
341 static const char do_not_unescape_when_decoding_URI[] =
342 "#$&+,/:;=?@";
343
344 return JSValue::encode(decode(exec, do_not_unescape_when_decoding_URI, true));
345}
346
347EncodedJSValue JSC_HOST_CALL globalFuncDecodeURIComponent(ExecState* exec)
348{
349 return JSValue::encode(decode(exec, "", true));
350}
351
352EncodedJSValue JSC_HOST_CALL globalFuncEncodeURI(ExecState* exec)
353{
354 static const char do_not_escape_when_encoding_URI[] =
355 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
356 "abcdefghijklmnopqrstuvwxyz"
357 "0123456789"
358 "!#$&'()*+,-./:;=?@_~";
359
360 return JSValue::encode(encode(exec, do_not_escape_when_encoding_URI));
361}
362
363EncodedJSValue JSC_HOST_CALL globalFuncEncodeURIComponent(ExecState* exec)
364{
365 static const char do_not_escape_when_encoding_URI_component[] =
366 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
367 "abcdefghijklmnopqrstuvwxyz"
368 "0123456789"
369 "!'()*-._~";
370
371 return JSValue::encode(encode(exec, do_not_escape_when_encoding_URI_component));
372}
373
374EncodedJSValue JSC_HOST_CALL globalFuncEscape(ExecState* exec)
375{
376 static const char do_not_escape[] =
377 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
378 "abcdefghijklmnopqrstuvwxyz"
379 "0123456789"
380 "*+-./@_";
381
382 JSStringBuilder builder;
383 UString str = exec->argument(0).toString(exec);
384 const UChar* c = str.data();
385 for (unsigned k = 0; k < str.size(); k++, c++) {
386 int u = c[0];
387 if (u > 255) {
388 char tmp[7];
389 sprintf(tmp, "%%u%04X", u);
390 builder.append(tmp);
391 } else if (u != 0 && strchr(do_not_escape, static_cast<char>(u)))
392 builder.append(c, 1);
393 else {
394 char tmp[4];
395 sprintf(tmp, "%%%02X", u);
396 builder.append(tmp);
397 }
398 }
399
400 return JSValue::encode(builder.build(exec));
401}
402
403EncodedJSValue JSC_HOST_CALL globalFuncUnescape(ExecState* exec)
404{
405 StringBuilder builder;
406 UString str = exec->argument(0).toString(exec);
407 int k = 0;
408 int len = str.size();
409 while (k < len) {
410 const UChar* c = str.data() + k;
411 UChar u;
412 if (c[0] == '%' && k <= len - 6 && c[1] == 'u') {
413 if (isASCIIHexDigit(c[2]) && isASCIIHexDigit(c[3]) && isASCIIHexDigit(c[4]) && isASCIIHexDigit(c[5])) {
414 u = Lexer::convertUnicode(c[2], c[3], c[4], c[5]);
415 c = &u;
416 k += 5;
417 }
418 } else if (c[0] == '%' && k <= len - 3 && isASCIIHexDigit(c[1]) && isASCIIHexDigit(c[2])) {
419 u = UChar(Lexer::convertHex(c[1], c[2]));
420 c = &u;
421 k += 2;
422 }
423 k++;
424 builder.append(*c);
425 }
426
427 return JSValue::encode(jsString(exec, builder.build()));
428}
429
430#ifndef NDEBUG
431EncodedJSValue JSC_HOST_CALL globalFuncJSCPrint(ExecState* exec)
432{
433 CString string = exec->argument(0).toString(exec).UTF8String();
434 puts(string.data());
435 return JSValue::encode(jsUndefined());
436}
437#endif
438
439} // namespace JSC
Note: See TracBrowser for help on using the repository browser.