source: webkit/trunk/JavaScriptCore/kjs/object.cpp@ 28777

Last change on this file since 28777 was 28476, checked in by [email protected], 17 years ago

Build fix. Include headers before trying to use the things that they declare.

  • Property svn:eol-style set to native
File size: 18.3 KB
Line 
1// -*- c-basic-offset: 2 -*-
2/*
3 * This file is part of the KDE libraries
4 * Copyright (C) 1999-2001 Harri Porten ([email protected])
5 * Copyright (C) 2001 Peter Kelly ([email protected])
6 * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
7 * Copyright (C) 2007 Eric Seidel ([email protected])
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 "object.h"
28
29#include "date_object.h"
30#include "error_object.h"
31#include "lookup.h"
32#include "nodes.h"
33#include "operations.h"
34#include "PropertyNameArray.h"
35#include <math.h>
36#include <wtf/Assertions.h>
37
38// maximum global call stack size. Protects against accidental or
39// malicious infinite recursions. Define to -1 if you want no limit.
40// In real-world testing it appears ok to bump the stack depth count to 500.
41// This of course is dependent on stack frame size.
42#define KJS_MAX_STACK 500
43
44#define JAVASCRIPT_CALL_TRACING 0
45#define JAVASCRIPT_MARK_TRACING 0
46
47#if JAVASCRIPT_CALL_TRACING
48static bool _traceJavaScript = false;
49
50extern "C" {
51 void setTraceJavaScript(bool f)
52 {
53 _traceJavaScript = f;
54 }
55
56 static bool traceJavaScript()
57 {
58 return _traceJavaScript;
59 }
60}
61#endif
62
63namespace KJS {
64
65// ------------------------------ Object ---------------------------------------
66
67JSValue *JSObject::call(ExecState *exec, JSObject *thisObj, const List &args)
68{
69 ASSERT(implementsCall());
70
71#if KJS_MAX_STACK > 0
72 static int depth = 0; // sum of all extant function calls
73
74#if JAVASCRIPT_CALL_TRACING
75 static bool tracing = false;
76 if (traceJavaScript() && !tracing) {
77 tracing = true;
78 for (int i = 0; i < depth; i++)
79 putchar (' ');
80 printf ("*** calling: %s\n", toString(exec).ascii());
81 for (int j = 0; j < args.size(); j++) {
82 for (int i = 0; i < depth; i++)
83 putchar (' ');
84 printf ("*** arg[%d] = %s\n", j, args[j]->toString(exec).ascii());
85 }
86 tracing = false;
87 }
88#endif
89
90 if (++depth > KJS_MAX_STACK) {
91 --depth;
92 return throwError(exec, RangeError, "Maximum call stack size exceeded.");
93 }
94#endif
95
96 JSValue *ret = callAsFunction(exec,thisObj,args);
97
98#if KJS_MAX_STACK > 0
99 --depth;
100#endif
101
102#if JAVASCRIPT_CALL_TRACING
103 if (traceJavaScript() && !tracing) {
104 tracing = true;
105 for (int i = 0; i < depth; i++)
106 putchar (' ');
107 printf ("*** returning: %s\n", ret->toString(exec).ascii());
108 tracing = false;
109 }
110#endif
111
112 return ret;
113}
114
115// ------------------------------ JSObject ------------------------------------
116
117void JSObject::mark()
118{
119 JSCell::mark();
120
121#if JAVASCRIPT_MARK_TRACING
122 static int markStackDepth = 0;
123 markStackDepth++;
124 for (int i = 0; i < markStackDepth; i++)
125 putchar('-');
126
127 printf("%s (%p)\n", className().UTF8String().c_str(), this);
128#endif
129
130 JSValue *proto = _proto;
131 if (!proto->marked())
132 proto->mark();
133
134 _prop.mark();
135
136#if JAVASCRIPT_MARK_TRACING
137 markStackDepth--;
138#endif
139}
140
141JSType JSObject::type() const
142{
143 return ObjectType;
144}
145
146const ClassInfo *JSObject::classInfo() const
147{
148 return 0;
149}
150
151UString JSObject::className() const
152{
153 const ClassInfo *ci = classInfo();
154 if ( ci )
155 return ci->className;
156 return "Object";
157}
158
159JSValue *JSObject::get(ExecState *exec, const Identifier &propertyName) const
160{
161 PropertySlot slot;
162
163 if (const_cast<JSObject *>(this)->getPropertySlot(exec, propertyName, slot))
164 return slot.getValue(exec, const_cast<JSObject *>(this), propertyName);
165
166 return jsUndefined();
167}
168
169JSValue *JSObject::get(ExecState *exec, unsigned propertyName) const
170{
171 PropertySlot slot;
172 if (const_cast<JSObject *>(this)->getPropertySlot(exec, propertyName, slot))
173 return slot.getValue(exec, const_cast<JSObject *>(this), propertyName);
174
175 return jsUndefined();
176}
177
178bool JSObject::getPropertySlot(ExecState *exec, unsigned propertyName, PropertySlot& slot)
179{
180 JSObject *imp = this;
181
182 while (true) {
183 if (imp->getOwnPropertySlot(exec, propertyName, slot))
184 return true;
185
186 JSValue *proto = imp->_proto;
187 if (!proto->isObject())
188 break;
189
190 imp = static_cast<JSObject *>(proto);
191 }
192
193 return false;
194}
195
196bool JSObject::getOwnPropertySlot(ExecState *exec, unsigned propertyName, PropertySlot& slot)
197{
198 return getOwnPropertySlot(exec, Identifier::from(propertyName), slot);
199}
200
201static void throwSetterError(ExecState *exec)
202{
203 throwError(exec, TypeError, "setting a property that has only a getter");
204}
205
206// ECMA 8.6.2.2
207void JSObject::put(ExecState* exec, const Identifier &propertyName, JSValue *value, int attr)
208{
209 ASSERT(value);
210
211 // non-standard netscape extension
212 if (propertyName == exec->propertyNames().underscoreProto) {
213 JSObject* proto = value->getObject();
214 while (proto) {
215 if (proto == this)
216 throwError(exec, GeneralError, "cyclic __proto__ value");
217 proto = proto->prototype() ? proto->prototype()->getObject() : 0;
218 }
219
220 setPrototype(value);
221 return;
222 }
223
224 /* TODO: check for write permissions directly w/o this call */
225 /* Doesn't look very easy with the PropertyMap API - David */
226 // putValue() is used for JS assignemnts. It passes no attribute.
227 // Assume that a C++ implementation knows what it is doing
228 // and let it override the canPut() check.
229 if ((attr == None || attr == DontDelete) && !canPut(exec,propertyName)) {
230 return;
231 }
232
233 // Check if there are any setters or getters in the prototype chain
234 JSObject *obj = this;
235 bool hasGettersOrSetters = false;
236 while (true) {
237 if (obj->_prop.hasGetterSetterProperties()) {
238 hasGettersOrSetters = true;
239 break;
240 }
241
242 if (!obj->_proto->isObject())
243 break;
244
245 obj = static_cast<JSObject *>(obj->_proto);
246 }
247
248 if (hasGettersOrSetters) {
249 obj = this;
250 while (true) {
251 unsigned attributes;
252 if (JSValue *gs = obj->_prop.get(propertyName, attributes)) {
253 if (attributes & GetterSetter) {
254 JSObject *setterFunc = static_cast<GetterSetterImp *>(gs)->getSetter();
255
256 if (!setterFunc) {
257 throwSetterError(exec);
258 return;
259 }
260
261 List args;
262 args.append(value);
263
264 setterFunc->call(exec, this, args);
265 return;
266 } else {
267 // If there's an existing property on the object or one of its
268 // prototype it should be replaced, so we just break here.
269 break;
270 }
271 }
272
273 if (!obj->_proto->isObject())
274 break;
275
276 obj = static_cast<JSObject *>(obj->_proto);
277 }
278 }
279
280 _prop.put(propertyName,value,attr);
281}
282
283void JSObject::put(ExecState *exec, unsigned propertyName,
284 JSValue *value, int attr)
285{
286 put(exec, Identifier::from(propertyName), value, attr);
287}
288
289// ECMA 8.6.2.3
290bool JSObject::canPut(ExecState *, const Identifier &propertyName) const
291{
292 unsigned attributes;
293
294 // Don't look in the prototype here. We can always put an override
295 // in the object, even if the prototype has a ReadOnly property.
296
297 if (!getPropertyAttributes(propertyName, attributes))
298 return true;
299 else
300 return !(attributes & ReadOnly);
301}
302
303// ECMA 8.6.2.4
304bool JSObject::hasProperty(ExecState *exec, const Identifier &propertyName) const
305{
306 PropertySlot slot;
307 return const_cast<JSObject *>(this)->getPropertySlot(exec, propertyName, slot);
308}
309
310bool JSObject::hasProperty(ExecState *exec, unsigned propertyName) const
311{
312 PropertySlot slot;
313 return const_cast<JSObject *>(this)->getPropertySlot(exec, propertyName, slot);
314}
315
316// ECMA 8.6.2.5
317bool JSObject::deleteProperty(ExecState* /*exec*/, const Identifier &propertyName)
318{
319 unsigned attributes;
320 JSValue *v = _prop.get(propertyName, attributes);
321 if (v) {
322 if ((attributes & DontDelete))
323 return false;
324 _prop.remove(propertyName);
325 if (attributes & GetterSetter)
326 _prop.setHasGetterSetterProperties(_prop.containsGettersOrSetters());
327 return true;
328 }
329
330 // Look in the static hashtable of properties
331 const HashEntry* entry = findPropertyHashEntry(propertyName);
332 if (entry && entry->attr & DontDelete)
333 return false; // this builtin property can't be deleted
334 return true;
335}
336
337bool JSObject::deleteProperty(ExecState *exec, unsigned propertyName)
338{
339 return deleteProperty(exec, Identifier::from(propertyName));
340}
341
342static ALWAYS_INLINE JSValue *tryGetAndCallProperty(ExecState *exec, const JSObject *object, const Identifier &propertyName) {
343 JSValue *v = object->get(exec, propertyName);
344 if (v->isObject()) {
345 JSObject *o = static_cast<JSObject*>(v);
346 if (o->implementsCall()) { // spec says "not primitive type" but ...
347 JSObject *thisObj = const_cast<JSObject*>(object);
348 JSValue *def = o->call(exec, thisObj, List::empty());
349 JSType defType = def->type();
350 ASSERT(defType != GetterSetterType);
351 if (defType != ObjectType)
352 return def;
353 }
354 }
355 return NULL;
356}
357
358bool JSObject::getPrimitiveNumber(ExecState* exec, double& number, JSValue*& result)
359{
360 result = defaultValue(exec, NumberType);
361 number = result->toNumber(exec);
362 return !result->isString();
363}
364
365// ECMA 8.6.2.6
366JSValue* JSObject::defaultValue(ExecState* exec, JSType hint) const
367{
368 /* Prefer String for Date objects */
369 if ((hint == StringType) || (hint != NumberType && _proto == exec->lexicalGlobalObject()->datePrototype())) {
370 if (JSValue* v = tryGetAndCallProperty(exec, this, exec->propertyNames().toString))
371 return v;
372 if (JSValue* v = tryGetAndCallProperty(exec, this, exec->propertyNames().valueOf))
373 return v;
374 } else {
375 if (JSValue* v = tryGetAndCallProperty(exec, this, exec->propertyNames().valueOf))
376 return v;
377 if (JSValue* v = tryGetAndCallProperty(exec, this, exec->propertyNames().toString))
378 return v;
379 }
380
381 if (exec->hadException())
382 return exec->exception();
383
384 return throwError(exec, TypeError, "No default value");
385}
386
387const HashEntry* JSObject::findPropertyHashEntry(const Identifier& propertyName) const
388{
389 for (const ClassInfo *info = classInfo(); info; info = info->parentClass) {
390 if (const HashTable *propHashTable = info->propHashTable) {
391 if (const HashEntry *e = Lookup::findEntry(propHashTable, propertyName))
392 return e;
393 }
394 }
395 return 0;
396}
397
398void JSObject::defineGetter(ExecState*, const Identifier& propertyName, JSObject* getterFunc)
399{
400 JSValue *o = getDirect(propertyName);
401 GetterSetterImp *gs;
402
403 if (o && o->type() == GetterSetterType) {
404 gs = static_cast<GetterSetterImp *>(o);
405 } else {
406 gs = new GetterSetterImp;
407 putDirect(propertyName, gs, GetterSetter);
408 }
409
410 _prop.setHasGetterSetterProperties(true);
411 gs->setGetter(getterFunc);
412}
413
414void JSObject::defineSetter(ExecState*, const Identifier& propertyName, JSObject* setterFunc)
415{
416 JSValue *o = getDirect(propertyName);
417 GetterSetterImp *gs;
418
419 if (o && o->type() == GetterSetterType) {
420 gs = static_cast<GetterSetterImp *>(o);
421 } else {
422 gs = new GetterSetterImp;
423 putDirect(propertyName, gs, GetterSetter);
424 }
425
426 _prop.setHasGetterSetterProperties(true);
427 gs->setSetter(setterFunc);
428}
429
430bool JSObject::implementsConstruct() const
431{
432 return false;
433}
434
435JSObject* JSObject::construct(ExecState*, const List& /*args*/)
436{
437 ASSERT(false);
438 return NULL;
439}
440
441JSObject* JSObject::construct(ExecState* exec, const List& args, const Identifier& /*functionName*/, const UString& /*sourceURL*/, int /*lineNumber*/)
442{
443 return construct(exec, args);
444}
445
446bool JSObject::implementsCall() const
447{
448 return false;
449}
450
451JSValue *JSObject::callAsFunction(ExecState* /*exec*/, JSObject* /*thisObj*/, const List &/*args*/)
452{
453 ASSERT(false);
454 return NULL;
455}
456
457bool JSObject::implementsHasInstance() const
458{
459 return false;
460}
461
462bool JSObject::hasInstance(ExecState* exec, JSValue* value)
463{
464 JSValue* proto = get(exec, exec->propertyNames().prototype);
465 if (!proto->isObject()) {
466 throwError(exec, TypeError, "intanceof called on an object with an invalid prototype property.");
467 return false;
468 }
469
470 if (!value->isObject())
471 return false;
472
473 JSObject* o = static_cast<JSObject*>(value);
474 while ((o = o->prototype()->getObject())) {
475 if (o == proto)
476 return true;
477 }
478 return false;
479}
480
481bool JSObject::propertyIsEnumerable(ExecState*, const Identifier& propertyName) const
482{
483 unsigned attributes;
484
485 if (!getPropertyAttributes(propertyName, attributes))
486 return false;
487 else
488 return !(attributes & DontEnum);
489}
490
491bool JSObject::getPropertyAttributes(const Identifier& propertyName, unsigned& attributes) const
492{
493 if (_prop.get(propertyName, attributes))
494 return true;
495
496 // Look in the static hashtable of properties
497 const HashEntry* e = findPropertyHashEntry(propertyName);
498 if (e) {
499 attributes = e->attr;
500 return true;
501 }
502
503 return false;
504}
505
506void JSObject::getPropertyNames(ExecState* exec, PropertyNameArray& propertyNames)
507{
508 _prop.getEnumerablePropertyNames(propertyNames);
509
510 // Add properties from the static hashtable of properties
511 const ClassInfo *info = classInfo();
512 while (info) {
513 if (info->propHashTable) {
514 int size = info->propHashTable->size;
515 const HashEntry *e = info->propHashTable->entries;
516 for (int i = 0; i < size; ++i, ++e) {
517 if (e->s && !(e->attr & DontEnum))
518 propertyNames.add(e->s);
519 }
520 }
521 info = info->parentClass;
522 }
523 if (_proto->isObject())
524 static_cast<JSObject*>(_proto)->getPropertyNames(exec, propertyNames);
525}
526
527bool JSObject::toBoolean(ExecState*) const
528{
529 return true;
530}
531
532double JSObject::toNumber(ExecState *exec) const
533{
534 JSValue *prim = toPrimitive(exec,NumberType);
535 if (exec->hadException()) // should be picked up soon in nodes.cpp
536 return 0.0;
537 return prim->toNumber(exec);
538}
539
540UString JSObject::toString(ExecState *exec) const
541{
542 JSValue *prim = toPrimitive(exec,StringType);
543 if (exec->hadException()) // should be picked up soon in nodes.cpp
544 return "";
545 return prim->toString(exec);
546}
547
548JSObject *JSObject::toObject(ExecState*) const
549{
550 return const_cast<JSObject*>(this);
551}
552
553void JSObject::putDirect(const Identifier &propertyName, JSValue *value, int attr)
554{
555 _prop.put(propertyName, value, attr);
556}
557
558void JSObject::putDirect(const Identifier &propertyName, int value, int attr)
559{
560 _prop.put(propertyName, jsNumber(value), attr);
561}
562
563void JSObject::removeDirect(const Identifier &propertyName)
564{
565 _prop.remove(propertyName);
566}
567
568void JSObject::putDirectFunction(InternalFunctionImp* func, int attr)
569{
570 putDirect(func->functionName(), func, attr);
571}
572
573void JSObject::fillGetterPropertySlot(PropertySlot& slot, JSValue **location)
574{
575 GetterSetterImp *gs = static_cast<GetterSetterImp *>(*location);
576 JSObject *getterFunc = gs->getGetter();
577 if (getterFunc)
578 slot.setGetterSlot(this, getterFunc);
579 else
580 slot.setUndefined(this);
581}
582
583// ------------------------------ Error ----------------------------------------
584
585const char * const errorNamesArr[] = {
586 I18N_NOOP("Error"), // GeneralError
587 I18N_NOOP("Evaluation error"), // EvalError
588 I18N_NOOP("Range error"), // RangeError
589 I18N_NOOP("Reference error"), // ReferenceError
590 I18N_NOOP("Syntax error"), // SyntaxError
591 I18N_NOOP("Type error"), // TypeError
592 I18N_NOOP("URI error"), // URIError
593};
594
595const char * const * const Error::errorNames = errorNamesArr;
596
597JSObject *Error::create(ExecState *exec, ErrorType errtype, const UString &message,
598 int lineno, int sourceId, const UString &sourceURL)
599{
600 JSObject *cons;
601 switch (errtype) {
602 case EvalError:
603 cons = exec->lexicalGlobalObject()->evalErrorConstructor();
604 break;
605 case RangeError:
606 cons = exec->lexicalGlobalObject()->rangeErrorConstructor();
607 break;
608 case ReferenceError:
609 cons = exec->lexicalGlobalObject()->referenceErrorConstructor();
610 break;
611 case SyntaxError:
612 cons = exec->lexicalGlobalObject()->syntaxErrorConstructor();
613 break;
614 case TypeError:
615 cons = exec->lexicalGlobalObject()->typeErrorConstructor();
616 break;
617 case URIError:
618 cons = exec->lexicalGlobalObject()->URIErrorConstructor();
619 break;
620 default:
621 cons = exec->lexicalGlobalObject()->errorConstructor();
622 break;
623 }
624
625 List args;
626 if (message.isEmpty())
627 args.append(jsString(errorNames[errtype]));
628 else
629 args.append(jsString(message));
630 JSObject *err = static_cast<JSObject *>(cons->construct(exec,args));
631
632 if (lineno != -1)
633 err->put(exec, "line", jsNumber(lineno));
634 if (sourceId != -1)
635 err->put(exec, "sourceId", jsNumber(sourceId));
636
637 if(!sourceURL.isNull())
638 err->put(exec, "sourceURL", jsString(sourceURL));
639
640 return err;
641
642/*
643#ifndef NDEBUG
644 const char *msg = err->get(messagePropertyName)->toString().value().ascii();
645 if (l >= 0)
646 fprintf(stderr, "KJS: %s at line %d. %s\n", estr, l, msg);
647 else
648 fprintf(stderr, "KJS: %s. %s\n", estr, msg);
649#endif
650
651 return err;
652*/
653}
654
655JSObject *Error::create(ExecState *exec, ErrorType type, const char *message)
656{
657 return create(exec, type, message, -1, -1, NULL);
658}
659
660JSObject *throwError(ExecState *exec, ErrorType type)
661{
662 JSObject *error = Error::create(exec, type, UString(), -1, -1, NULL);
663 exec->setException(error);
664 return error;
665}
666
667JSObject *throwError(ExecState *exec, ErrorType type, const UString &message)
668{
669 JSObject *error = Error::create(exec, type, message, -1, -1, NULL);
670 exec->setException(error);
671 return error;
672}
673
674JSObject *throwError(ExecState *exec, ErrorType type, const char *message)
675{
676 JSObject *error = Error::create(exec, type, message, -1, -1, NULL);
677 exec->setException(error);
678 return error;
679}
680
681JSObject *throwError(ExecState *exec, ErrorType type, const UString &message, int line, int sourceId, const UString &sourceURL)
682{
683 JSObject *error = Error::create(exec, type, message, line, sourceId, sourceURL);
684 exec->setException(error);
685 return error;
686}
687
688} // namespace KJS
Note: See TracBrowser for help on using the repository browser.