JSGlobalObjectFunctions.cpp 25.5 KB
Newer Older
weinig@apple.com's avatar
weinig@apple.com committed
1 2 3
/*
 *  Copyright (C) 1999-2002 Harri Porten (porten@kde.org)
 *  Copyright (C) 2001 Peter Kelly (pmk@post.com)
4
 *  Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2012 Apple Inc. All rights reserved.
weinig@apple.com's avatar
weinig@apple.com committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *  Copyright (C) 2007 Cameron Zwarich (cwzwarich@uwaterloo.ca)
 *  Copyright (C) 2007 Maks Orlovich
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 *
 */

#include "config.h"
#include "JSGlobalObjectFunctions.h"

ggaren@apple.com's avatar
ggaren@apple.com committed
28
#include "CallFrame.h"
29
#include "CallFrameInlines.h"
30
#include "Interpreter.h"
31
#include "JSFunction.h"
weinig@apple.com's avatar
weinig@apple.com committed
32 33
#include "JSGlobalObject.h"
#include "JSString.h"
34
#include "JSStringBuilder.h"
35
#include "Lexer.h"
36
#include "LiteralParser.h"
37
#include "Nodes.h"
38
#include "Operations.h"
39
#include "Parser.h"
40
#include "StackVisitor.h"
41
#include <wtf/dtoa.h>
weinig@apple.com's avatar
weinig@apple.com committed
42 43 44 45 46
#include <stdio.h>
#include <stdlib.h>
#include <wtf/ASCIICType.h>
#include <wtf/Assertions.h>
#include <wtf/MathExtras.h>
47
#include <wtf/StringExtras.h>
48
#include <wtf/text/StringBuilder.h>
weinig@apple.com's avatar
weinig@apple.com committed
49 50 51 52 53
#include <wtf/unicode/UTF8.h>

using namespace WTF;
using namespace Unicode;

