properly compute width of containing block of inline elements
[kdelibs.git] / kjs / function_object.cpp
blob6df63d831a8462bbbc8e999f232eebbbbb501f09
1 // -*- c-basic-offset: 2 -*-
2 // krazy:excludeall=doublequote_chars (UStrings aren't QStrings)
3 /*
4 * This file is part of the KDE libraries
5 * Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
6 * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include "function_object.h"
25 #include <config.h>
26 #include "internal.h"
27 #include "function.h"
28 #include "scriptfunction.h"
29 #include "array_object.h"
30 #include "nodes.h"
31 #include "lexer.h"
32 #include "debugger.h"
33 #include "object.h"
35 #include <assert.h>
36 #include <stdio.h>
37 #include <string.h>
39 using namespace KJS;
41 // ------------------------------ FunctionPrototype -------------------------
43 FunctionPrototype::FunctionPrototype(ExecState *exec)
45 static const Identifier* applyPropertyName = new Identifier("apply");
46 static const Identifier* callPropertyName = new Identifier("call");
48 putDirect(exec->propertyNames().length, jsNumber(0), DontDelete | ReadOnly | DontEnum);
49 putDirectFunction(new FunctionProtoFunc(exec, this, FunctionProtoFunc::ToString, 0, exec->propertyNames().toString), DontEnum);
50 putDirectFunction(new FunctionProtoFunc(exec, this, FunctionProtoFunc::Apply, 2, *applyPropertyName), DontEnum);
51 putDirectFunction(new FunctionProtoFunc(exec, this, FunctionProtoFunc::Call, 1, *callPropertyName), DontEnum);
54 FunctionPrototype::~FunctionPrototype()
58 // ECMA 15.3.4
59 JSValue *FunctionPrototype::callAsFunction(ExecState * /*exec*/, JSObject * /*thisObj*/, const List &/*args*/)
61 return jsUndefined();
64 // ------------------------------ FunctionProtoFunc -------------------------
66 FunctionProtoFunc::FunctionProtoFunc(ExecState* exec, FunctionPrototype* funcProto, int i, int len, const Identifier& name)
67 : InternalFunctionImp(funcProto, name)
68 , id(i)
70 putDirect(exec->propertyNames().length, len, DontDelete | ReadOnly | DontEnum);
73 JSValue* FunctionProtoFunc::callAsFunction(ExecState* exec, JSObject* thisObj, const List &args)
75 JSValue* result = NULL;
77 switch (id) {
78 case ToString:
79 if (!thisObj || !thisObj->inherits(&InternalFunctionImp::info)) {
80 #ifndef NDEBUG
81 fprintf(stderr,"attempted toString() call on null or non-function object\n");
82 #endif
83 return throwError(exec, TypeError);
85 if (thisObj->inherits(&FunctionImp::info)) {
86 return jsString(static_cast<FunctionImp*>(thisObj)->toSource());
87 } else if (thisObj->inherits(&InternalFunctionImp::info) &&
88 !static_cast<InternalFunctionImp*>(thisObj)->functionName().isNull()) {
89 result = jsString("\nfunction " + static_cast<InternalFunctionImp*>(thisObj)->functionName().ustring() + "() {\n"
90 " [native code]\n}\n");
91 } else {
92 result = jsString("[function]");
94 break;
95 case Apply: {
96 JSValue *thisArg = args[0];
97 JSValue *argArray = args[1];
98 JSObject *func = thisObj;
100 if (!func->implementsCall())
101 return throwError(exec, TypeError);
103 JSObject *applyThis;
104 if (thisArg->isUndefinedOrNull())
105 applyThis = exec->dynamicInterpreter()->globalObject();
106 else
107 applyThis = thisArg->toObject(exec);
109 List applyArgs;
110 if (!argArray->isUndefinedOrNull()) {
111 if (argArray->isObject() &&
112 (static_cast<JSObject *>(argArray)->inherits(&ArrayInstance::info) ||
113 static_cast<JSObject *>(argArray)->inherits(&Arguments::info))) {
115 JSObject *argArrayObj = static_cast<JSObject *>(argArray);
116 unsigned int length = argArrayObj->get(exec, exec->propertyNames().length)->toUInt32(exec);
117 for (unsigned int i = 0; i < length; i++)
118 applyArgs.append(argArrayObj->get(exec,i));
120 else
121 return throwError(exec, TypeError);
123 result = func->call(exec,applyThis,applyArgs);
125 break;
126 case Call: {
127 JSValue *thisArg = args[0];
128 JSObject *func = thisObj;
130 if (!func->implementsCall())
131 return throwError(exec, TypeError);
133 JSObject *callThis;
134 if (thisArg->isUndefinedOrNull())
135 callThis = exec->dynamicInterpreter()->globalObject();
136 else
137 callThis = thisArg->toObject(exec);
139 result = func->call(exec,callThis,args.copyTail());
141 break;
144 return result;
147 // ------------------------------ FunctionObjectImp ----------------------------
149 FunctionObjectImp::FunctionObjectImp(ExecState* exec, FunctionPrototype* funcProto)
150 : InternalFunctionImp(funcProto)
152 putDirect(exec->propertyNames().prototype, funcProto, DontEnum|DontDelete|ReadOnly);
154 // no. of arguments for constructor
155 putDirect(exec->propertyNames().length, jsNumber(1), ReadOnly|DontDelete|DontEnum);
158 FunctionObjectImp::~FunctionObjectImp()
162 bool FunctionObjectImp::implementsConstruct() const
164 return true;
167 // ECMA 15.3.2 The Function Constructor
168 JSObject* FunctionObjectImp::construct(ExecState* exec, const List& args, const Identifier& functionName, const UString& sourceURL, int lineNumber)
170 UString p("");
171 UString body;
172 int argsSize = args.size();
173 if (argsSize == 0) {
174 body = "";
175 } else if (argsSize == 1) {
176 body = args[0]->toString(exec);
177 } else {
178 p = args[0]->toString(exec);
179 for (int k = 1; k < argsSize - 1; k++)
180 p += "," + args[k]->toString(exec);
181 body = args[argsSize-1]->toString(exec);
184 // parse the source code
185 int sourceId;
186 int errLine;
187 UString errMsg;
188 RefPtr<FunctionBodyNode> functionBody = parser().parseFunctionBody(sourceURL, lineNumber, body.data(), body.size(), &sourceId, &errLine, &errMsg);
190 // notify debugger that source has been parsed
191 Debugger *dbg = exec->dynamicInterpreter()->debugger();
192 if (dbg) {
193 // make sure to pass in sourceURL, since it's useful for lazy event listeners, and empty for actual function ctor
194 bool cont = dbg->sourceParsed(exec, sourceId, sourceURL, body, lineNumber, errLine, errMsg);
195 if (!cont) {
196 dbg->imp()->abort();
197 return new JSObject();
201 // no program node == syntax error - throw a syntax error
202 if (!functionBody)
203 // we can't return a Completion(Throw) here, so just set the exception
204 // and return it
205 return throwError(exec, SyntaxError, errMsg, errLine, sourceId, sourceURL);
207 ScopeChain scopeChain;
208 scopeChain.push(exec->lexicalInterpreter()->globalObject());
210 FunctionImp* fimp = new FunctionImp(exec, functionName, functionBody.get(), scopeChain);
212 // parse parameter list. throw syntax error on illegal identifiers
213 int len = p.size();
214 const UChar *c = p.data();
215 int i = 0, params = 0;
216 UString param;
217 while (i < len) {
218 while (*c == ' ' && i < len)
219 c++, i++;
220 if (Lexer::isIdentStart(c->uc)) { // else error
221 param = UString(c, 1);
222 c++, i++;
223 while (i < len && (Lexer::isIdentPart(c->uc))) {
224 param += UString(c, 1);
225 c++, i++;
227 while (i < len && *c == ' ')
228 c++, i++;
229 if (i == len) {
230 functionBody->addParam(Identifier(param));
231 params++;
232 break;
233 } else if (*c == ',') {
234 functionBody->addParam(Identifier(param));
235 params++;
236 c++, i++;
237 continue;
238 } // else error
240 return throwError(exec, SyntaxError, "Syntax error in parameter list");
243 List consArgs;
245 JSObject* objCons = exec->lexicalInterpreter()->builtinObject();
246 JSObject* prototype = objCons->construct(exec,List::empty());
247 prototype->put(exec, exec->propertyNames().constructor, fimp, DontEnum|DontDelete|ReadOnly);
248 fimp->put(exec, exec->propertyNames().prototype, prototype, Internal|DontDelete);
249 return fimp;
252 // ECMA 15.3.2 The Function Constructor
253 JSObject* FunctionObjectImp::construct(ExecState* exec, const List& args)
255 return construct(exec, args, "anonymous", UString(), 0);
258 // ECMA 15.3.1 The Function Constructor Called as a Function
259 JSValue* FunctionObjectImp::callAsFunction(ExecState* exec, JSObject* /*thisObj*/, const List &args)
261 return construct(exec, args);