source: webkit/trunk/JavaScriptCore/kjs/function.cpp@ 29825

Last change on this file since 29825 was 29818, checked in by Darin Adler, 17 years ago

JavaScriptCore:

Reviewed by Oliver.

  • fix <rdar://problem/5657450> REGRESSION: const is broken

Test: fast/js/const.html

SunSpider said this was 0.3% slower. And I saw some Shark samples in
JSGlobalObject::put -- not a lot but a few. We may be able to regain the
speed, but for now we will take that small hit for correctness sake.

  • kjs/JSGlobalObject.cpp: (KJS::JSGlobalObject::put): Pass the checkReadOnly flag in to symbolTablePut instead of passing attributes.
  • kjs/JSVariableObject.h: (KJS::JSVariableObject::symbolTablePut): Removed the code to set attributes here, since we only set attributes when creating a property. Added the code to check read-only here, since we need that to implement const!
  • kjs/function.cpp: (KJS::ActivationImp::put): Pass the checkReadOnly flag in to symbolTablePut instead of passing attributes.
  • kjs/nodes.cpp: (KJS::isConstant): Added. (KJS::PostIncResolveNode::optimizeVariableAccess): Create a PostIncConstNode if optimizing for a local variable and the variable is constant. (KJS::PostDecResolveNode::optimizeVariableAccess): Ditto. But PostDecConstNode. (KJS::PreIncResolveNode::optimizeVariableAccess): Ditto. But PreIncConstNode. (KJS::PreDecResolveNode::optimizeVariableAccess): Ditto. But PreDecConstNode. (KJS::PreIncConstNode::evaluate): Return the value + 1. (KJS::PreDecConstNode::evaluate): Return the value - 1. (KJS::PostIncConstNode::evaluate): Return the value converted to a number. (KJS::PostDecConstNode::evaluate): Ditto. (KJS::ReadModifyResolveNode::optimizeVariableAccess): Create a ReadModifyConstNode if optimizing for a local variable and the variable is constant. (KJS::AssignResolveNode::optimizeVariableAccess): Ditto. But AssignConstNode. (KJS::ScopeNode::optimizeVariableAccess): Pass the local storage to the node optimizeVariableAccess functions, since that's where we need to look to figure out if a variable is constant. (KJS::FunctionBodyNode::processDeclarations): Moved the call to optimizeVariableAccess until after localStorage is set up. (KJS::ProgramNode::processDeclarations): Ditto.
  • kjs/nodes.h: Fixed the IsConstant and HasInitializer values. They are used as flag masks, so a value of 0 will not work for IsConstant. Changed the first parameter to optimizeVariableAccess to be a const reference to a symbol table and added a const reference to local storage. Added classes for const versions of local variable access: PostIncConstNode, PostDecConstNode, PreIncConstNode, PreDecConstNode, ReadModifyConstNode, and AssignConstNode.
  • kjs/object.cpp: (KJS::JSObject::put): Tweaked comments a bit, and changed the checkReadOnly expression to match the form used at the two other call sites.

LayoutTests:

Reviewed by Oliver.

  • tests for <rdar://problem/5657450> REGRESSION: const is broken
  • fast/js/const-expected.txt: Updated with results that express success rather than failure, and to include the many new tests I added.
  • fast/js/kde/const-expected.txt: Ditto.
  • fast/js/resources/const.js: Added many new tests, covering the various cases of const in globals, function locals, the slow case inside eval, the different node types, and the values of the expressions.
  • Property svn:eol-style set to native