54
namespace JSC {
weinig@apple.com's avatar
weinig@apple.com committed
55

56
static JSValue encode(ExecState* exec, const char* doNotEscape)
weinig@apple.com's avatar
weinig@apple.com committed
57
{
58
    CString cstr = exec->argument(0).toString(exec)->value(exec).utf8(StrictConversion);
59
    if (!cstr.data())
60
        return exec->vm().throwException(exec, createURIError(exec, ASCIILiteral("String contained an illegal UTF-16 sequence.")));
weinig@apple.com's avatar
weinig@apple.com committed
61

62
    JSStringBuilder builder;
63 64
    const char* p = cstr.data();
    for (size_t k = 0; k < cstr.length(); k++, p++) {
weinig@apple.com's avatar
weinig@apple.com committed
65 66
        char c = *p;
        if (c && strchr(doNotEscape, c))
67
            builder.append(c);
weinig@apple.com's avatar
weinig@apple.com committed
68 69
        else {
            char tmp[4];
70
            snprintf(tmp, sizeof(tmp), "%%%02X", static_cast<unsigned char>(c));
71
            builder.append(tmp);
weinig@apple.com's avatar
weinig@apple.com committed
72
        }
weinig@apple.com's avatar
weinig@apple.com committed
73
    }
74
    return builder.build(exec);
weinig@apple.com's avatar
weinig@apple.com committed
75 76
}

77 78 79
template <typename CharType>
ALWAYS_INLINE
static JSValue decode(ExecState* exec, const CharType* characters, int length, const char* doNotUnescape, bool strict)
weinig@apple.com's avatar
weinig@apple.com committed
80
{
81
    JSStringBuilder builder;
weinig@apple.com's avatar
weinig@apple.com committed
82 83
    int k = 0;
    UChar u = 0;
84 85 86
    while (k < length) {
        const CharType* p = characters + k;
        CharType c = *p;
weinig@apple.com's avatar
weinig@apple.com committed
87 88
        if (c == '%') {
            int charLen = 0;
89 90
            if (k <= length - 3 && isASCIIHexDigit(p[1]) && isASCIIHexDigit(p[2])) {
                const char b0 = Lexer<CharType>::convertHex(p[1], p[2]);
weinig@apple.com's avatar
weinig@apple.com committed
91
                const int sequenceLen = UTF8SequenceLength(b0);
92
                if (sequenceLen && k <= length - sequenceLen * 3) {
weinig@apple.com's avatar
weinig@apple.com committed
93 94 95 96
                    charLen = sequenceLen * 3;
                    char sequence[5];
                    sequence[0] = b0;
                    for (int i = 1; i < sequenceLen; ++i) {
97
                        const CharType* q = p + i * 3;
weinig@apple.com's avatar
weinig@apple.com committed
98
                        if (q[0] == '%' && isASCIIHexDigit(q[1]) && isASCIIHexDigit(q[2]))
99
                            sequence[i] = Lexer<CharType>::convertHex(q[1], q[2]);
weinig@apple.com's avatar
weinig@apple.com committed
100 101 102 103 104 105 106 107 108 109 110 111
                        else {
                            charLen = 0;
                            break;
                        }
                    }
                    if (charLen != 0) {
                        sequence[sequenceLen] = 0;
                        const int character = decodeUTF8Sequence(sequence);
                        if (character < 0 || character >= 0x110000)
                            charLen = 0;
                        else if (character >= 0x10000) {
                            // Convert to surrogate pair.
112
                            builder.append(static_cast<UChar>(0xD800 | ((character - 0x10000) >> 10)));
weinig@apple.com's avatar
weinig@apple.com committed
113 114 115 116 117
                            u = static_cast<UChar>(0xDC00 | ((character - 0x10000) & 0x3FF));
                        } else
                            u = static_cast<UChar>(character);
                    }
                }
weinig@apple.com's avatar
weinig@apple.com committed
118
            }
weinig@apple.com's avatar
weinig@apple.com committed
119 120
            if (charLen == 0) {
                if (strict)
121
                    return exec->vm().throwException(exec, createURIError(exec, ASCIILiteral("URI error")));
weinig@apple.com's avatar
weinig@apple.com committed
122 123
                // The only case where we don't use "strict" mode is the "unescape" function.
                // For that, it's good to support the wonky "%u" syntax for compatibility with WinIE.
124
                if (k <= length - 6 && p[1] == 'u'
weinig@apple.com's avatar
weinig@apple.com committed
125 126 127
                        && isASCIIHexDigit(p[2]) && isASCIIHexDigit(p[3])
                        && isASCIIHexDigit(p[4]) && isASCIIHexDigit(p[5])) {
                    charLen = 6;
128
                    u = Lexer<UChar>::convertUnicode(p[2], p[3], p[4], p[5]);
weinig@apple.com's avatar
weinig@apple.com committed
129 130 131
                }
            }
            if (charLen && (u == 0 || u >= 128 || !strchr(doNotUnescape, u))) {
132 133 134 135 136 137
                if (u < 256)
                    builder.append(static_cast<LChar>(u));
                else
                    builder.append(u);
                k += charLen;
                continue;
weinig@apple.com's avatar
weinig@apple.com committed
138 139
            }
        }
weinig@apple.com's avatar
weinig@apple.com committed
140
        k++;
141
        builder.append(c);
weinig@apple.com's avatar
weinig@apple.com committed
142
    }
143
    return builder.build(exec);
weinig@apple.com's avatar
weinig@apple.com committed
144 145
}

146 147 148
static JSValue decode(ExecState* exec, const char* doNotUnescape, bool strict)
{
    JSStringBuilder builder;
149
    String str = exec->argument(0).toString(exec)->value(exec);
150 151 152 153 154 155
    
    if (str.is8Bit())
        return decode(exec, str.characters8(), str.length(), doNotUnescape, strict);
    return decode(exec, str.characters16(), str.length(), doNotUnescape, strict);
}

sfalken@apple.com's avatar
sfalken@apple.com committed
156
bool isStrWhiteSpace(UChar c)
weinig@apple.com's avatar
weinig@apple.com committed
157 158
{
    switch (c) {
barraclough@apple.com's avatar
barraclough@apple.com committed
159
        // ECMA-262-5th 7.2 & 7.3
weinig@apple.com's avatar
weinig@apple.com committed
160 161 162 163 164 165 166
        case 0x0009:
        case 0x000A:
        case 0x000B:
        case 0x000C:
        case 0x000D:
        case 0x0020:
        case 0x00A0:
167
        case 0x180E: // This character used to be in Zs category before Unicode 6.3, and EcmaScript says that we should keep treating it as such.
weinig@apple.com's avatar
weinig@apple.com committed
168 169
        case 0x2028:
        case 0x2029:
barraclough@apple.com's avatar
barraclough@apple.com committed
170
        case 0xFEFF:
weinig@apple.com's avatar
weinig@apple.com committed
171 172
            return true;
        default:
173
            return c > 0xFF && u_charType(c) == U_SPACE_SEPARATOR;
weinig@apple.com's avatar
weinig@apple.com committed
174 175 176 177 178 179 180
    }
}

static int parseDigit(unsigned short c, int radix)
{
    int digit = -1;

weinig@apple.com's avatar
weinig@apple.com committed
181
    if (c >= '0' && c <= '9')
weinig@apple.com's avatar
weinig@apple.com committed
182
        digit = c - '0';
weinig@apple.com's avatar
weinig@apple.com committed
183
    else if (c >= 'A' && c <= 'Z')
weinig@apple.com's avatar
weinig@apple.com committed
184
        digit = c - 'A' + 10;
weinig@apple.com's avatar
weinig@apple.com committed
185
    else if (c >= 'a' && c <= 'z')
weinig@apple.com's avatar
weinig@apple.com committed
186 187 188 189 190 191 192
        digit = c - 'a' + 10;

    if (digit >= radix)
        return -1;
    return digit;
}

193
double parseIntOverflow(const LChar* s, int length, int radix)
weinig@apple.com's avatar
weinig@apple.com committed
194 195 196 197
{
    double number = 0.0;
    double radixMultiplier = 1.0;

198
    for (const LChar* p = s + length - 1; p >= s; p--) {
199
        if (radixMultiplier == std::numeric_limits<double>::infinity()) {
weinig@apple.com's avatar
weinig@apple.com committed
200
            if (*p != '0') {
201
                number = std::numeric_limits<double>::infinity();
weinig@apple.com's avatar
weinig@apple.com committed
202 203 204 205 206 207 208 209 210 211 212 213 214
                break;
            }
        } else {
            int digit = parseDigit(*p, radix);
            number += digit * radixMultiplier;
        }

        radixMultiplier *= radix;
    }

    return number;
}

215 216 217 218 219 220
double parseIntOverflow(const UChar* s, int length, int radix)
{
    double number = 0.0;
    double radixMultiplier = 1.0;

    for (const UChar* p = s + length - 1; p >= s; p--) {
221
        if (radixMultiplier == std::numeric_limits<double>::infinity()) {
222
            if (*p != '0') {
223
                number = std::numeric_limits<double>::infinity();
224 225 226 227 228 229 230 231 232 233 234 235 236
                break;
            }
        } else {
            int digit = parseDigit(*p, radix);
            number += digit * radixMultiplier;
        }

        radixMultiplier *= radix;
    }

    return number;
}

237
// ES5.1 15.1.2.2
238 239
template <typename CharType>
ALWAYS_INLINE
240
static double parseInt(const String& s, const CharType* data, int radix)
weinig@apple.com's avatar
weinig@apple.com committed
241
{
242 243 244 245
    // 1. Let inputString be ToString(string).
    // 2. Let S be a newly created substring of inputString consisting of the first character that is not a
    //    StrWhiteSpaceChar and all characters following that character. (In other words, remove leading white
    //    space.) If inputString does not contain any such characters, let S be the empty string.
246
    int length = s.length();
weinig@apple.com's avatar
weinig@apple.com committed
247
    int p = 0;
248
    while (p < length && isStrWhiteSpace(data[p]))
weinig@apple.com's avatar
weinig@apple.com committed
249 250
        ++p;

251 252 253
    // 3. Let sign be 1.
    // 4. If S is not empty and the first character of S is a minus sign -, let sign be -1.
    // 5. If S is not empty and the first character of S is a plus sign + or a minus sign -, then remove the first character from S.
weinig@apple.com's avatar
weinig@apple.com committed
254 255
    double sign = 1;
    if (p < length) {
256
        if (data[p] == '+')
weinig@apple.com's avatar
weinig@apple.com committed
257
            ++p;
258
        else if (data[p] == '-') {
weinig@apple.com's avatar
weinig@apple.com committed
259 260 261 262 263
            sign = -1;
            ++p;
        }
    }

264 265 266 267 268 269 270 271 272 273 274
    // 6. Let R = ToInt32(radix).
    // 7. Let stripPrefix be true.
    // 8. If R != 0,then
    //   b. If R != 16, let stripPrefix be false.
    // 9. Else, R == 0
    //   a. LetR = 10.
    // 10. If stripPrefix is true, then
    //   a. If the length of S is at least 2 and the first two characters of S are either ―0x or ―0X,
    //      then remove the first two characters from S and let R = 16.
    // 11. If S contains any character that is not a radix-R digit, then let Z be the substring of S
    //     consisting of all characters before the first such character; otherwise, let Z be S.
275
    if ((radix == 0 || radix == 16) && length - p >= 2 && data[p] == '0' && (data[p + 1] == 'x' || data[p + 1] == 'X')) {
weinig@apple.com's avatar
weinig@apple.com committed
276 277
        radix = 16;
        p += 2;
278 279
    } else if (radix == 0)
        radix = 10;
weinig@apple.com's avatar
weinig@apple.com committed
280

281
    // 8.a If R < 2 or R > 36, then return NaN.
weinig@apple.com's avatar
weinig@apple.com committed
282
    if (radix < 2 || radix > 36)
283
        return QNaN;
weinig@apple.com's avatar
weinig@apple.com committed
284

285 286 287 288 289 290
    // 13. Let mathInt be the mathematical integer value that is represented by Z in radix-R notation, using the letters
    //     A-Z and a-z for digits with values 10 through 35. (However, if R is 10 and Z contains more than 20 significant
    //     digits, every significant digit after the 20th may be replaced by a 0 digit, at the option of the implementation;
    //     and if R is not 2, 4, 8, 10, 16, or 32, then mathInt may be an implementation-dependent approximation to the
    //     mathematical integer value that is represented by Z in radix-R notation.)
    // 14. Let number be the Number value for mathInt.
weinig@apple.com's avatar
weinig@apple.com committed
291 292 293 294
    int firstDigitPosition = p;
    bool sawDigit = false;
    double number = 0;
    while (p < length) {
295
        int digit = parseDigit(data[p], radix);
weinig@apple.com's avatar
weinig@apple.com committed
296 297 298 299 300 301 302 303
        if (digit == -1)
            break;
        sawDigit = true;
        number *= radix;
        number += digit;
        ++p;
    }

304
    // 12. If Z is empty, return NaN.
weinig@apple.com's avatar
weinig@apple.com committed
305
    if (!sawDigit)
306
        return QNaN;
weinig@apple.com's avatar
weinig@apple.com committed
307

308 309 310 311
    // Alternate code path for certain large numbers.
    if (number >= mantissaOverflowLowerBound) {
        if (radix == 10) {
            size_t parsedLength;
312
            number = parseDouble(s.deprecatedCharacters() + firstDigitPosition, p - firstDigitPosition, parsedLength);
313 314 315 316
        } else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32)
            number = parseIntOverflow(s.substringSharingImpl(firstDigitPosition, p - firstDigitPosition).utf8().data(), p - firstDigitPosition, radix);
    }

317
    // 15. Return sign x number.
weinig@apple.com's avatar
weinig@apple.com committed
318 319 320
    return sign * number;
}

