1 // -*- c-basic-offset: 2 -*-
3 * Copyright (C) 1999-2002 Harri Porten (porten@kde.org)
4 * Copyright (C) 2001 Peter Kelly (pmk@post.com)
5 * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Cameron Zwarich (cwzwarich@uwaterloo.ca)
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.
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.
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.
31 #include "function_object.h"
33 #include "JSGlobalObject.h"
36 #include "operations.h"
41 #include <wtf/ASCIICType.h>
42 #include <wtf/Assertions.h>
43 #include <wtf/unicode/Unicode.h>
46 using namespace Unicode;
50 // ----------------------------- FunctionImp ----------------------------------
52 const ClassInfo FunctionImp::info = { "Function", &InternalFunctionImp::info, 0, 0 };
54 FunctionImp::FunctionImp(ExecState* exec, const Identifier& name, FunctionBodyNode* b, const ScopeChain& sc)
55 : InternalFunctionImp(static_cast<FunctionPrototype*>(exec->lexicalInterpreter()->builtinFunctionPrototype()), name)
61 void FunctionImp::mark()
63 InternalFunctionImp::mark();
67 JSValue* FunctionImp::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args)
69 JSGlobalObject* globalObj = exec->dynamicInterpreter()->globalObject();
71 // enter a new execution context
72 Context ctx(globalObj, exec->dynamicInterpreter(), thisObj, body.get(),
73 FunctionCode, exec->context(), this, &args);
74 ExecState newExec(exec->dynamicInterpreter(), &ctx);
75 if (exec->hadException())
76 newExec.setException(exec->exception());
77 ctx.setExecState(&newExec);
79 Debugger* dbg = exec->dynamicInterpreter()->debugger();
83 sid = body->sourceId();
84 lineno = body->firstLine();
86 bool cont = dbg->callEvent(&newExec,sid,lineno,this,args);
93 Completion comp = execute(&newExec);
95 // if an exception occured, propogate it back to the previous execution object
96 if (newExec.hadException())
97 comp = Completion(Throw, newExec.exception());
99 // The debugger may have been deallocated by now if the WebFrame
100 // we were running in has been destroyed, so refetch it.
101 // See http://bugs.webkit.org/show_bug.cgi?id=9477
102 dbg = exec->dynamicInterpreter()->debugger();
105 lineno = body->lastLine();
107 if (comp.complType() == Throw)
108 newExec.setException(comp.value());
110 int cont = dbg->returnEvent(&newExec,sid,lineno,this);
113 return jsUndefined();
117 if (comp.complType() == Throw) {
118 exec->setException(comp.value());
121 else if (comp.complType() == ReturnValue)
124 return jsUndefined();
127 JSValue* FunctionImp::argumentsGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot)
129 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
130 Context* context = exec->m_context;
132 if (context->function() == thisObj)
133 return static_cast<ActivationImp*>(context->activationObject())->get(exec, propertyName);
134 context = context->callingContext();
139 JSValue* FunctionImp::callerGetter(ExecState* exec, JSObject*, const Identifier&, const PropertySlot& slot)
141 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
142 Context* context = exec->m_context;
144 if (context->function() == thisObj)
146 context = context->callingContext();
152 Context* callingContext = context->callingContext();
156 FunctionImp* callingFunction = callingContext->function();
157 if (!callingFunction)
160 return callingFunction;
163 JSValue* FunctionImp::lengthGetter(ExecState*, JSObject*, const Identifier&, const PropertySlot& slot)
165 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
166 return jsNumber(thisObj->body->numParams());
169 bool FunctionImp::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
171 // Find the arguments from the closest context.
172 if (propertyName == exec->propertyNames().arguments) {
173 slot.setCustom(this, argumentsGetter);
177 // Compute length of parameters.
178 if (propertyName == exec->propertyNames().length) {
179 slot.setCustom(this, lengthGetter);
183 if (propertyName == exec->propertyNames().caller) {
184 slot.setCustom(this, callerGetter);
188 return InternalFunctionImp::getOwnPropertySlot(exec, propertyName, slot);
191 void FunctionImp::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr)
193 if (propertyName == exec->propertyNames().arguments || propertyName == exec->propertyNames().length)
195 InternalFunctionImp::put(exec, propertyName, value, attr);
198 bool FunctionImp::deleteProperty(ExecState* exec, const Identifier& propertyName)
200 if (propertyName == exec->propertyNames().arguments || propertyName == exec->propertyNames().length)
202 return InternalFunctionImp::deleteProperty(exec, propertyName);
205 /* Returns the parameter name corresponding to the given index. eg:
206 * function f1(x, y, z): getParameterName(0) --> x
208 * If a name appears more than once, only the last index at which
209 * it appears associates with it. eg:
210 * function f2(x, x): getParameterName(0) --> null
212 Identifier FunctionImp::getParameterName(int index)
214 Vector<Identifier>& parameters = body->parameters();
216 if (static_cast<size_t>(index) >= body->numParams())
217 return CommonIdentifiers::shared()->nullIdentifier;
219 Identifier name = parameters[index];
221 // Are there any subsequent parameters with the same name?
222 size_t size = parameters.size();
223 for (size_t i = index + 1; i < size; ++i)
224 if (parameters[i] == name)
225 return CommonIdentifiers::shared()->nullIdentifier;
230 // ECMA 13.2.2 [[Construct]]
231 JSObject* FunctionImp::construct(ExecState* exec, const List& args)
234 JSValue* p = get(exec, exec->propertyNames().prototype);
236 proto = static_cast<JSObject*>(p);
238 proto = exec->lexicalInterpreter()->builtinObjectPrototype();
240 JSObject* obj(new JSObject(proto));
242 JSValue* res = call(exec,obj,args);
245 return static_cast<JSObject*>(res);
250 Completion FunctionImp::execute(ExecState* exec)
252 Completion result = body->execute(exec);
254 if (result.complType() == Throw || result.complType() == ReturnValue)
256 return Completion(Normal, jsUndefined()); // TODO: or ReturnValue ?
259 // ------------------------------ IndexToNameMap ---------------------------------
261 // We map indexes in the arguments array to their corresponding argument names.
262 // Example: function f(x, y, z): arguments[0] = x, so we map 0 to Identifier("x").
264 // Once we have an argument name, we can get and set the argument's value in the
265 // activation object.
267 // We use Identifier::null to indicate that a given argument's value
268 // isn't stored in the activation object.
270 IndexToNameMap::IndexToNameMap(FunctionImp* func, const List& args)
272 _map = new Identifier[args.size()];
273 this->size = args.size();
276 ListIterator iterator = args.begin();
277 for (; iterator != args.end(); i++, iterator++)
278 _map[i] = func->getParameterName(i); // null if there is no corresponding parameter
281 IndexToNameMap::~IndexToNameMap() {
285 bool IndexToNameMap::isMapped(const Identifier& index) const
288 int indexAsNumber = index.toUInt32(&indexIsNumber);
293 if (indexAsNumber >= size)
296 if (_map[indexAsNumber].isNull())
302 void IndexToNameMap::unMap(const Identifier& index)
305 int indexAsNumber = index.toUInt32(&indexIsNumber);
307 ASSERT(indexIsNumber && indexAsNumber < size);
309 _map[indexAsNumber] = CommonIdentifiers::shared()->nullIdentifier;
312 Identifier& IndexToNameMap::operator[](int index)
317 Identifier& IndexToNameMap::operator[](const Identifier& index)
320 int indexAsNumber = index.toUInt32(&indexIsNumber);
322 ASSERT(indexIsNumber && indexAsNumber < size);
324 return (*this)[indexAsNumber];
327 // ------------------------------ Arguments ---------------------------------
329 const ClassInfo Arguments::info = {"Arguments", 0, 0, 0};
332 Arguments::Arguments(ExecState* exec, FunctionImp* func, const List& args, ActivationImp* act)
333 : JSObject(exec->lexicalInterpreter()->builtinObjectPrototype()),
334 _activationObject(act),
335 indexToNameMap(func, args)
337 putDirect(exec->propertyNames().callee, func, DontEnum);
338 putDirect(exec->propertyNames().length, args.size(), DontEnum);
341 ListIterator iterator = args.begin();
342 for (; iterator != args.end(); i++, iterator++) {
343 if (!indexToNameMap.isMapped(Identifier::from(i))) {
344 JSObject::put(exec, Identifier::from(i), *iterator, DontEnum);
349 void Arguments::mark()
352 if (_activationObject && !_activationObject->marked())
353 _activationObject->mark();
356 JSValue* Arguments::mappedIndexGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot)
358 Arguments* thisObj = static_cast<Arguments*>(slot.slotBase());
359 return thisObj->_activationObject->get(exec, thisObj->indexToNameMap[propertyName]);
362 bool Arguments::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
364 if (indexToNameMap.isMapped(propertyName)) {
365 slot.setCustom(this, mappedIndexGetter);
369 return JSObject::getOwnPropertySlot(exec, propertyName, slot);
372 void Arguments::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr)
374 if (indexToNameMap.isMapped(propertyName)) {
375 _activationObject->put(exec, indexToNameMap[propertyName], value, attr);
377 JSObject::put(exec, propertyName, value, attr);
381 bool Arguments::deleteProperty(ExecState* exec, const Identifier& propertyName)
383 if (indexToNameMap.isMapped(propertyName)) {
384 indexToNameMap.unMap(propertyName);
387 return JSObject::deleteProperty(exec, propertyName);
391 // ------------------------------ ActivationImp --------------------------------
393 const ClassInfo ActivationImp::info = {"Activation", 0, 0, 0};
396 ActivationImp::ActivationImp(FunctionImp* function, const List& arguments)
397 : _function(function), _arguments(arguments), _argumentsObject(0)
399 // FIXME: Do we need to support enumerating the arguments property?
402 JSValue* ActivationImp::argumentsGetter(ExecState* exec, JSObject*, const Identifier&, const PropertySlot& slot)
404 ActivationImp* thisObj = static_cast<ActivationImp*>(slot.slotBase());
406 // default: return builtin arguments array
407 if (!thisObj->_argumentsObject)
408 thisObj->createArgumentsObject(exec);
410 return thisObj->_argumentsObject;
413 PropertySlot::GetValueFunc ActivationImp::getArgumentsGetter()
415 return ActivationImp::argumentsGetter;
418 bool ActivationImp::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
420 // do this first so property map arguments property wins over the below
421 // we don't call JSObject because we won't have getter/setter properties
422 // and we don't want to support __proto__
424 if (JSValue** location = getDirectLocation(propertyName)) {
425 slot.setValueSlot(this, location);
429 if (propertyName == exec->propertyNames().arguments) {
430 slot.setCustom(this, getArgumentsGetter());
437 bool ActivationImp::deleteProperty(ExecState* exec, const Identifier& propertyName)
439 if (propertyName == exec->propertyNames().arguments)
441 return JSObject::deleteProperty(exec, propertyName);
444 void ActivationImp::put(ExecState*, const Identifier& propertyName, JSValue* value, int attr)
446 // There's no way that an activation object can have a prototype or getter/setter properties
447 ASSERT(!_prop.hasGetterSetterProperties());
448 ASSERT(prototype() == jsNull());
450 _prop.put(propertyName, value, attr, (attr == None || attr == DontDelete));
453 void ActivationImp::mark()
455 if (_function && !_function->marked())
457 if (_argumentsObject && !_argumentsObject->marked())
458 _argumentsObject->mark();
462 void ActivationImp::createArgumentsObject(ExecState* exec)
464 _argumentsObject = new Arguments(exec, _function, _arguments, const_cast<ActivationImp*>(this));
465 // The arguments list is only needed to create the arguments object, so discard it now
469 // ------------------------------ GlobalFunc -----------------------------------
472 GlobalFuncImp::GlobalFuncImp(ExecState* exec, FunctionPrototype* funcProto, int i, int len, const Identifier& name)
473 : InternalFunctionImp(funcProto, name)
476 putDirect(exec->propertyNames().length, len, DontDelete|ReadOnly|DontEnum);
479 static JSValue* encode(ExecState* exec, const List& args, const char* do_not_escape)
481 UString r = "", s, str = args[0]->toString(exec);
482 CString cstr = str.UTF8String();
483 const char* p = cstr.c_str();
484 for (size_t k = 0; k < cstr.size(); k++, p++) {
486 if (c && strchr(do_not_escape, c)) {
490 sprintf(tmp, "%%%02X", (unsigned char)c);
497 static JSValue* decode(ExecState* exec, const List& args, const char* do_not_unescape, bool strict)
499 UString s = "", str = args[0]->toString(exec);
500 int k = 0, len = str.size();
501 const UChar* d = str.data();
504 const UChar* p = d + k;
508 if (k <= len - 3 && isASCIIHexDigit(p[1].uc) && isASCIIHexDigit(p[2].uc)) {
509 const char b0 = Lexer::convertHex(p[1].uc, p[2].uc);
510 const int sequenceLen = UTF8SequenceLength(b0);
511 if (sequenceLen != 0 && k <= len - sequenceLen * 3) {
512 charLen = sequenceLen * 3;
515 for (int i = 1; i < sequenceLen; ++i) {
516 const UChar* q = p + i * 3;
517 if (q[0] == '%' && isASCIIHexDigit(q[1].uc) && isASCIIHexDigit(q[2].uc))
518 sequence[i] = Lexer::convertHex(q[1].uc, q[2].uc);
525 sequence[sequenceLen] = 0;
526 const int character = decodeUTF8Sequence(sequence);
527 if (character < 0 || character >= 0x110000) {
529 } else if (character >= 0x10000) {
530 // Convert to surrogate pair.
531 s.append(static_cast<unsigned short>(0xD800 | ((character - 0x10000) >> 10)));
532 u = static_cast<unsigned short>(0xDC00 | ((character - 0x10000) & 0x3FF));
534 u = static_cast<unsigned short>(character);
541 return throwError(exec, URIError);
542 // The only case where we don't use "strict" mode is the "unescape" function.
543 // For that, it's good to support the wonky "%u" syntax for compatibility with WinIE.
544 if (k <= len - 6 && p[1] == 'u'
545 && isASCIIHexDigit(p[2].uc) && isASCIIHexDigit(p[3].uc)
546 && isASCIIHexDigit(p[4].uc) && isASCIIHexDigit(p[5].uc)) {
548 u = Lexer::convertUnicode(p[2].uc, p[3].uc, p[4].uc, p[5].uc);
551 if (charLen && (u.uc == 0 || u.uc >= 128 || !strchr(do_not_unescape, u.low()))) {
562 static bool isStrWhiteSpace(unsigned short c)
576 return isSeparatorSpace(c);
580 static int parseDigit(unsigned short c, int radix)
584 if (c >= '0' && c <= '9') {
586 } else if (c >= 'A' && c <= 'Z') {
587 digit = c - 'A' + 10;
588 } else if (c >= 'a' && c <= 'z') {
589 digit = c - 'a' + 10;
597 double parseIntOverflow(const char* s, int length, int radix)
600 double radixMultiplier = 1.0;
602 for (const char* p = s + length - 1; p >= s; p--) {
603 if (radixMultiplier == Inf) {
609 int digit = parseDigit(*p, radix);
610 number += digit * radixMultiplier;
613 radixMultiplier *= radix;
619 static double parseInt(const UString& s, int radix)
621 int length = s.size();
624 while (p < length && isStrWhiteSpace(s[p].uc)) {
632 } else if (s[p] == '-') {
638 if ((radix == 0 || radix == 16) && length - p >= 2 && s[p] == '0' && (s[p + 1] == 'x' || s[p + 1] == 'X')) {
641 } else if (radix == 0) {
642 if (p < length && s[p] == '0')
648 if (radix < 2 || radix > 36)
651 int firstDigitPosition = p;
652 bool sawDigit = false;
655 int digit = parseDigit(s[p].uc, radix);
664 if (number >= mantissaOverflowLowerBound) {
666 number = kjs_strtod(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), 0);
667 else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32)
668 number = parseIntOverflow(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), p - firstDigitPosition, radix);
674 return sign * number;
677 static double parseFloat(const UString& s)
679 // Check for 0x prefix here, because toDouble allows it, but we must treat it as 0.
680 // Need to skip any whitespace and then one + or - sign.
681 int length = s.size();
683 while (p < length && isStrWhiteSpace(s[p].uc)) {
686 if (p < length && (s[p] == '+' || s[p] == '-')) {
689 if (length - p >= 2 && s[p] == '0' && (s[p + 1] == 'x' || s[p + 1] == 'X')) {
693 return s.toDouble( true /*tolerant*/, false /* NaN for empty string */ );
696 JSValue* GlobalFuncImp::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args)
698 JSValue* res = jsUndefined();
700 static const char do_not_escape[] =
701 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
702 "abcdefghijklmnopqrstuvwxyz"
706 static const char do_not_escape_when_encoding_URI_component[] =
707 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
708 "abcdefghijklmnopqrstuvwxyz"
711 static const char do_not_escape_when_encoding_URI[] =
712 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
713 "abcdefghijklmnopqrstuvwxyz"
715 "!#$&'()*+,-./:;=?@_~";
716 static const char do_not_unescape_when_decoding_URI[] =
720 case Eval: { // eval()
721 JSValue* x = args[0];
725 UString s = x->toString(exec);
730 RefPtr<ProgramNode> progNode(Parser::parse(UString(), 0, s.data(),s.size(),&sid,&errLine,&errMsg));
732 Debugger* dbg = exec->dynamicInterpreter()->debugger();
734 bool cont = dbg->sourceParsed(exec, sid, UString(), s, 0, errLine, errMsg);
736 return jsUndefined();
739 // no program node means a syntax occurred
741 return throwError(exec, SyntaxError, errMsg, errLine, sid, NULL);
743 bool switchGlobal = thisObj && thisObj != exec->dynamicInterpreter()->globalObject();
745 // enter a new execution context
746 Interpreter* interpreter = switchGlobal ? static_cast<JSGlobalObject*>(thisObj)->interpreter() : exec->dynamicInterpreter();
747 JSObject* thisVal = static_cast<JSObject*>(exec->context()->thisValue());
748 Context ctx(interpreter->globalObject(),
754 ExecState newExec(interpreter, &ctx);
755 if (exec->hadException())
756 newExec.setException(exec->exception());
757 ctx.setExecState(&newExec);
760 ctx.pushScope(thisObj);
761 ctx.setVariableObject(thisObj);
764 Completion c = progNode->execute(&newExec);
769 // if an exception occured, propogate it back to the previous execution object
770 if (newExec.hadException())
771 exec->setException(newExec.exception());
774 if (c.complType() == Throw)
775 exec->setException(c.value());
776 else if (c.isValueCompletion())
782 res = jsNumber(parseInt(args[0]->toString(exec), args[1]->toInt32(exec)));
785 res = jsNumber(parseFloat(args[0]->toString(exec)));
788 res = jsBoolean(isNaN(args[0]->toNumber(exec)));
791 double n = args[0]->toNumber(exec);
792 res = jsBoolean(!isNaN(n) && !isInf(n));
796 res = decode(exec, args, do_not_unescape_when_decoding_URI, true);
798 case DecodeURIComponent:
799 res = decode(exec, args, "", true);
802 res = encode(exec, args, do_not_escape_when_encoding_URI);
804 case EncodeURIComponent:
805 res = encode(exec, args, do_not_escape_when_encoding_URI_component);
809 UString r = "", s, str = args[0]->toString(exec);
810 const UChar* c = str.data();
811 for (int k = 0; k < str.size(); k++, c++) {
815 sprintf(tmp, "%%u%04X", u);
817 } else if (u != 0 && strchr(do_not_escape, (char)u)) {
821 sprintf(tmp, "%%%02X", u);
831 UString s = "", str = args[0]->toString(exec);
832 int k = 0, len = str.size();
834 const UChar* c = str.data() + k;
836 if (*c == UChar('%') && k <= len - 6 && *(c+1) == UChar('u')) {
837 if (Lexer::isHexDigit((c+2)->uc) && Lexer::isHexDigit((c+3)->uc) &&
838 Lexer::isHexDigit((c+4)->uc) && Lexer::isHexDigit((c+5)->uc)) {
839 u = Lexer::convertUnicode((c+2)->uc, (c+3)->uc,
840 (c+4)->uc, (c+5)->uc);
844 } else if (*c == UChar('%') && k <= len - 3 &&
845 Lexer::isHexDigit((c+1)->uc) && Lexer::isHexDigit((c+2)->uc)) {
846 u = UChar(Lexer::convertHex((c+1)->uc, (c+2)->uc));
858 puts(args[0]->toString(exec).ascii());
866 UString escapeStringForPrettyPrinting(const UString& s)
868 UString escapedString;
870 for (int i = 0; i < s.size(); i++) {
871 unsigned short c = s.data()[i].unicode();
875 escapedString += "\\\"";
878 escapedString += "\\n";
881 escapedString += "\\r";
884 escapedString += "\\t";
887 escapedString += "\\\\";
890 if (c < 128 && isPrintableChar(c))
891 escapedString.append(c);
896 _snprintf(hexValue, 7, "\\u%04x", c);
898 snprintf(hexValue, 7, "\\u%04x", c);
900 escapedString += hexValue;
905 return escapedString;