File size: 26.1 KB
Line 
1// -*- c-basic-offset: 2 -*-
2/*
3 * Copyright (C) 1999-2002 Harri Porten ([email protected])
4 * Copyright (C) 2001 Peter Kelly ([email protected])
5 * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Cameron Zwarich ([email protected])
7 * Copyright (C) 2007 Maks Orlovich
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
18 *
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
23 *
24 */
25
26#include "config.h"
27#include "function.h"
28
29#include "Activation.h"
30#include "ExecState.h"
31#include "JSGlobalObject.h"
32#include "Parser.h"
33#include "PropertyNameArray.h"
34#include "debugger.h"
35#include "dtoa.h"
36#include "function_object.h"
37#include "internal.h"
38#include "lexer.h"
39#include "nodes.h"
40#include "operations.h"
41#include "scope_chain_mark.h"
42#include <errno.h>
43#include <stdio.h>
44#include <stdlib.h>
45#include <string.h>
46#include <wtf/ASCIICType.h>
47#include <wtf/Assertions.h>
48#include <wtf/MathExtras.h>
49#include <wtf/unicode/UTF8.h>
50
51using namespace WTF;
52using namespace Unicode;
53
54namespace KJS {
55
56// ----------------------------- FunctionImp ----------------------------------
57
58const ClassInfo FunctionImp::info = { "Function", &InternalFunctionImp::info, 0 };
59
60FunctionImp::FunctionImp(ExecState* exec, const Identifier& name, FunctionBodyNode* b, const ScopeChain& sc)
61 : InternalFunctionImp(exec->lexicalGlobalObject()->functionPrototype(), name)
62 , body(b)
63 , _scope(sc)
64{
65}
66
67void FunctionImp::mark()
68{
69 InternalFunctionImp::mark();
70 _scope.mark();
71}
72
73JSValue* FunctionImp::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args)
74{
75 FunctionExecState newExec(exec->dynamicGlobalObject(), thisObj, body.get(), exec, this, args);
76 JSValue* result = body->execute(&newExec);
77 if (newExec.completionType() == Throw) {
78 exec->setException(result);
79 return result;
80 }
81 if (newExec.completionType() == ReturnValue)
82 return result;
83 return jsUndefined();
84}
85
86JSValue* FunctionImp::argumentsGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot)
87{
88 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
89
90 for (ExecState* e = exec; e; e = e->callingExecState())
91 if (e->function() == thisObj) {
92 e->dynamicGlobalObject()->tearOffActivation(e, e != exec);
93 return e->activationObject()->get(exec, propertyName);
94 }
95
96 return jsNull();
97}
98
99JSValue* FunctionImp::callerGetter(ExecState* exec, JSObject*, const Identifier&, const PropertySlot& slot)
100{
101 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
102 ExecState* e = exec;
103 while (e) {
104 if (e->function() == thisObj)
105 break;
106 e = e->callingExecState();
107 }
108
109 if (!e)
110 return jsNull();
111
112 ExecState* callingExecState = e->callingExecState();
113 if (!callingExecState)
114 return jsNull();
115
116 FunctionImp* callingFunction = callingExecState->function();
117 if (!callingFunction)
118 return jsNull();
119
120 return callingFunction;
121}
122
123JSValue* FunctionImp::lengthGetter(ExecState*, JSObject*, const Identifier&, const PropertySlot& slot)
124{
125 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
126 return jsNumber(thisObj->body->parameters().size());
127}
128
129bool FunctionImp::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
130{
131 // Find the arguments from the closest context.
132 if (propertyName == exec->propertyNames().arguments) {
133 slot.setCustom(this, argumentsGetter);
134 return true;
135 }
136
137 // Compute length of parameters.
138 if (propertyName == exec->propertyNames().length) {
139 slot.setCustom(this, lengthGetter);
140 return true;
141 }
142
143 if (propertyName == exec->propertyNames().caller) {
144 slot.setCustom(this, callerGetter);
145 return true;
146 }
147
148 return InternalFunctionImp::getOwnPropertySlot(exec, propertyName, slot);
149}
150
151void FunctionImp::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr)
152{
153 if (propertyName == exec->propertyNames().arguments || propertyName == exec->propertyNames().length)
154 return;
155 InternalFunctionImp::put(exec, propertyName, value, attr);
156}
157
158bool FunctionImp::deleteProperty(ExecState* exec, const Identifier& propertyName)
159{
160 if (propertyName == exec->propertyNames().arguments || propertyName == exec->propertyNames().length)
161 return false;
162 return InternalFunctionImp::deleteProperty(exec, propertyName);
163}
164
165/* Returns the parameter name corresponding to the given index. eg:
166 * function f1(x, y, z): getParameterName(0) --> x
167 *
168 * If a name appears more than once, only the last index at which
169 * it appears associates with it. eg:
170 * function f2(x, x): getParameterName(0) --> null
171 */
172Identifier FunctionImp::getParameterName(int index)
173{
174 Vector<Identifier>& parameters = body->parameters();
175
176 if (static_cast<size_t>(index) >= body->parameters().size())
177 return CommonIdentifiers::shared()->nullIdentifier;
178
179 Identifier name = parameters[index];
180
181 // Are there any subsequent parameters with the same name?
182 size_t size = parameters.size();
183 for (size_t i = index + 1; i < size; ++i)
184 if (parameters[i] == name)
185 return CommonIdentifiers::shared()->nullIdentifier;
186
187 return name;
188}
189
190// ECMA 13.2.2 [[Construct]]
191JSObject* FunctionImp::construct(ExecState* exec, const List& args)
192{
193 JSObject* proto;
194 JSValue* p = get(exec, exec->propertyNames().prototype);
195 if (p->isObject())
196 proto = static_cast<JSObject*>(p);
197 else
198 proto = exec->lexicalGlobalObject()->objectPrototype();
199
200 JSObject* obj(new JSObject(proto));
201
202 JSValue* res = call(exec,obj,args);
203
204 if (res->isObject())
205 return static_cast<JSObject*>(res);
206 else
207 return obj;
208}
209
210// ------------------------------ IndexToNameMap ---------------------------------
211
212// We map indexes in the arguments array to their corresponding argument names.
213// Example: function f(x, y, z): arguments[0] = x, so we map 0 to Identifier("x").
214
215// Once we have an argument name, we can get and set the argument's value in the
216// activation object.
217
218// We use Identifier::null to indicate that a given argument's value
219// isn't stored in the activation object.
220
221IndexToNameMap::IndexToNameMap(FunctionImp* func, const List& args)
222{
223 _map = new Identifier[args.size()];
224 this->size = args.size();
225
226 int i = 0;
227 List::const_iterator end = args.end();
228 for (List::const_iterator it = args.begin(); it != end; ++i, ++it)
229 _map[i] = func->getParameterName(i); // null if there is no corresponding parameter
230}
231
232IndexToNameMap::~IndexToNameMap() {
233 delete [] _map;
234}
235
236bool IndexToNameMap::isMapped(const Identifier& index) const
237{
238 bool indexIsNumber;
239 int indexAsNumber = index.toUInt32(&indexIsNumber);
240
241 if (!indexIsNumber)
242 return false;
243
244 if (indexAsNumber >= size)
245 return false;
246
247 if (_map[indexAsNumber].isNull())
248 return false;
249
250 return true;
251}
252
253void IndexToNameMap::unMap(const Identifier& index)
254{
255 bool indexIsNumber;
256 int indexAsNumber = index.toUInt32(&indexIsNumber);
257
258 ASSERT(indexIsNumber && indexAsNumber < size);
259
260 _map[indexAsNumber] = CommonIdentifiers::shared()->nullIdentifier;
261}
262
263Identifier& IndexToNameMap::operator[](int index)
264{
265 return _map[index];
266}
267
268Identifier& IndexToNameMap::operator[](const Identifier& index)
269{
270 bool indexIsNumber;
271 int indexAsNumber = index.toUInt32(&indexIsNumber);
272
273 ASSERT(indexIsNumber && indexAsNumber < size);
274
275 return (*this)[indexAsNumber];
276}
277
278// ------------------------------ Arguments ---------------------------------
279
280const ClassInfo Arguments::info = { "Arguments", 0, 0 };
281
282// ECMA 10.1.8
283Arguments::Arguments(ExecState* exec, FunctionImp* func, const List& args, ActivationImp* act)
284: JSObject(exec->lexicalGlobalObject()->objectPrototype()),
285_activationObject(act),
286indexToNameMap(func, args)
287{
288 putDirect(exec->propertyNames().callee, func, DontEnum);
289 putDirect(exec->propertyNames().length, args.size(), DontEnum);
290
291 int i = 0;
292 List::const_iterator end = args.end();
293 for (List::const_iterator it = args.begin(); it != end; ++it, ++i) {
294 if (!indexToNameMap.isMapped(Identifier::from(i))) {
295 JSObject::put(exec, Identifier::from(i), *it, DontEnum);
296 }
297 }
298}
299
300void Arguments::mark()
301{
302 JSObject::mark();
303 if (_activationObject && !_activationObject->marked())
304 _activationObject->mark();
305}
306
307JSValue* Arguments::mappedIndexGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot)
308{
309 Arguments* thisObj = static_cast<Arguments*>(slot.slotBase());
310 return thisObj->_activationObject->get(exec, thisObj->indexToNameMap[propertyName]);
311}
312
313bool Arguments::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
314{
315 if (indexToNameMap.isMapped(propertyName)) {
316 slot.setCustom(this, mappedIndexGetter);
317 return true;
318 }
319
320 return JSObject::getOwnPropertySlot(exec, propertyName, slot);
321}
322
323void Arguments::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr)
324{
325 if (indexToNameMap.isMapped(propertyName)) {
326 _activationObject->put(exec, indexToNameMap[propertyName], value, attr);
327 } else {
328 JSObject::put(exec, propertyName, value, attr);
329 }
330}
331
332bool Arguments::deleteProperty(ExecState* exec, const Identifier& propertyName)
333{
334 if (indexToNameMap.isMapped(propertyName)) {
335 indexToNameMap.unMap(propertyName);
336 return true;
337 } else {
338 return JSObject::deleteProperty(exec, propertyName);
339 }
340}
341
342// ------------------------------ ActivationImp --------------------------------
343
344const ClassInfo ActivationImp::info = { "Activation", 0, 0 };
345
346ActivationImp::ActivationImp(const ActivationData& oldData, bool leaveRelic)
347{
348 JSVariableObject::d = new ActivationData(oldData);
349 d()->leftRelic = leaveRelic;
350}
351
352ActivationImp::~ActivationImp()
353{
354 if (!d()->isOnStack)
355 delete d();
356}
357
358void ActivationImp::init(ExecState* exec)
359{
360 d()->symbolTable = &exec->function()->body->symbolTable();
361 d()->exec = exec;
362 d()->function = exec->function();
363 d()->argumentsObject = 0;
364}
365
366JSValue* ActivationImp::argumentsGetter(ExecState* exec, JSObject*, const Identifier&, const PropertySlot& slot)
367{
368 ActivationImp* thisObj = static_cast<ActivationImp*>(slot.slotBase());
369
370 if (!thisObj->d()->argumentsObject)
371 thisObj->createArgumentsObject(exec);
372
373 return thisObj->d()->argumentsObject;
374}
375
376PropertySlot::GetValueFunc ActivationImp::getArgumentsGetter()
377{
378 return ActivationImp::argumentsGetter;
379}
380
381bool ActivationImp::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
382{
383 if (symbolTableGet(propertyName, slot))
384 return true;
385
386 if (JSValue** location = getDirectLocation(propertyName)) {
387 slot.setValueSlot(this, location);
388 return true;
389 }
390
391 // Only return the built-in arguments object if it wasn't overridden above.
392 if (propertyName == exec->propertyNames().arguments) {
393 for (ExecState* e = exec; e; e = e->callingExecState())
394 if (e->function() == d()->function) {
395 e->dynamicGlobalObject()->tearOffActivation(e, e != exec);
396 ActivationImp* newActivation = e->activationObject();
397 slot.setCustom(newActivation, newActivation->getArgumentsGetter());
398 return true;
399 }
400
401 slot.setCustom(this, getArgumentsGetter());
402 return true;
403 }
404
405 // We don't call through to JSObject because there's no way to give an
406 // activation object getter properties or a prototype.
407 ASSERT(!_prop.hasGetterSetterProperties());
408 ASSERT(prototype() == jsNull());
409 return false;
410}
411
412bool ActivationImp::deleteProperty(ExecState* exec, const Identifier& propertyName)
413{
414 if (propertyName == exec->propertyNames().arguments)
415 return false;
416
417 return JSVariableObject::deleteProperty(exec, propertyName);
418}
419
420void ActivationImp::put(ExecState*, const Identifier& propertyName, JSValue* value, int attr)
421{
422 // If any bits other than DontDelete are set, then we bypass the read-only check.
423 bool checkReadOnly = !(attr & ~DontDelete);
424 if (symbolTablePut(propertyName, value, checkReadOnly))
425 return;
426
427 // We don't call through to JSObject because __proto__ and getter/setter
428 // properties are non-standard extensions that other implementations do not
429 // expose in the activation object.
430 ASSERT(!_prop.hasGetterSetterProperties());
431 _prop.put(propertyName, value, attr, checkReadOnly);
432}
433
434void ActivationImp::markChildren()
435{
436 LocalStorage& localStorage = d()->localStorage;
437 size_t size = localStorage.size();
438
439 for (size_t i = 0; i < size; ++i) {
440 JSValue* value = localStorage[i].value;
441
442 if (!value->marked())
443 value->mark();
444 }
445
446 if (!d()->function->marked())
447 d()->function->mark();
448
449 if (d()->argumentsObject && !d()->argumentsObject->marked())
450 d()->argumentsObject->mark();
451}
452
453void ActivationImp::mark()
454{
455 JSObject::mark();
456 markChildren();
457}
458
459void ActivationImp::createArgumentsObject(ExecState* exec)
460{
461 // Since "arguments" is only accessible while a function is being called,
462 // we can retrieve our argument list from the ExecState for our function
463 // call instead of storing the list ourselves.
464 d()->argumentsObject = new Arguments(exec, d()->exec->function(), *d()->exec->arguments(), this);
465}
466
467ActivationImp::ActivationData::ActivationData(const ActivationData& old)
468 : JSVariableObjectData(old)
469 , exec(old.exec)
470 , function(old.function)
471 , argumentsObject(old.argumentsObject)
472 , isOnStack(false)
473{
474}
475
476// ------------------------------ Global Functions -----------------------------------
477
478static JSValue* encode(ExecState* exec, const List& args, const char* do_not_escape)
479{
480 UString r = "", s, str = args[0]->toString(exec);
481 CString cstr = str.UTF8String(true);
482 if (!cstr.c_str())
483 return throwError(exec, URIError, "String contained an illegal UTF-16 sequence.");
484 const char* p = cstr.c_str();
485 for (size_t k = 0; k < cstr.size(); k++, p++) {
486 char c = *p;
487 if (c && strchr(do_not_escape, c)) {
488 r.append(c);
489 } else {
490 char tmp[4];
491 sprintf(tmp, "%%%02X", (unsigned char)c);
492 r += tmp;
493 }
494 }
495 return jsString(r);
496}
497
498static JSValue* decode(ExecState* exec, const List& args, const char* do_not_unescape, bool strict)
499{
500 UString s = "", str = args[0]->toString(exec);
501 int k = 0, len = str.size();
502 const UChar* d = str.data();
503 UChar u;
504 while (k < len) {
505 const UChar* p = d + k;
506 UChar c = *p;
507 if (c == '%') {
508 int charLen = 0;
509 if (k <= len - 3 && isASCIIHexDigit(p[1].uc) && isASCIIHexDigit(p[2].uc)) {
510 const char b0 = Lexer::convertHex(p[1].uc, p[2].uc);
511 const int sequenceLen = UTF8SequenceLength(b0);
512 if (sequenceLen != 0 && k <= len - sequenceLen * 3) {
513 charLen = sequenceLen * 3;
514 char sequence[5];
515 sequence[0] = b0;
516 for (int i = 1; i < sequenceLen; ++i) {
517 const UChar* q = p + i * 3;
518 if (q[0] == '%' && isASCIIHexDigit(q[1].uc) && isASCIIHexDigit(q[2].uc))
519 sequence[i] = Lexer::convertHex(q[1].uc, q[2].uc);
520 else {
521 charLen = 0;
522 break;
523 }
524 }
525 if (charLen != 0) {
526 sequence[sequenceLen] = 0;
527 const int character = decodeUTF8Sequence(sequence);
528 if (character < 0 || character >= 0x110000) {
529 charLen = 0;
530 } else if (character >= 0x10000) {
531 // Convert to surrogate pair.
532 s.append(static_cast<unsigned short>(0xD800 | ((character - 0x10000) >> 10)));
533 u = static_cast<unsigned short>(0xDC00 | ((character - 0x10000) & 0x3FF));
534 } else {
535 u = static_cast<unsigned short>(character);
536 }
537 }
538 }
539 }
540 if (charLen == 0) {
541 if (strict)
542 return throwError(exec, URIError);
543 // The only case where we don't use "strict" mode is the "unescape" function.
544 // For that, it's good to support the wonky "%u" syntax for compatibility with WinIE.
545 if (k <= len - 6 && p[1] == 'u'
546 && isASCIIHexDigit(p[2].uc) && isASCIIHexDigit(p[3].uc)
547 && isASCIIHexDigit(p[4].uc) && isASCIIHexDigit(p[5].uc)) {
548 charLen = 6;
549 u = Lexer::convertUnicode(p[2].uc, p[3].uc, p[4].uc, p[5].uc);
550 }
551 }
552 if (charLen && (u.uc == 0 || u.uc >= 128 || !strchr(do_not_unescape, u.low()))) {
553 c = u;
554 k += charLen - 1;
555 }
556 }
557 k++;
558 s.append(c);
559 }
560 return jsString(s);
561}
562
563static bool isStrWhiteSpace(unsigned short c)
564{
565 switch (c) {
566 case 0x0009:
567 case 0x000A:
568 case 0x000B:
569 case 0x000C:
570 case 0x000D:
571 case 0x0020:
572 case 0x00A0:
573 case 0x2028:
574 case 0x2029:
575 return true;
576 default:
577 return isSeparatorSpace(c);
578 }
579}
580
581static int parseDigit(unsigned short c, int radix)
582{
583 int digit = -1;
584
585 if (c >= '0' && c <= '9') {
586 digit = c - '0';
587 } else if (c >= 'A' && c <= 'Z') {
588 digit = c - 'A' + 10;
589 } else if (c >= 'a' && c <= 'z') {
590 digit = c - 'a' + 10;
591 }
592
593 if (digit >= radix)
594 return -1;
595 return digit;
596}
597
598double parseIntOverflow(const char* s, int length, int radix)
599{
600 double number = 0.0;
601 double radixMultiplier = 1.0;
602
603 for (const char* p = s + length - 1; p >= s; p--) {
604 if (radixMultiplier == Inf) {
605 if (*p != '0') {
606 number = Inf;
607 break;
608 }
609 } else {
610 int digit = parseDigit(*p, radix);
611 number += digit * radixMultiplier;
612 }
613
614 radixMultiplier *= radix;
615 }
616
617 return number;
618}
619
620static double parseInt(const UString& s, int radix)
621{
622 int length = s.size();
623 int p = 0;
624
625 while (p < length && isStrWhiteSpace(s[p].uc)) {
626 ++p;
627 }
628
629 double sign = 1;
630 if (p < length) {
631 if (s[p] == '+') {
632 ++p;
633 } else if (s[p] == '-') {
634 sign = -1;
635 ++p;
636 }
637 }
638
639 if ((radix == 0 || radix == 16) && length - p >= 2 && s[p] == '0' && (s[p + 1] == 'x' || s[p + 1] == 'X')) {
640 radix = 16;
641 p += 2;
642 } else if (radix == 0) {
643 if (p < length && s[p] == '0')
644 radix = 8;
645 else
646 radix = 10;
647 }
648
649 if (radix < 2 || radix > 36)
650 return NaN;
651
652 int firstDigitPosition = p;
653 bool sawDigit = false;
654 double number = 0;
655 while (p < length) {
656 int digit = parseDigit(s[p].uc, radix);
657 if (digit == -1)
658 break;
659 sawDigit = true;
660 number *= radix;
661 number += digit;
662 ++p;
663 }
664
665 if (number >= mantissaOverflowLowerBound) {
666 if (radix == 10)
667 number = kjs_strtod(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), 0);
668 else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32)
669 number = parseIntOverflow(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), p - firstDigitPosition, radix);
670 }
671
672 if (!sawDigit)
673 return NaN;
674
675 return sign * number;
676}
677
678static double parseFloat(const UString& s)
679{
680 // Check for 0x prefix here, because toDouble allows it, but we must treat it as 0.
681 // Need to skip any whitespace and then one + or - sign.
682 int length = s.size();
683 int p = 0;
684 while (p < length && isStrWhiteSpace(s[p].uc)) {
685 ++p;
686 }
687 if (p < length && (s[p] == '+' || s[p] == '-')) {
688 ++p;
689 }
690 if (length - p >= 2 && s[p] == '0' && (s[p + 1] == 'x' || s[p + 1] == 'X')) {
691 return 0;
692 }
693
694 return s.toDouble( true /*tolerant*/, false /* NaN for empty string */ );
695}
696
697JSValue* globalFuncEval(ExecState* exec, JSObject* thisObj, const List& args)
698{
699 JSValue* x = args[0];
700 if (!x->isString())
701 return x;
702
703 UString s = x->toString(exec);
704
705 int sourceId;
706 int errLine;
707 UString errMsg;
708 RefPtr<EvalNode> evalNode = parser().parse<EvalNode>(UString(), 0, s.data(), s.size(), &sourceId, &errLine, &errMsg);
709
710 Debugger* dbg = exec->dynamicGlobalObject()->debugger();
711 if (dbg) {
712 bool cont = dbg->sourceParsed(exec, sourceId, UString(), s, 0, errLine, errMsg);
713 if (!cont)
714 return jsUndefined();
715 }
716
717 // No program node means a syntax occurred
718 if (!evalNode)
719 return throwError(exec, SyntaxError, errMsg, errLine, sourceId, NULL);
720
721 bool switchGlobal = thisObj && thisObj != exec->dynamicGlobalObject() && thisObj->isGlobalObject();
722
723 // enter a new execution context
724 exec->dynamicGlobalObject()->tearOffActivation(exec);
725 JSGlobalObject* globalObject = switchGlobal ? static_cast<JSGlobalObject*>(thisObj) : exec->dynamicGlobalObject();
726 EvalExecState newExec(globalObject, evalNode.get(), exec);
727
728 if (switchGlobal) {
729 newExec.pushScope(thisObj);
730 newExec.setVariableObject(static_cast<JSGlobalObject*>(thisObj));
731 }
732 JSValue* value = evalNode->execute(&newExec);
733 if (switchGlobal)
734 newExec.popScope();
735
736 if (newExec.completionType() == Throw) {
737 exec->setException(value);
738 return value;
739 }
740
741 return value ? value : jsUndefined();
742}
743
744JSValue* globalFuncParseInt(ExecState* exec, JSObject*, const List& args)
745{
746 return jsNumber(parseInt(args[0]->toString(exec), args[1]->toInt32(exec)));
747}
748
749JSValue* globalFuncParseFloat(ExecState* exec, JSObject*, const List& args)
750{
751 return jsNumber(parseFloat(args[0]->toString(exec)));
752}
753
754JSValue* globalFuncIsNaN(ExecState* exec, JSObject*, const List& args)
755{
756 return jsBoolean(isnan(args[0]->toNumber(exec)));
757}
758
759JSValue* globalFuncIsFinite(ExecState* exec, JSObject*, const List& args)
760{
761 double n = args[0]->toNumber(exec);
762 return jsBoolean(!isnan(n) && !isinf(n));
763}
764
765JSValue* globalFuncDecodeURI(ExecState* exec, JSObject*, const List& args)
766{
767 static const char do_not_unescape_when_decoding_URI[] =
768 "#$&+,/:;=?@";
769
770 return decode(exec, args, do_not_unescape_when_decoding_URI, true);
771}
772
773JSValue* globalFuncDecodeURIComponent(ExecState* exec, JSObject*, const List& args)
774{
775 return decode(exec, args, "", true);
776}
777
778JSValue* globalFuncEncodeURI(ExecState* exec, JSObject*, const List& args)
779{
780 static const char do_not_escape_when_encoding_URI[] =
781 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
782 "abcdefghijklmnopqrstuvwxyz"
783 "0123456789"
784 "!#$&'()*+,-./:;=?@_~";
785
786 return encode(exec, args, do_not_escape_when_encoding_URI);
787}
788
789JSValue* globalFuncEncodeURIComponent(ExecState* exec, JSObject*, const List& args)
790{
791 static const char do_not_escape_when_encoding_URI_component[] =
792 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
793 "abcdefghijklmnopqrstuvwxyz"
794 "0123456789"
795 "!'()*-._~";
796
797 return encode(exec, args, do_not_escape_when_encoding_URI_component);
798}
799
800JSValue* globalFuncEscape(ExecState* exec, JSObject*, const List& args)
801{
802 static const char do_not_escape[] =
803 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
804 "abcdefghijklmnopqrstuvwxyz"
805 "0123456789"
806 "*+-./@_";
807
808 UString r = "", s, str = args[0]->toString(exec);
809 const UChar* c = str.data();
810 for (int k = 0; k < str.size(); k++, c++) {
811 int u = c->uc;
812 if (u > 255) {
813 char tmp[7];
814 sprintf(tmp, "%%u%04X", u);
815 s = UString(tmp);
816 } else if (u != 0 && strchr(do_not_escape, (char)u))
817 s = UString(c, 1);
818 else {
819 char tmp[4];
820 sprintf(tmp, "%%%02X", u);
821 s = UString(tmp);
822 }
823 r += s;
824 }
825
826 return jsString(r);
827}
828
829JSValue* globalFuncUnescape(ExecState* exec, JSObject*, const List& args)
830{
831 UString s = "", str = args[0]->toString(exec);
832 int k = 0, len = str.size();
833 while (k < len) {
834 const UChar* c = str.data() + k;
835 UChar u;
836 if (*c == UChar('%') && k <= len - 6 && *(c + 1) == UChar('u')) {
837 if (Lexer::isHexDigit((c + 2)->uc) && Lexer::isHexDigit((c + 3)->uc) && Lexer::isHexDigit((c + 4)->uc) && Lexer::isHexDigit((c + 5)->uc)) {
838 u = Lexer::convertUnicode((c + 2)->uc, (c + 3)->uc, (c + 4)->uc, (c + 5)->uc);
839 c = &u;
840 k += 5;
841 }
842 } else if (*c == UChar('%') && k <= len - 3 && Lexer::isHexDigit((c + 1)->uc) && Lexer::isHexDigit((c + 2)->uc)) {
843 u = UChar(Lexer::convertHex((c+1)->uc, (c+2)->uc));
844 c = &u;
845 k += 2;
846 }
847 k++;
848 s += UString(c, 1);
849 }
850
851 return jsString(s);
852}
853
854#ifndef NDEBUG
855JSValue* globalFuncKJSPrint(ExecState* exec, JSObject*, const List& args)
856{
857 puts(args[0]->toString(exec).ascii());
858 return jsUndefined();
859}
860#endif
861
862// ------------------------------ PrototypeFunction -------------------------------
863
864PrototypeFunction::PrototypeFunction(ExecState* exec, int len, const Identifier& name, JSMemberFunction function)
865 : InternalFunctionImp(exec->lexicalGlobalObject()->functionPrototype(), name)
866 , m_function(function)
867{
868 ASSERT_ARG(function, function);
869 put(exec, exec->propertyNames().length, jsNumber(len), DontDelete | ReadOnly | DontEnum);
870}
871
872PrototypeFunction::PrototypeFunction(ExecState* exec, FunctionPrototype* functionPrototype, int len, const Identifier& name, JSMemberFunction function)
873 : InternalFunctionImp(functionPrototype, name)
874 , m_function(function)
875{
876 ASSERT_ARG(function, function);
877 put(exec, exec->propertyNames().length, jsNumber(len), DontDelete | ReadOnly | DontEnum);
878}
879
880JSValue* PrototypeFunction::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args)
881{
882 return m_function(exec, thisObj, args);
883}
884
885} // namespace KJS
Note: See TracBrowser for help on using the repository browser.