321
static double parseInt(const String& s, int radix)
322 323 324 325 326 327
{
    if (s.is8Bit())
        return parseInt(s, s.characters8(), radix);
    return parseInt(s, s.characters16(), radix);
}

328 329
static const int SizeOfInfinity = 8;

330 331
template <typename CharType>
static bool isInfinity(const CharType* data, const CharType* end)
332 333 334 335 336 337 338 339 340 341 342 343 344
{
    return (end - data) >= SizeOfInfinity
        && data[0] == 'I'
        && data[1] == 'n'
        && data[2] == 'f'
        && data[3] == 'i'
        && data[4] == 'n'
        && data[5] == 'i'
        && data[6] == 't'
        && data[7] == 'y';
}

// See ecma-262 9.3.1
345 346
template <typename CharType>
static double jsHexIntegerLiteral(const CharType*& data, const CharType* end)
347 348 349
{
    // Hex number.
    data += 2;
350
    const CharType* firstDigitPosition = data;
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    double number = 0;
    while (true) {
        number = number * 16 + toASCIIHexValue(*data);
        ++data;
        if (data == end)
            break;
        if (!isASCIIHexDigit(*data))
            break;
    }
    if (number >= mantissaOverflowLowerBound)
        number = parseIntOverflow(firstDigitPosition, data - firstDigitPosition, 16);

    return number;
}

