bool _NPN_Invoke(NPP npp, NPObject* o, NPIdentifier methodName, const NPVariant* args, uint32_t argCount, NPVariant* result) { if (o->_class == NPScriptObjectClass) { JavaScriptObject* obj = (JavaScriptObject*)o; if (!_isSafeScript(obj)) return false; PrivateIdentifier* i = (PrivateIdentifier*)methodName; if (!i->isString) return false; // Special case the "eval" method. if (methodName == _NPN_GetStringIdentifier("eval")) { if (argCount != 1) return false; if (args[0].type != NPVariantType_String) return false; return _NPN_Evaluate(npp, o, (NPString *)&args[0].value.stringValue, result); } // Lookup the function object. RootObject* rootObject = obj->rootObject; if (!rootObject || !rootObject->isValid()) return false; ExecState* exec = rootObject->interpreter()->globalExec(); JSLock lock; JSValue* func = obj->imp->get(exec, identifierFromNPIdentifier(i->value.string)); if (func->isNull()) { NULL_TO_NPVARIANT(*result); return false; } if (func->isUndefined()) { VOID_TO_NPVARIANT(*result); return false; } // Call the function object. JSObject *funcImp = static_cast<JSObject*>(func); JSObject *thisObj = const_cast<JSObject*>(obj->imp); List argList = listFromVariantArgs(exec, args, argCount, rootObject); rootObject->interpreter()->startTimeoutCheck(); JSValue *resultV = funcImp->call (exec, thisObj, argList); rootObject->interpreter()->stopTimeoutCheck(); // Convert and return the result of the function call. convertValueToNPVariant(exec, resultV, result); return true; } if (o->_class->invoke) return o->_class->invoke(o, methodName, args, argCount, result); VOID_TO_NPVARIANT(*result); return true; }
static ALWAYS_INLINE JSValue *tryGetAndCallProperty(ExecState *exec, const JSObject *object, const Identifier &propertyName) { JSValue *v = object->get(exec, propertyName); if (v->isObject()) { JSObject *o = static_cast<JSObject*>(v); if (o->implementsCall()) { // spec says "not primitive type" but ... JSObject *thisObj = const_cast<JSObject*>(object); JSValue *def = o->call(exec, thisObj, List::empty()); JSType defType = def->type(); ASSERT(defType != GetterSetterType); if (defType != ObjectType) return def; } } return NULL; }
JSValue* WebScriptCallFrame::valueByEvaluatingJavaScriptFromString(String script) { #if 0 ExecState* state = m_state; JSGlobalObject* globObj = state->dynamicGlobalObject(); // find "eval" JSObject* eval = 0; if (state->scopeNode()) { // "eval" won't work without context (i.e. at global scope) JSValue* v = globObj->get(state, "eval"); if (v->isObject() && static_cast<JSObject*>(v)->implementsCall()) eval = static_cast<JSObject*>(v); else // no "eval" - fallback operates on global exec state state = globObj->globalExec(); } JSValue* savedException = state->exception(); state->clearException(); UString code(script.utf8().data()); // evaluate JSValue* scriptExecutionResult; if (eval) { List args; args.append(jsString(code)); scriptExecutionResult = eval->call(state, 0, args); } else // no "eval", or no context (i.e. global scope) - use global fallback scriptExecutionResult = Interpreter::evaluate(state, UString(), 0, code.data(), code.size(), globObj).value(); if (state->hadException()) scriptExecutionResult = state->exception(); // (may be redundant depending on which eval path was used) state->setException(savedException); return scriptExecutionResult; #else return jsNull(); #endif }
JSValue* JSHTMLDocument::open(ExecState* exec, const List& args) { // For compatibility with other browsers, pass open calls with more than 2 parameters to the window. if (args.size() > 2) { Frame* frame = static_cast<HTMLDocument*>(impl())->frame(); if (frame) { Window* window = Window::retrieveWindow(frame); if (window) { JSObject* functionObject = window->get(exec, "open")->getObject(); if (!functionObject || !functionObject->implementsCall()) return throwError(exec, TypeError); return functionObject->call(exec, window, args); } } return jsUndefined(); } // In the case of two parameters or fewer, do a normal document open. static_cast<HTMLDocument*>(impl())->open(); return jsUndefined(); }
bool _NPN_InvokeDefault(NPP, NPObject* o, const NPVariant* args, uint32_t argCount, NPVariant* result) { if (o->_class == NPScriptObjectClass) { JavaScriptObject* obj = (JavaScriptObject*)o; if (!_isSafeScript(obj)) return false; VOID_TO_NPVARIANT(*result); // Lookup the function object. RootObject* rootObject = obj->rootObject; if (!rootObject || !rootObject->isValid()) return false; ExecState* exec = rootObject->interpreter()->globalExec(); JSLock lock; // Call the function object. JSObject *funcImp = static_cast<JSObject*>(obj->imp); if (!funcImp->implementsCall()) return false; List argList = listFromVariantArgs(exec, args, argCount, rootObject); rootObject->interpreter()->startTimeoutCheck(); JSValue *resultV = funcImp->call (exec, funcImp, argList); rootObject->interpreter()->stopTimeoutCheck(); // Convert and return the result of the function call. convertValueToNPVariant(exec, resultV, result); return true; } if (o->_class->invokeDefault) return o->_class->invokeDefault(o, args, argCount, result); VOID_TO_NPVARIANT(*result); return true; }
EXPORT JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { JSLock lock; ExecState* exec = toJS(ctx); JSObject* jsObject = toJS(object); JSObject* jsThisObject = toJS(thisObject); if (!jsThisObject) jsThisObject = exec->dynamicInterpreter()->globalObject(); List argList; for (size_t i = 0; i < argumentCount; i++) argList.append(toJS(arguments[i])); JSValueRef result = toRef(jsObject->call(exec, jsThisObject, argList)); // returns NULL if object->implementsCall() is false if (exec->hadException()) { if (exception) *exception = toRef(exec->exception()); exec->clearException(); result = 0; } return result; }
// ECMA 8.6.2.2 void JSObject::put(ExecState *exec, const Identifier &propertyName, JSValue *value, int attr) { assert(value); // non-standard netscape extension if (propertyName == exec->propertyNames().underscoreProto) { JSObject* proto = value->getObject(); while (proto) { if (proto == this) { throwError(exec, GeneralError, "cyclic __proto__ value"); return; } proto = proto->prototype() ? proto->prototype()->getObject() : 0; } setPrototype(value); return; } // putValue() is used for JS assignemnts. It passes no attribute. // Assume that a C++ implementation knows what it is doing // and don't spend time doing a read-only check for it. bool checkRO = (attr == None || attr == DontDelete); if (checkRO) { // Check for static properties that are ReadOnly; the property map will check the dynamic properties. // We don't have to worry about setters being read-only as they can't be added with such an attribute. // We also need to inherit any attributes we have from the entry const HashEntry* entry = findPropertyHashEntry(propertyName); if (entry) { if (entry->attr & ReadOnly) { #ifdef KJS_VERBOSE fprintf( stderr, "WARNING: static property %s is ReadOnly\n", propertyName.ascii() ); #endif return; } attr = entry->attr; } } // Check if there are any setters or getters in the prototype chain JSObject *obj = this; bool hasGettersOrSetters = false; while (true) { if (obj->_prop.hasGetterSetterProperties()) { hasGettersOrSetters = true; break; } if (!obj->_proto->isObject()) break; obj = static_cast<JSObject *>(obj->_proto); } if (hasGettersOrSetters) { obj = this; while (true) { unsigned attributes; if (JSValue *gs = obj->_prop.get(propertyName, attributes)) { if (attributes & GetterSetter) { JSObject *setterFunc = static_cast<GetterSetterImp *>(gs)->getSetter(); if (!setterFunc) { throwSetterError(exec); return; } List args; args.append(value); setterFunc->call(exec, this, args); return; } else { // If there's an existing property on the object or one of its // prototype it should be replaced, so we just break here. break; } } if (!obj->_proto->isObject()) break; obj = static_cast<JSObject *>(obj->_proto); } } _prop.put(propertyName,value,attr,checkRO); }
JSValue *FunctionProtoFunc::callAsFunction(ExecState *exec, JSObject *thisObj, const List &args) { JSValue *result = NULL; switch (id) { case ToString: if (!thisObj || !thisObj->inherits(&InternalFunctionImp::info)) { #ifndef NDEBUG fprintf(stderr, "attempted toString() call on null or non-function object\n"); #endif return throwError(exec, TypeError); } if (thisObj->inherits(&FunctionImp::info)) { return jsString(static_cast<FunctionImp *>(thisObj)->toSource()); } else if (thisObj->inherits(&InternalFunctionImp::info) && !static_cast<InternalFunctionImp *>(thisObj)->functionName().isNull()) { result = jsString("\nfunction " + static_cast<InternalFunctionImp *>(thisObj)->functionName().ustring() + "() {\n" " [native code]\n}\n"); } else { result = jsString("[function]"); } break; case Apply: { JSValue *thisArg = args[0]; JSValue *argArray = args[1]; JSObject *func = thisObj; if (!func->implementsCall()) { return throwError(exec, TypeError); } JSObject *applyThis; if (thisArg->isUndefinedOrNull()) { applyThis = exec->dynamicInterpreter()->globalObject(); } else { applyThis = thisArg->toObject(exec); } List applyArgs; if (!argArray->isUndefinedOrNull()) { if (argArray->isObject() && (static_cast<JSObject *>(argArray)->inherits(&ArrayInstance::info) || static_cast<JSObject *>(argArray)->inherits(&Arguments::info))) { JSObject *argArrayObj = static_cast<JSObject *>(argArray); unsigned int length = argArrayObj->get(exec, exec->propertyNames().length)->toUInt32(exec); for (unsigned int i = 0; i < length; i++) { applyArgs.append(argArrayObj->get(exec, i)); } } else { return throwError(exec, TypeError); } } result = func->call(exec, applyThis, applyArgs); } break; case Call: { JSValue *thisArg = args[0]; JSObject *func = thisObj; if (!func->implementsCall()) { return throwError(exec, TypeError); } JSObject *callThis; if (thisArg->isUndefinedOrNull()) { callThis = exec->dynamicInterpreter()->globalObject(); } else { callThis = thisArg->toObject(exec); } result = func->call(exec, callThis, args.copyTail()); } break; case Bind: { //ECMA Edition 5.1r6 - 15.3.4.5 JSObject *target(thisObj); if (!target->implementsCall()) { return throwError(exec, TypeError, "object is not callable"); } List newArgs; for (int i = 1; i < args.size(); ++i) { newArgs.append(args[i]); } JSObject *boundThis = 0; // As call does not accept JSValue(undefined/null), // do it like in call and use the global object if (args[0]->isUndefinedOrNull()) { boundThis = exec->dynamicInterpreter()->globalObject(); } else { boundThis = args[0]->toObject(exec); } BoundFunction *bfunc = new BoundFunction(exec, target, boundThis, newArgs); unsigned length; if (target->inherits(&FunctionImp::info)) { double L = target->get(exec, exec->propertyNames().length)->getNumber() - newArgs.size(); length = (unsigned)std::max<int>((int)L, 0); } else { length = 0; } bfunc->put(exec, exec->propertyNames().length, jsNumber(length), ReadOnly | DontEnum | DontDelete); JSObject *thrower = new Thrower(TypeError); PropertyDescriptor callerDesc; GetterSetterImp *gs = new GetterSetterImp(); gs->setGetter(thrower); gs->setSetter(thrower); callerDesc.setPropertyDescriptorValues(exec, gs, DontEnum | DontDelete); bfunc->defineOwnProperty(exec, exec->propertyNames().caller, callerDesc, false); PropertyDescriptor argumentsDesc; argumentsDesc.setPropertyDescriptorValues(exec, gs, DontEnum | DontDelete); bfunc->defineOwnProperty(exec, exec->propertyNames().arguments, argumentsDesc, false); return bfunc; } break; } return result; }
// ECMA 8.6.2.2 EXPORT void JSObject::put(ExecState* exec, const Identifier &propertyName, JSValue *value, int attr) { assert(value); // non-standard netscape extension if (propertyName == exec->propertyNames().underscoreProto) { JSObject* proto = value->getObject(); while (proto) { if (proto == this) throwError(exec, GeneralError, "cyclic __proto__ value"); proto = proto->prototype() ? proto->prototype()->getObject() : 0; } setPrototype(value); return; } /* TODO: check for write permissions directly w/o this call */ /* Doesn't look very easy with the PropertyMap API - David */ // putValue() is used for JS assignemnts. It passes no attribute. // Assume that a C++ implementation knows what it is doing // and let it override the canPut() check. if ((attr == None || attr == DontDelete) && !canPut(exec,propertyName)) { #ifdef KJS_VERBOSE fprintf( stderr, "WARNING: canPut %s said NO\n", propertyName.ascii() ); #endif return; } // Check if there are any setters or getters in the prototype chain JSObject *obj = this; bool hasGettersOrSetters = false; while (true) { if (obj->_prop.hasGetterSetterProperties()) { hasGettersOrSetters = true; break; } if (!obj->_proto->isObject()) break; obj = static_cast<JSObject *>(obj->_proto); } if (hasGettersOrSetters) { obj = this; while (true) { unsigned attributes; if (JSValue *gs = obj->_prop.get(propertyName, attributes)) { if (attributes & GetterSetter) { JSObject *setterFunc = static_cast<GetterSetterImp *>(gs)->getSetter(); if (!setterFunc) { throwSetterError(exec); return; } List args; args.append(value); setterFunc->call(exec, this, args); return; } else { // If there's an existing property on the object or one of its // prototype it should be replaced, so we just break here. break; } } if (!obj->_proto->isObject()) break; obj = static_cast<JSObject *>(obj->_proto); } } _prop.put(propertyName,value,attr); }
// ECMA 15.4.4 JSValue* ArrayProtoFunc::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args) { unsigned length = thisObj->get(exec, exec->propertyNames().length)->toUInt32(exec); JSValue *result = 0; // work around gcc 4.0 bug in uninitialized variable warning switch (id) { case ToLocaleString: case ToString: if (!thisObj->inherits(&ArrayInstance::info)) return throwError(exec, TypeError); // fall through case Join: { static HashSet<JSObject*> visitedElems; if (visitedElems.contains(thisObj)) return jsString(""); UString separator = ","; UString str = ""; visitedElems.add(thisObj); if (id == Join && !args[0]->isUndefined()) separator = args[0]->toString(exec); for (unsigned int k = 0; k < length; k++) { if (k >= 1) str += separator; if (str.isNull()) { JSObject *error = Error::create(exec, GeneralError, "Out of memory"); exec->setException(error); break; } JSValue* element = thisObj->get(exec, k); if (element->isUndefinedOrNull()) continue; bool fallback = false; if (id == ToLocaleString) { JSObject* o = element->toObject(exec); JSValue* conversionFunction = o->get(exec, exec->propertyNames().toLocaleString); if (conversionFunction->isObject() && static_cast<JSObject*>(conversionFunction)->implementsCall()) str += static_cast<JSObject*>(conversionFunction)->call(exec, o, List())->toString(exec); else // try toString() fallback fallback = true; } if (id == ToString || id == Join || fallback) str += element->toString(exec); if (str.isNull()) { JSObject *error = Error::create(exec, GeneralError, "Out of memory"); exec->setException(error); } if (exec->hadException()) break; } visitedElems.remove(thisObj); result = jsString(str); break; } case Concat: { JSObject *arr = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec,List::empty())); int n = 0; JSValue *curArg = thisObj; JSObject *curObj = static_cast<JSObject *>(thisObj); ListIterator it = args.begin(); for (;;) { if (curArg->isObject() && curObj->inherits(&ArrayInstance::info)) { unsigned int k = 0; // Older versions tried to optimize out getting the length of thisObj // by checking for n != 0, but that doesn't work if thisObj is an empty array. length = curObj->get(exec, exec->propertyNames().length)->toUInt32(exec); while (k < length) { if (JSValue *v = getProperty(exec, curObj, k)) arr->put(exec, n, v); n++; k++; } } else { arr->put(exec, n, curArg); n++; } if (it == args.end()) break; curArg = *it; curObj = static_cast<JSObject *>(it++); // may be 0 } arr->put(exec, exec->propertyNames().length, jsNumber(n), DontEnum | DontDelete); result = arr; break; } case Pop:{ if (length == 0) { thisObj->put(exec, exec->propertyNames().length, jsNumber(length), DontEnum | DontDelete); result = jsUndefined(); } else { result = thisObj->get(exec, length - 1); thisObj->put(exec, exec->propertyNames().length, jsNumber(length - 1), DontEnum | DontDelete); } break; } case Push: { for (int n = 0; n < args.size(); n++) thisObj->put(exec, length + n, args[n]); length += args.size(); thisObj->put(exec, exec->propertyNames().length, jsNumber(length), DontEnum | DontDelete); result = jsNumber(length); break; } case Reverse: { unsigned int middle = length / 2; for (unsigned int k = 0; k < middle; k++) { unsigned lk1 = length - k - 1; JSValue *obj2 = getProperty(exec, thisObj, lk1); JSValue *obj = getProperty(exec, thisObj, k); if (obj2) thisObj->put(exec, k, obj2); else thisObj->deleteProperty(exec, k); if (obj) thisObj->put(exec, lk1, obj); else thisObj->deleteProperty(exec, lk1); } result = thisObj; break; } case Shift: { if (length == 0) { thisObj->put(exec, exec->propertyNames().length, jsNumber(length), DontEnum | DontDelete); result = jsUndefined(); } else { result = thisObj->get(exec, 0); for(unsigned int k = 1; k < length; k++) { if (JSValue *obj = getProperty(exec, thisObj, k)) thisObj->put(exec, k-1, obj); else thisObj->deleteProperty(exec, k-1); } thisObj->deleteProperty(exec, length - 1); thisObj->put(exec, exec->propertyNames().length, jsNumber(length - 1), DontEnum | DontDelete); } break; } case Slice: { // http://developer.netscape.com/docs/manuals/js/client/jsref/array.htm#1193713 or 15.4.4.10 // We return a new array JSObject *resObj = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec,List::empty())); result = resObj; double begin = 0; if (!args[0]->isUndefined()) { begin = args[0]->toInteger(exec); if (begin >= 0) { // false for NaN if (begin > length) begin = length; } else { begin += length; if (!(begin >= 0)) // true for NaN begin = 0; } } double end = length; if (!args[1]->isUndefined()) { end = args[1]->toInteger(exec); if (end < 0) { // false for NaN end += length; if (end < 0) end = 0; } else { if (!(end <= length)) // true for NaN end = length; } } //printf( "Slicing from %d to %d \n", begin, end ); int n = 0; int b = static_cast<int>(begin); int e = static_cast<int>(end); for(int k = b; k < e; k++, n++) { if (JSValue *v = getProperty(exec, thisObj, k)) resObj->put(exec, n, v); } resObj->put(exec, exec->propertyNames().length, jsNumber(n), DontEnum | DontDelete); break; } case Sort:{ #if 0 printf("KJS Array::Sort length=%d\n", length); for ( unsigned int i = 0 ; i<length ; ++i ) printf("KJS Array::Sort: %d: %s\n", i, thisObj->get(exec, i)->toString(exec).ascii() ); #endif JSObject *sortFunction = NULL; if (!args[0]->isUndefined()) { sortFunction = args[0]->toObject(exec); if (!sortFunction->implementsCall()) sortFunction = NULL; } if (thisObj->classInfo() == &ArrayInstance::info) { if (sortFunction) ((ArrayInstance *)thisObj)->sort(exec, sortFunction); else ((ArrayInstance *)thisObj)->sort(exec); result = thisObj; break; } if (length == 0) { thisObj->put(exec, exec->propertyNames().length, jsNumber(0), DontEnum | DontDelete); result = thisObj; break; } // "Min" sort. Not the fastest, but definitely less code than heapsort // or quicksort, and much less swapping than bubblesort/insertionsort. for ( unsigned int i = 0 ; i<length-1 ; ++i ) { JSValue *iObj = thisObj->get(exec,i); unsigned int themin = i; JSValue *minObj = iObj; for ( unsigned int j = i+1 ; j<length ; ++j ) { JSValue *jObj = thisObj->get(exec,j); double cmp; if (jObj->isUndefined()) { cmp = 1; // don't check minObj because there's no need to differentiate == (0) from > (1) } else if (minObj->isUndefined()) { cmp = -1; } else if (sortFunction) { List l; l.append(jObj); l.append(minObj); cmp = sortFunction->call(exec, exec->dynamicInterpreter()->globalObject(), l)->toNumber(exec); } else { cmp = (jObj->toString(exec) < minObj->toString(exec)) ? -1 : 1; } if ( cmp < 0 ) { themin = j; minObj = jObj; } } // Swap themin and i if ( themin > i ) { //printf("KJS Array::Sort: swapping %d and %d\n", i, themin ); thisObj->put( exec, i, minObj ); thisObj->put( exec, themin, iObj ); } } #if 0 printf("KJS Array::Sort -- Resulting array:\n"); for ( unsigned int i = 0 ; i<length ; ++i ) printf("KJS Array::Sort: %d: %s\n", i, thisObj->get(exec, i)->toString(exec).ascii() ); #endif result = thisObj; break; } case Splice: { // 15.4.4.12 - oh boy this is huge JSObject *resObj = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec,List::empty())); result = resObj; int begin = args[0]->toUInt32(exec); if ( begin < 0 ) begin = maxInt( begin + length, 0 ); else begin = minInt( begin, length ); unsigned int deleteCount = minInt( maxInt( args[1]->toUInt32(exec), 0 ), length - begin ); //printf( "Splicing from %d, deleteCount=%d \n", begin, deleteCount ); for(unsigned int k = 0; k < deleteCount; k++) { if (JSValue *v = getProperty(exec, thisObj, k+begin)) resObj->put(exec, k, v); } resObj->put(exec, exec->propertyNames().length, jsNumber(deleteCount), DontEnum | DontDelete); unsigned int additionalArgs = maxInt( args.size() - 2, 0 ); if ( additionalArgs != deleteCount ) { if ( additionalArgs < deleteCount ) { for ( unsigned int k = begin; k < length - deleteCount; ++k ) { if (JSValue *v = getProperty(exec, thisObj, k+deleteCount)) thisObj->put(exec, k+additionalArgs, v); else thisObj->deleteProperty(exec, k+additionalArgs); } for ( unsigned int k = length ; k > length - deleteCount + additionalArgs; --k ) thisObj->deleteProperty(exec, k-1); } else { for ( unsigned int k = length - deleteCount; (int)k > begin; --k ) { if (JSValue *obj = getProperty(exec, thisObj, k + deleteCount - 1)) thisObj->put(exec, k + additionalArgs - 1, obj); else thisObj->deleteProperty(exec, k+additionalArgs-1); } } } for ( unsigned int k = 0; k < additionalArgs; ++k ) { thisObj->put(exec, k+begin, args[k+2]); } thisObj->put(exec, exec->propertyNames().length, jsNumber(length - deleteCount + additionalArgs), DontEnum | DontDelete); break; } case UnShift: { // 15.4.4.13 unsigned int nrArgs = args.size(); for ( unsigned int k = length; k > 0; --k ) { if (JSValue *v = getProperty(exec, thisObj, k - 1)) thisObj->put(exec, k+nrArgs-1, v); else thisObj->deleteProperty(exec, k+nrArgs-1); } for ( unsigned int k = 0; k < nrArgs; ++k ) thisObj->put(exec, k, args[k]); result = jsNumber(length + nrArgs); thisObj->put(exec, exec->propertyNames().length, result, DontEnum | DontDelete); break; } case Filter: case Map: { JSObject *eachFunction = args[0]->toObject(exec); if (!eachFunction->implementsCall()) return throwError(exec, TypeError); JSObject *applyThis = args[1]->isUndefinedOrNull() ? exec->dynamicInterpreter()->globalObject() : args[1]->toObject(exec); JSObject *resultArray; if (id == Filter) resultArray = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec, List::empty())); else { List args; args.append(jsNumber(length)); resultArray = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec, args)); } unsigned filterIndex = 0; for (unsigned k = 0; k < length && !exec->hadException(); ++k) { PropertySlot slot; if (!thisObj->getPropertySlot(exec, k, slot)) continue; JSValue *v = slot.getValue(exec, thisObj, k); List eachArguments; eachArguments.append(v); eachArguments.append(jsNumber(k)); eachArguments.append(thisObj); JSValue *result = eachFunction->call(exec, applyThis, eachArguments); if (id == Map) resultArray->put(exec, k, result); else if (result->toBoolean(exec)) resultArray->put(exec, filterIndex++, v); } return resultArray; } case Every: case ForEach: case Some: { //Documentation for these three is available at: //http://developer-test.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:every //http://developer-test.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:forEach //http://developer-test.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:some JSObject *eachFunction = args[0]->toObject(exec); if (!eachFunction->implementsCall()) return throwError(exec, TypeError); JSObject *applyThis = args[1]->isUndefinedOrNull() ? exec->dynamicInterpreter()->globalObject() : args[1]->toObject(exec); if (id == Some || id == Every) result = jsBoolean(id == Every); else result = jsUndefined(); for (unsigned k = 0; k < length && !exec->hadException(); ++k) { PropertySlot slot; if (!thisObj->getPropertySlot(exec, k, slot)) continue; List eachArguments; eachArguments.append(slot.getValue(exec, thisObj, k)); eachArguments.append(jsNumber(k)); eachArguments.append(thisObj); bool predicateResult = eachFunction->call(exec, applyThis, eachArguments)->toBoolean(exec); if (id == Every && !predicateResult) { result = jsBoolean(false); break; } if (id == Some && predicateResult) { result = jsBoolean(true); break; } } break; } case IndexOf: { // JavaScript 1.5 Extension by Mozilla // Documentation: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf unsigned index = 0; double d = args[1]->toInteger(exec); if (d < 0) d += length; if (d > 0) { if (d > length) index = length; else index = static_cast<unsigned>(d); } JSValue* searchElement = args[0]; for (; index < length; ++index) { JSValue* e = getProperty(exec, thisObj, index); if (!e) continue; if (strictEqual(exec, searchElement, e)) return jsNumber(index); } return jsNumber(-1); } case LastIndexOf: { // JavaScript 1.6 Extension by Mozilla // Documentation: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:lastIndexOf int index = length - 1; double d = args[1]->toInteger(exec); if (d < 0) { d += length; if (d < 0) return jsNumber(-1); } if (d < length) index = static_cast<int>(d); JSValue* searchElement = args[0]; for (; index >= 0; --index) { JSValue* e = getProperty(exec, thisObj, index); if (!e) continue; if (strictEqual(exec, searchElement, e)) return jsNumber(index); } return jsNumber(-1); } default: assert(0); result = 0; break; } return result; }
JSValue* FunctionProtoFunc::callAsFunction(ExecState* exec, JSObject* thisObj, const List &args) { JSValue* result = NULL; switch (id) { case ToString: if (!thisObj || !thisObj->inherits(&InternalFunctionImp::info)) { #ifndef NDEBUG fprintf(stderr,"attempted toString() call on null or non-function object\n"); #endif return throwError(exec, TypeError); } if (thisObj->inherits(&FunctionImp::info)) { return jsString(static_cast<FunctionImp*>(thisObj)->toSource()); } else if (thisObj->inherits(&InternalFunctionImp::info) && !static_cast<InternalFunctionImp*>(thisObj)->functionName().isNull()) { result = jsString("\nfunction " + static_cast<InternalFunctionImp*>(thisObj)->functionName().ustring() + "() {\n" " [native code]\n}\n"); } else { result = jsString("[function]"); } break; case Apply: { JSValue *thisArg = args[0]; JSValue *argArray = args[1]; JSObject *func = thisObj; if (!func->implementsCall()) return throwError(exec, TypeError); JSObject *applyThis; if (thisArg->isUndefinedOrNull()) applyThis = exec->dynamicInterpreter()->globalObject(); else applyThis = thisArg->toObject(exec); List applyArgs; if (!argArray->isUndefinedOrNull()) { if (argArray->isObject() && (static_cast<JSObject *>(argArray)->inherits(&ArrayInstance::info) || static_cast<JSObject *>(argArray)->inherits(&Arguments::info))) { JSObject *argArrayObj = static_cast<JSObject *>(argArray); unsigned int length = argArrayObj->get(exec, exec->propertyNames().length)->toUInt32(exec); for (unsigned int i = 0; i < length; i++) applyArgs.append(argArrayObj->get(exec,i)); } else return throwError(exec, TypeError); } result = func->call(exec,applyThis,applyArgs); } break; case Call: { JSValue *thisArg = args[0]; JSObject *func = thisObj; if (!func->implementsCall()) return throwError(exec, TypeError); JSObject *callThis; if (thisArg->isUndefinedOrNull()) callThis = exec->dynamicInterpreter()->globalObject(); else callThis = thisArg->toObject(exec); result = func->call(exec,callThis,args.copyTail()); } break; } return result; }
void JSAbstractEventListener::handleEvent(Event* ele, bool isWindowEvent) { #ifdef KJS_DEBUGGER if (KJSDebugWin::instance() && KJSDebugWin::instance()->inSession()) return; #endif Event *event = ele; JSObject* listener = listenerObj(); if (!listener) return; Window* window = windowObj(); Frame *frame = window->frame(); if (!frame) return; KJSProxy* proxy = frame->jScript(); if (!proxy) return; JSLock lock; ScriptInterpreter* interpreter = proxy->interpreter(); ExecState* exec = interpreter->globalExec(); JSValue* handleEventFuncValue = listener->get(exec, "handleEvent"); JSObject* handleEventFunc = 0; if (handleEventFuncValue->isObject()) { handleEventFunc = static_cast<JSObject*>(handleEventFuncValue); if (!handleEventFunc->implementsCall()) handleEventFunc = 0; } if (handleEventFunc || listener->implementsCall()) { ref(); List args; args.append(toJS(exec, event)); // Set the event we're handling in the Window object window->setCurrentEvent(event); // ... and in the interpreter interpreter->setCurrentEvent(event); JSValue* retval; if (handleEventFunc) { interpreter->startTimeoutCheck(); retval = handleEventFunc->call(exec, listener, args); } else { JSObject* thisObj; if (isWindowEvent) thisObj = window; else thisObj = static_cast<JSObject*>(toJS(exec, event->currentTarget())); interpreter->startTimeoutCheck(); retval = listener->call(exec, thisObj, args); } interpreter->stopTimeoutCheck(); window->setCurrentEvent(0); interpreter->setCurrentEvent(0); if (exec->hadException()) { JSObject* exception = exec->exception()->toObject(exec); String message = exception->get(exec, messagePropertyName)->toString(exec); int lineNumber = exception->get(exec, "line")->toInt32(exec); String sourceURL = exception->get(exec, "sourceURL")->toString(exec); if (Interpreter::shouldPrintExceptions()) printf("(event handler):%s\n", message.deprecatedString().utf8().data()); frame->addMessageToConsole(message, lineNumber, sourceURL); exec->clearException(); } else { if (!retval->isUndefinedOrNull() && event->storesResultAsString()) event->storeResult(retval->toString(exec)); if (html) { bool retvalbool; if (retval->getBoolean(retvalbool) && !retvalbool) event->preventDefault(); } } Document::updateDocumentsRendering(); deref(); } }