// See ecma-262 9.3.1
367
template <typename CharType>
368
static double jsStrDecimalLiteral(const CharType*& data, const CharType* end)
369
{
370
    RELEASE_ASSERT(data < end);
371

372 373 374 375
    size_t parsedLength;
    double number = parseDouble(data, end - data, parsedLength);
    if (parsedLength) {
        data += parsedLength;
376 377 378 379 380 381 382 383
        return number;
    }

    // Check for [+-]?Infinity
    switch (*data) {
    case 'I':
        if (isInfinity(data, end)) {
            data += SizeOfInfinity;
384
            return std::numeric_limits<double>::infinity();
385 386 387 388 389 390
        }
        break;

    case '+':
        if (isInfinity(data + 1, end)) {
            data += SizeOfInfinity + 1;
391
            return std::numeric_limits<double>::infinity();
392 393 394 395 396 397
        }
        break;

    case '-':
        if (isInfinity(data + 1, end)) {
            data += SizeOfInfinity + 1;
398
            return -std::numeric_limits<double>::infinity();
399 400 401 402 403
        }
        break;
    }

    // Not a number.
404
    return QNaN;
405 406
}

407 408
template <typename CharType>
static double toDouble(const CharType* characters, unsigned size)
409
{
410
    const CharType* endCharacters = characters + size;
411 412

    // Skip leading white space.
413 414
    for (; characters < endCharacters; ++characters) {
        if (!isStrWhiteSpace(*characters))
415 416
            break;
    }
417
    
418
    // Empty string.
419
    if (characters == endCharacters)
420
        return 0.0;
421
    
422
    double number;
423 424
    if (characters[0] == '0' && characters + 2 < endCharacters && (characters[1] | 0x20) == 'x' && isASCIIHexDigit(characters[2]))
        number = jsHexIntegerLiteral(characters, endCharacters);
425
    else
426
        number = jsStrDecimalLiteral(characters, endCharacters);
427
    
428
    // Allow trailing white space.
429 430
    for (; characters < endCharacters; ++characters) {
        if (!isStrWhiteSpace(*characters))
431 432
            break;
    }
433
    if (characters != endCharacters)
434
        return QNaN;
435
    
436 437 438
    return number;
}

439
// See ecma-262 9.3.1
440
double jsToNumber(const String& s)
441 442 443 444 445 446 447 448 449
{
    unsigned size = s.length();

    if (size == 1) {
        UChar c = s[0];
        if (isASCIIDigit(c))
            return c - '0';
        if (isStrWhiteSpace(c))
            return 0;
450
        return QNaN;
451 452 453 454 455 456 457
    }

    if (s.is8Bit())
        return toDouble(s.characters8(), size);
    return toDouble(s.characters16(), size);
}

458
static double parseFloat(const String& s)
weinig@apple.com's avatar
weinig@apple.com committed
459
{
460 461 462
    unsigned size = s.length();

    if (size == 1) {
463
        UChar c = s[0];
464 465
        if (isASCIIDigit(c))
            return c - '0';
466
        return QNaN;
467 468
    }

469 470 471 472 473 474 475 476 477 478 479 480
    if (s.is8Bit()) {
        const LChar* data = s.characters8();
        const LChar* end = data + size;

        // Skip leading white space.
        for (; data < end; ++data) {
            if (!isStrWhiteSpace(*data))
                break;
        }

        // Empty string.
        if (data == end)
481
            return QNaN;
482

483
        return jsStrDecimalLiteral(data, end);
484 485 486
    }

    const UChar* data = s.characters16();
487
    const UChar* end = data + size;
weinig@apple.com's avatar
weinig@apple.com committed
488

489 490 491 492 493
    // Skip leading white space.
    for (; data < end; ++data) {
        if (!isStrWhiteSpace(*data))
            break;
    }
weinig@apple.com's avatar
weinig@apple.com committed
494

495 496
    // Empty string.
    if (data == end)
497
        return QNaN;
weinig@apple.com's avatar
weinig@apple.com committed
498

499
    return jsStrDecimalLiteral(data, end);
weinig@apple.com's avatar
weinig@apple.com committed
500 501
}

502
EncodedJSValue JSC_HOST_CALL globalFuncEval(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
503
{
504
    JSValue x = exec->argument(0);
weinig@apple.com's avatar
weinig@apple.com committed
505
    if (!x.isString())
506
        return JSValue::encode(x);
weinig@apple.com's avatar
weinig@apple.com committed
507

508
    String s = x.toString(exec)->value(exec);
weinig@apple.com's avatar
weinig@apple.com committed
509

510 511 512 513 514 515 516 517 518
    if (s.is8Bit()) {
        LiteralParser<LChar> preparser(exec, s.characters8(), s.length(), NonStrictJSON);
        if (JSValue parsedObject = preparser.tryLiteralParse())
            return JSValue::encode(parsedObject);
    } else {
        LiteralParser<UChar> preparser(exec, s.characters16(), s.length(), NonStrictJSON);
        if (JSValue parsedObject = preparser.tryLiteralParse())
            return JSValue::encode(parsedObject);        
    }
519

520
    JSGlobalObject* calleeGlobalObject = exec->callee()->globalObject();
521 522
    EvalExecutable* eval = EvalExecutable::create(exec, makeSource(s), false);
    if (!eval)
523
        return JSValue::encode(jsUndefined());
weinig@apple.com's avatar
weinig@apple.com committed
524

525
    return JSValue::encode(exec->interpreter()->execute(eval, exec, calleeGlobalObject->globalThis(), calleeGlobalObject));
weinig@apple.com's avatar
weinig@apple.com committed
526 527
}

528
EncodedJSValue JSC_HOST_CALL globalFuncParseInt(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
529
{
530
    JSValue value = exec->argument(0);
531 532 533 534 535 536 537 538 539 540 541 542 543
    JSValue radixValue = exec->argument(1);

    // Optimized handling for numbers:
    // If the argument is 0 or a number in range 10^-6 <= n < INT_MAX+1, then parseInt
    // results in a truncation to integer. In the case of -0, this is converted to 0.
    //
    // This is also a truncation for values in the range INT_MAX+1 <= n < 10^21,
    // however these values cannot be trivially truncated to int since 10^21 exceeds
    // even the int64_t range. Negative numbers are a little trickier, the case for
    // values in the range -10^21 < n <= -1 are similar to those for integer, but
    // values in the range -1 < n <= -10^-6 need to truncate to -0, not 0.
    static const double tenToTheMinus6 = 0.000001;
    static const double intMaxPlusOne = 2147483648.0;
ggaren@apple.com's avatar
ggaren@apple.com committed
544 545 546 547 548
    if (value.isNumber()) {
        double n = value.asNumber();
        if (((n < intMaxPlusOne && n >= tenToTheMinus6) || !n) && radixValue.isUndefinedOrNull())
            return JSValue::encode(jsNumber(static_cast<int32_t>(n)));
    }
549

550
    // If ToString throws, we shouldn't call ToInt32.
551
    String s = value.toString(exec)->value(exec);
552 553
    if (exec->hadException())
        return JSValue::encode(jsUndefined());
554

555
    return JSValue::encode(jsNumber(parseInt(s, radixValue.toInt32(exec))));
weinig@apple.com's avatar
weinig@apple.com committed
556 557
}

558
EncodedJSValue JSC_HOST_CALL globalFuncParseFloat(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
559
{
560
    return JSValue::encode(jsNumber(parseFloat(exec->argument(0).toString(exec)->value(exec))));
weinig@apple.com's avatar
weinig@apple.com committed
561 562
}

563
EncodedJSValue JSC_HOST_CALL globalFuncIsNaN(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
564
{
565
    return JSValue::encode(jsBoolean(std::isnan(exec->argument(0).toNumber(exec))));
weinig@apple.com's avatar
weinig@apple.com committed
566 567
}

568
EncodedJSValue JSC_HOST_CALL globalFuncIsFinite(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
569
{
570
    double n = exec->argument(0).toNumber(exec);
571
    return JSValue::encode(jsBoolean(std::isfinite(n)));
weinig@apple.com's avatar
weinig@apple.com committed
572 573
}

574
EncodedJSValue JSC_HOST_CALL globalFuncDecodeURI(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
575 576 577 578
{
    static const char do_not_unescape_when_decoding_URI[] =
        "#$&+,/:;=?@";

579
    return JSValue::encode(decode(exec, do_not_unescape_when_decoding_URI, true));
weinig@apple.com's avatar
weinig@apple.com committed
580 581
}

582
EncodedJSValue JSC_HOST_CALL globalFuncDecodeURIComponent(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
583
{
584
    return JSValue::encode(decode(exec, "", true));
weinig@apple.com's avatar
weinig@apple.com committed
585 586
}

587
EncodedJSValue JSC_HOST_CALL globalFuncEncodeURI(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
588 589 590 591 592 593 594
{
    static const char do_not_escape_when_encoding_URI[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "0123456789"
        "!#$&'()*+,-./:;=?@_~";

595
    return JSValue::encode(encode(exec, do_not_escape_when_encoding_URI));
weinig@apple.com's avatar
weinig@apple.com committed
596 597
}

598
EncodedJSValue JSC_HOST_CALL globalFuncEncodeURIComponent(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
599 600 601 602 603 604 605
{
    static const char do_not_escape_when_encoding_URI_component[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "0123456789"
        "!'()*-._~";

606
    return JSValue::encode(encode(exec, do_not_escape_when_encoding_URI_component));
weinig@apple.com's avatar
weinig@apple.com committed
607 608
}

609
EncodedJSValue JSC_HOST_CALL globalFuncEscape(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
610 611 612 613 614 615 616
{
    static const char do_not_escape[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "0123456789"
        "*+-./@_";

617
    JSStringBuilder builder;
618
    String str = exec->argument(0).toString(exec)->value(exec);
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    if (str.is8Bit()) {
        const LChar* c = str.characters8();
        for (unsigned k = 0; k < str.length(); k++, c++) {
            int u = c[0];
            if (u && strchr(do_not_escape, static_cast<char>(u)))
                builder.append(c, 1);
            else {
                char tmp[4];
                snprintf(tmp, sizeof(tmp), "%%%02X", u);
                builder.append(tmp);
            }
        }

        return JSValue::encode(builder.build(exec));        
    }

    const UChar* c = str.characters16();
636
    for (unsigned k = 0; k < str.length(); k++, c++) {
weinig@apple.com's avatar
weinig@apple.com committed
637 638 639
        int u = c[0];
        if (u > 255) {
            char tmp[7];
640
            snprintf(tmp, sizeof(tmp), "%%u%04X", u);
641
            builder.append(tmp);
weinig@apple.com's avatar
weinig@apple.com committed
642
        } else if (u != 0 && strchr(do_not_escape, static_cast<char>(u)))
643
            builder.append(c, 1);
weinig@apple.com's avatar
weinig@apple.com committed
644 645
        else {
            char tmp[4];
646
            snprintf(tmp, sizeof(tmp), "%%%02X", u);
647
            builder.append(tmp);
weinig@apple.com's avatar
weinig@apple.com committed
648 649 650
        }
    }

651
    return JSValue::encode(builder.build(exec));
weinig@apple.com's avatar
weinig@apple.com committed
652 653
}

654
EncodedJSValue JSC_HOST_CALL globalFuncUnescape(ExecState* exec)
weinig@apple.com's avatar
weinig@apple.com committed
655
{
656 657
    StringBuilder builder;
    String str = exec->argument(0).toString(exec)->value(exec);
weinig@apple.com's avatar
weinig@apple.com committed
658
    int k = 0;
659
    int len = str.length();
660 661 662
    
    if (str.is8Bit()) {
        const LChar* characters = str.characters8();
663
        LChar convertedLChar;
664 665 666 667 668
        while (k < len) {
            const LChar* c = characters + k;
            if (c[0] == '%' && k <= len - 6 && c[1] == 'u') {
                if (isASCIIHexDigit(c[2]) && isASCIIHexDigit(c[3]) && isASCIIHexDigit(c[4]) && isASCIIHexDigit(c[5])) {
                    builder.append(Lexer<UChar>::convertUnicode(c[2], c[3], c[4], c[5]));
669 670
                    k += 6;
                    continue;
671 672
                }
            } else if (c[0] == '%' && k <= len - 3 && isASCIIHexDigit(c[1]) && isASCIIHexDigit(c[2])) {
673 674
                convertedLChar = LChar(Lexer<LChar>::convertHex(c[1], c[2]));
                c = &convertedLChar;
675
                k += 2;
676 677
            }
            builder.append(*c);
678 679 680 681 682 683 684
            k++;
        }        
    } else {
        const UChar* characters = str.characters16();

        while (k < len) {
            const UChar* c = characters + k;
685
            UChar convertedUChar;
686 687
            if (c[0] == '%' && k <= len - 6 && c[1] == 'u') {
                if (isASCIIHexDigit(c[2]) && isASCIIHexDigit(c[3]) && isASCIIHexDigit(c[4]) && isASCIIHexDigit(c[5])) {
688 689
                    convertedUChar = Lexer<UChar>::convertUnicode(c[2], c[3], c[4], c[5]);
                    c = &convertedUChar;
690 691 692
                    k += 5;
                }
            } else if (c[0] == '%' && k <= len - 3 && isASCIIHexDigit(c[1]) && isASCIIHexDigit(c[2])) {
693 694
                convertedUChar = UChar(Lexer<UChar>::convertHex(c[1], c[2]));
                c = &convertedUChar;
695
                k += 2;
weinig@apple.com's avatar
weinig@apple.com committed
696
            }
697 698
            k++;
            builder.append(*c);
weinig@apple.com's avatar
weinig@apple.com committed
699 700 701
        }
    }

702
    return JSValue::encode(jsString(exec, builder.toString()));
weinig@apple.com's avatar
weinig@apple.com committed
703 704
}

705 706 707 708 709
EncodedJSValue JSC_HOST_CALL globalFuncThrowTypeError(ExecState* exec)
{
    return throwVMTypeError(exec);
}

710 711 712 713 714 715 716 717 718 719 720
class GlobalFuncProtoGetterFunctor {
public:
    GlobalFuncProtoGetterFunctor(JSObject* thisObject)
        : m_hasSkippedFirstFrame(false)
        , m_thisObject(thisObject)
        , m_result(JSValue::encode(jsUndefined()))
    {
    }

    EncodedJSValue result() { return m_result; }

721
    StackVisitor::Status operator()(StackVisitor& visitor)
722 723 724
    {
        if (!m_hasSkippedFirstFrame) {
            m_hasSkippedFirstFrame = true;
725
            return StackVisitor::Continue;
726 727
        }

728
        if (m_thisObject->allowsAccessFrom(visitor->callFrame()))
729 730
            m_result = JSValue::encode(m_thisObject->prototype());

731
        return StackVisitor::Done;
732 733 734 735 736 737 738 739
    }

private:
    bool m_hasSkippedFirstFrame;
    JSObject* m_thisObject;
    EncodedJSValue m_result;
};

740 741
EncodedJSValue JSC_HOST_CALL globalFuncProtoGetter(ExecState* exec)
{
742 743 744
    JSObject* thisObject = jsDynamicCast<JSObject*>(exec->thisValue().toThis(exec, NotStrictMode));

    if (!thisObject)
745 746
        return JSValue::encode(exec->thisValue().synthesizePrototype(exec));

747
    GlobalFuncProtoGetterFunctor functor(thisObject);
748
    exec->iterate(functor);
749
    return functor.result();
750 751
}

752 753 754 755 756 757 758 759 760 761 762
class GlobalFuncProtoSetterFunctor {
public:
    GlobalFuncProtoSetterFunctor(JSObject* thisObject)
        : m_hasSkippedFirstFrame(false)
        , m_allowsAccess(false)
        , m_thisObject(thisObject)
    {
    }

    bool allowsAccess() const { return m_allowsAccess; }

763
    StackVisitor::Status operator()(StackVisitor& visitor)
764 765 766
    {
        if (!m_hasSkippedFirstFrame) {
            m_hasSkippedFirstFrame = true;
767
            return StackVisitor::Continue;
768 769
        }

770 771
        m_allowsAccess = m_thisObject->allowsAccessFrom(visitor->callFrame());
        return StackVisitor::Done;
772 773 774 775 776 777 778 779
    }

private:
    bool m_hasSkippedFirstFrame;
    bool m_allowsAccess;
    JSObject* m_thisObject;
};

780 781 782 783
EncodedJSValue JSC_HOST_CALL globalFuncProtoSetter(ExecState* exec)
{
    JSValue value = exec->argument(0);

784 785
    JSObject* thisObject = jsDynamicCast<JSObject*>(exec->thisValue().toThis(exec, NotStrictMode));

786
    // Setting __proto__ of a primitive should have no effect.
787
    if (!thisObject)
788 789
        return JSValue::encode(jsUndefined());

790
    GlobalFuncProtoSetterFunctor functor(thisObject);
791
    exec->iterate(functor);
792
    if (!functor.allowsAccess())
793 794 795 796 797 798 799 800 801
        return JSValue::encode(jsUndefined());

    // Setting __proto__ to a non-object, non-null value is silently ignored to match Mozilla.
    if (!value.isObject() && !value.isNull())
        return JSValue::encode(jsUndefined());

    if (!thisObject->isExtensible())
        return throwVMError(exec, createTypeError(exec, StrictModeReadonlyPropertyWriteError));

802
    if (!thisObject->setPrototypeWithCycleCheck(exec, value))
803
        exec->vm().throwException(exec, createError(exec, "cyclic __proto__ value"));
804 805 806
    return JSValue::encode(jsUndefined());
}

807
} // namespace JSC