HandleProxy* V8EngineProxy::Call(HandleProxy *subject, const uint16_t *functionName, HandleProxy *_this, uint16_t argCount, HandleProxy** args) { if (_this == nullptr) _this = subject; // (assume the subject is also "this" if not given) auto hThis = _this->Handle(); if (hThis.IsEmpty() || !hThis->IsObject()) throw exception("Call: The target instance handle ('this') does not represent an object."); auto hSubject = subject->Handle(); Handle<Function> hFunc; if (functionName != nullptr) // (if no name is given, assume the subject IS a function object, otherwise get the property as a function) { if (hSubject.IsEmpty() || !hSubject->IsObject()) throw exception("Call: The subject handle does not represent an object."); auto hProp = hSubject.As<Object>()->Get(NewUString(functionName)); if (hProp.IsEmpty() || !hProp->IsFunction()) throw exception("Call: The specified property does not represent a function."); hFunc = hProp.As<Function>(); } else if (hSubject.IsEmpty() || !hSubject->IsFunction()) throw exception("Call: The subject handle does not represent a function."); else hFunc = hSubject.As<Function>(); TryCatch __tryCatch; Handle<Value> result; if (argCount > 0) { Handle<Value>* _args = new Handle<Value>[argCount]; for (auto i = 0; i < argCount; i++) _args[i] = args[i]->Handle(); result = hFunc->Call(hThis.As<Object>(), argCount, _args); delete[] _args; } else result = hFunc->Call(hThis.As<Object>(), 0, nullptr); HandleProxy *returnVal; if (__tryCatch.HasCaught()) { returnVal = GetHandleProxy(GetErrorMessage(__tryCatch)); returnVal->_Type = JSV_ExecutionError; } else returnVal = result.IsEmpty() ? nullptr : GetHandleProxy(result); return returnVal; }
JSValue JSObject::CallAsFunction(const std::vector<JSValue>& arguments, JSObject this_object) { HAL_JSOBJECT_LOCK_GUARD; if (!IsFunction()) { detail::ThrowRuntimeError("JSObject", "This JavaScript object is not a function."); } JSValueRef exception { nullptr }; JSValueRef js_value_ref { nullptr }; if (!arguments.empty()) { const auto arguments_array = detail::to_vector(arguments); js_value_ref = JSObjectCallAsFunction(static_cast<JSContextRef>(js_context__), js_object_ref__, static_cast<JSObjectRef>(this_object), arguments_array.size(), &arguments_array[0], &exception); } else { js_value_ref = JSObjectCallAsFunction(static_cast<JSContextRef>(js_context__), js_object_ref__, static_cast<JSObjectRef>(this_object), 0, nullptr, &exception); } if (exception) { // If this assert fails then we need to JSValueUnprotect // js_value_ref. assert(!js_value_ref); detail::ThrowRuntimeError("JSObject", JSValue(js_context__, exception)); } assert(js_value_ref); return JSValue(js_context__, js_value_ref); }
void ScriptEntity::think( float dt ) { MagnetiteCore::Singleton->runOnMainThread( [&,dt]() { // Perhaps a better (thread safe) mechanism for handling callbacks could be devised. PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext(); Context::Scope scope( ctx ); HandleScope hs; // Get the object prototype, which contains the script-side create. auto proto = mScriptObject->GetPrototype(); if( proto->IsObject() ) { auto protobj = proto.As<Object>(); if( protobj->Has( v8::String::New("think") ) ) { auto createVal = protobj->Get( v8::String::New("think") ); if( createVal->IsFunction() ) { auto createFunc = createVal.As<Function>(); ValueHandle args[] = { Number::New(dt) }; createFunc->Call( mScriptObject, 1, args ); } } } }); BaseEntity::think(dt); }
JResult JObject::Call(JObject& this_, JArgList& arg) { IOTJS_ASSERT(IsFunction()); JRawObjectType* this_obj_p = this_.IsNull() ? NULL : this_.raw_value().v_object; JRawValueType res; JRawValueType* val_args = NULL; uint16_t val_argv = 0; if (arg.GetLength() > 0) { val_argv = arg.GetLength(); val_args = new JRawValueType[val_argv]; for (int i = 0; i < val_argv; ++i) { val_args[i] = arg.Get(i)->raw_value(); } } bool is_ok = jerry_api_call_function(_obj_val.v_object, this_obj_p, &res, val_args, val_argv); if (val_args) { delete [] val_args; } JResultType type = is_ok ? JRESULT_OK : JRESULT_EXCEPTION; return JResult(&res, type); }
AdblockPlus::JsValuePtr AdblockPlus::JsValue::Call(const JsValueList& params, JsValuePtr thisPtr) const { if (!IsFunction()) throw new std::runtime_error("Attempting to call a non-function"); const JsContext context(jsEngine); if (!thisPtr) { v8::Local<v8::Context> localContext = v8::Local<v8::Context>::New(jsEngine->GetIsolate(), *jsEngine->context); thisPtr = JsValuePtr(new JsValue(jsEngine, localContext->Global())); } if (!thisPtr->IsObject()) throw new std::runtime_error("`this` pointer has to be an object"); v8::Local<v8::Object> thisObj = v8::Local<v8::Object>::Cast(thisPtr->UnwrapValue()); std::vector<v8::Handle<v8::Value>> argv; for (JsValueList::const_iterator it = params.begin(); it != params.end(); ++it) argv.push_back((*it)->UnwrapValue()); const v8::TryCatch tryCatch; v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(UnwrapValue()); v8::Local<v8::Value> result = func->Call(thisObj, argv.size(), argv.size() ? &argv.front() : 0); if (tryCatch.HasCaught()) throw JsError(tryCatch.Exception(), tryCatch.Message()); return JsValuePtr(new JsValue(jsEngine, result)); }
CValue CallFunction( CScope& scope, CStack& stack, const CSourceLocation& location, const std::string& symbol, const std::vector<CValue>& argValues) { // Analyze function value. CValue functionValue = scope.GetValue(symbol, location, stack); if (!IsFunction(functionValue)) { throw ExScopeSymbolIsNotFunction{ location, stack }; } if (argValues.size() > functionValue.GetFuncArity()) { throw ExScopeFormalActualArgCountMismatch{ location, stack }; } // Analyze function definition. const auto& functionDef = functionValue.GetFuncDef(); const auto& captures = functionValue.GetFuncCaptures(); auto applArgs = functionValue.GetAppliedArgs(); std::copy(begin(argValues), end(argValues), std::back_inserter(applArgs)); if (argValues.size() < functionValue.GetFuncArity()) { // "Curry on"... return CValue::MakeFunction(&functionDef, captures, applArgs); } // Call function const auto& argNames = functionDef.GetFormalArgs(); const auto& argLocations = functionDef.GetArgLocations(); assert(argNames.size() == argLocations.size()); unsigned argsCount = argNames.size(); CLocalScope funcScope{ scope.GetGlobalScope() }; for (unsigned i = 0; i < argsCount; ++i) { funcScope.TryRegisteringBind( stack, argNames[i], applArgs[i], argLocations[i]); } for (const auto& pr : captures) { funcScope.TryRegisteringBind( stack, pr.first, pr.second.value, pr.second.location); } stack.PushCall(symbol); CValue result = functionDef.Execute(funcScope, stack); stack.PopCall(); return result; }
void CScript::ColorizeScript(Ui::CEdit* edit) { CBotToken* bt; CBotString bs; const char* token; int error, type, cursor1, cursor2; Gfx::FontHighlight color; edit->ClearFormat(); bt = CBotToken::CompileTokens(edit->GetText(), error); while ( bt != 0 ) { bs = bt->GetString(); token = bs; type = bt->GetType(); cursor1 = bt->GetStart(); cursor2 = bt->GetEnd(); color = Gfx::FONT_HIGHLIGHT_NONE; if ( type >= TokenKeyWord && type < TokenKeyWord+100 ) { color = Gfx::FONT_HIGHLIGHT_TOKEN; } if ( type >= TokenKeyDeclare && type < TokenKeyDeclare+100 ) { color = Gfx::FONT_HIGHLIGHT_TYPE; } if ( type >= TokenKeyVal && type < TokenKeyVal+100 ) { color = Gfx::FONT_HIGHLIGHT_CONST; } if ( type == TokenTypVar ) { if ( IsType(token) ) { color = Gfx::FONT_HIGHLIGHT_TYPE; } else if ( IsFunction(token) ) { color = Gfx::FONT_HIGHLIGHT_TOKEN; } } if ( type == TokenTypDef ) { color =Gfx::FONT_HIGHLIGHT_CONST; } if ( cursor1 < cursor2 && color != Gfx::FONT_HIGHLIGHT_NONE ) { edit->SetFormat(cursor1, cursor2, color); } bt = bt->GetNext(); } CBotToken::Delete(bt); }
v8::Handle<v8::Value> create_js_box(const osmium::Box& box) { v8::HandleScope scope; if (!box.valid()) { return scope.Close(v8::Undefined()); } auto cf = module->Get(symbol_Coordinates); assert(cf->IsFunction()); auto bf = module->Get(symbol_Box); assert(bf->IsFunction()); v8::Local<v8::Value> argv_bl[2] = { v8::Number::New(box.bottom_left().lon()), v8::Number::New(box.bottom_left().lat()) }; auto bottom_left = v8::Local<v8::Function>::Cast(cf)->NewInstance(2, argv_bl); v8::Local<v8::Value> argv_tr[2] = { v8::Number::New(box.top_right().lon()), v8::Number::New(box.top_right().lat()) }; auto top_right = v8::Local<v8::Function>::Cast(cf)->NewInstance(2, argv_tr); v8::Local<v8::Value> argv_box[2] = { bottom_left, top_right }; return scope.Close(v8::Local<v8::Function>::Cast(bf)->NewInstance(2, argv_box)); }
JSBool XPCDispInterface::Member::GetValue(XPCCallContext& ccx, XPCNativeInterface * iface, jsval * retval) const { // This is a method or attribute - we'll be needing a function object // We need to use the safe context for this thread because we don't want // to parent the new (and cached forever!) function object to the current // JSContext's global object. That would be bad! if((mType & RESOLVED) == 0) { JSContext* cx = ccx.GetSafeJSContext(); if(!cx) return JS_FALSE; intN argc; JSNative callback; // Is this a function or a parameterized getter/setter if(IsFunction() || IsParameterizedProperty()) { argc = GetParamCount(); callback = XPC_IDispatch_CallMethod; } else { argc = 0; callback = XPC_IDispatch_GetterSetter; } JSFunction *fun = JS_NewFunctionById(cx, callback, argc, 0, nsnull, mName); if(!fun) return JS_FALSE; JSObject* funobj = JS_GetFunctionObject(fun); if(!funobj) return JS_FALSE; // Store ourselves and our native interface within the JSObject if(!JS_SetReservedSlot(ccx, funobj, 0, PRIVATE_TO_JSVAL((void *) this))) return JS_FALSE; if(!JS_SetReservedSlot(ccx, funobj, 1, PRIVATE_TO_JSVAL(iface))) return JS_FALSE; { // scoped lock XPCAutoLock lock(ccx.GetRuntime()->GetMapLock()); const_cast<Member*>(this)->mVal = OBJECT_TO_JSVAL(funobj); const_cast<Member*>(this)->mType |= RESOLVED; } } *retval = mVal; return JS_TRUE; }
v8::Handle<v8::Value> OSMNodeWrap::get_coordinates(v8::Local<v8::String> /* property */, const v8::AccessorInfo& info) { v8::HandleScope scope; auto cf = module->Get(v8::String::NewSymbol("Coordinates")); assert(cf->IsFunction()); const osmium::Location& location = wrapped(info.This()).location(); if (!location) { return scope.Close(v8::Local<v8::Function>::Cast(cf)->NewInstance()); } v8::Local<v8::Value> lon = v8::Number::New(location.lon_without_check()); v8::Local<v8::Value> lat = v8::Number::New(location.lat_without_check()); v8::Local<v8::Value> argv[2] = { lon, lat }; return scope.Close(v8::Local<v8::Function>::Cast(cf)->NewInstance(2, argv)); }
static Expr *CheckNodeForUndefinedFunctions( CgContext *cg, Expr *fExpr, void *arg1, int arg2) { Symbol *lSymb; Expr *lExpr; int *count = (int *) arg1; switch (fExpr->kind) { case DECL_N: case SYMB_N: case CONST_N: case UNARY_N: break; case BINARY_N: if (static_cast< Binary * >( fExpr )->op == FUN_CALL_OP) { lExpr = static_cast< Binary * >( fExpr )->left; if (lExpr->kind == SYMB_N) { lSymb = static_cast< Symb * >( lExpr )->symbol; if (IsFunction(lSymb)) { if (!(lSymb->properties & SYMB_IS_DEFINED)) { SemanticError( cg, cg->pLastSourceLoc, ERROR_S_CALL_UNDEF_FUN, cg->GetString(lSymb->name)); count++; } else { if (lSymb->flags == BEING_CHECKED) { SemanticError( cg, cg->pLastSourceLoc, ERROR_S_RECURSION, cg->GetString(lSymb->name)); count++; } else { CheckFunctionDefinition( cg, NULL, lSymb, 0); } } } } } break; case TRINARY_N: break; default: assert(!"bad kind to CheckNodeForUndefinedFunctions()"); break; } return fExpr; } // CheckNodeForUndefinedFunctions
JBoolean SCCircuitVarList::SetFunction ( const JIndex index, const JFunction& f ) { if (IsFunction(index)) { VarInfo info = itsVars->GetElement(index); delete (info.f); info.f = f.Copy(); itsVars->SetElement(index, info); Broadcast(VarValueChanged(index,1)); return kJTrue; } else { return kJFalse; } }
std::vector<v8::Persistent<v8::Function>>* SMJS_Plugin::GetHooks(char const *type){ std::string typeStd(type); auto it = hooks.find(typeStd); if(it != hooks.end()){ return &it->second; } hooks.insert(std::make_pair(typeStd, std::vector<v8::Persistent<v8::Function>>())); auto vec = GetHooks(type); HandleScope handle_scope(isolate); Context::Scope context_scope(context); auto g = context->Global()->Get(v8::String::New(type)); if(!g.IsEmpty() && g->IsFunction()){ vec->push_back(v8::Persistent<v8::Function>::New(v8::Local<v8::Function>::Cast(g))); } return vec; }
void ScriptEntity::create() { // Perhaps a better (thread safe) mechanism for handling callbacks could be devised. PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext(); Context::Scope scope( ctx ); HandleScope hs; // Get the object prototype, which contains the script-side create. auto proto = mScriptObject->GetPrototype(); if( proto->IsObject() ) { auto protobj = proto.As<Object>(); if( protobj->Has( v8::String::New("create") ) ) { auto createVal = protobj->Get( v8::String::New("create") ); if( createVal->IsFunction() ) { auto createFunc = createVal.As<Function>(); createFunc->Call( mScriptObject, 0, nullptr ); } } } BaseEntity::create(); }
bool TagEntry::IsMethod() const { return IsPrototype() || IsFunction(); }
void CBSymbolList::ReadSymbolList ( istream& input, const CBLanguage lang, const JCharacter* fullName, const JFAID_t fileID ) { JString path, fileName; JSplitPathAndName(fullName, &path, &fileName); input >> ws; while (input.peek() == '!') { JIgnoreLine(input); input >> ws; } JStringPtrMap<JString> flags(JPtrArrayT::kDeleteAll); while (1) { JString* name = new JString; assert( name != NULL ); input >> ws; *name = JReadUntil(input, '\t'); // symbol name if (input.eof() || input.fail()) { delete name; break; } JIgnoreUntil(input, '\t'); // file name JIndex lineIndex; input >> lineIndex; // line index ReadExtensionFlags(input, &flags); JCharacter typeChar = ' '; JString* value; if (flags.GetElement("kind", &value) && !value->IsEmpty()) { typeChar = value->GetFirstCharacter(); } JString* signature = NULL; if (flags.GetElement("signature", &value) && !value->IsEmpty()) { signature = new JString(*value); assert( signature != NULL ); signature->PrependCharacter(' '); } if (IgnoreSymbol(*name)) { delete name; } else { const Type type = DecodeSymbolType(lang, typeChar); if (signature == NULL && (IsFunction(type) || IsPrototype(type))) { signature = new JString(" ( )"); assert( signature != NULL ); } const SymbolInfo info(name, signature, lang, type, kJFalse, fileID, lineIndex); itsSymbolList->InsertSorted(info); // add file:name if (IsFileScope(type)) { JString* name1 = new JString(fileName); assert( name1 != NULL ); *name1 += ":"; *name1 += *name; JString* sig1 = NULL; if (signature != NULL) { sig1 = new JString(*signature); assert( sig1 != NULL ); } const SymbolInfo info1(name1, sig1, lang, type, kJTrue, fileID, lineIndex); itsSymbolList->InsertSorted(info1); } } } }
JBoolean CBSymbolList::FindSymbol ( const JCharacter* name, const JFAID_t contextFileID, const JString& contextNamespace, const CBLanguage contextLang, JPtrArray<JString>* cContextNamespaceList, JPtrArray<JString>* javaContextNamespaceList, const JBoolean findDeclaration, const JBoolean findDefinition, JArray<JIndex>* matchList ) const { // find all symbols that match matchList->RemoveAll(); matchList->SetBlockSize(50); JArray<JIndex> allMatchList(50); JString s = name; SymbolInfo target; target.name = &s; JIndex startIndex; if (itsSymbolList->SearchSorted(target, JOrderedSetT::kFirstMatch, &startIndex)) { const JSize count = itsSymbolList->GetElementCount(); for (JIndex i=startIndex; i<=count; i++) { const SymbolInfo info = itsSymbolList->GetElement(i); if (!CompareSymbols(target, info) == JOrderedSetT::kFirstEqualSecond) { break; } if (!CBIsCaseSensitive(info.lang) || *(info.name) == s) { if (contextFileID == info.fileID && // automatically fails if context is kInvalidID IsFileScope(info.type)) { matchList->RemoveAll(); matchList->AppendElement(i); break; } if ((findDeclaration || !IsPrototype(info.type)) && (findDefinition || !IsFunction(info.type))) { matchList->AppendElement(i); } allMatchList.AppendElement(i); } } } JBoolean usedAllList = kJFalse; if (matchList->IsEmpty()) { *matchList = allMatchList; usedAllList = kJTrue; } // replace symbols with fully qualified versions if (!matchList->IsEmpty()) { JString ns1, ns2; PrepareContextNamespace(contextNamespace, contextLang, &ns1, &ns2); PrepareCContextNamespaceList(cContextNamespaceList); PrepareJavaContextNamespaceList(javaContextNamespaceList); JArray<JIndex> noContextList = *matchList; if (!ConvertToFullNames(&noContextList, matchList, ns1, ns2, contextLang, *cContextNamespaceList, *javaContextNamespaceList)) { if (!usedAllList && !findDeclaration && findDefinition) { // if no definition, try declarations // (all: class decl, C++: pure virtual fn) JArray<JIndex> allNoContextList = allMatchList; if (ConvertToFullNames(&allNoContextList, &allMatchList, ns1, ns2, contextLang, *cContextNamespaceList, *javaContextNamespaceList)) { *matchList = allMatchList; } else { *matchList = noContextList; // honor original request for only defn } } else { *matchList = noContextList; } } // re-sort matchList->SetCompareObject(FindSymbolCompare(*itsSymbolList)); matchList->SetSortOrder(itsSymbolList->GetSortOrder()); matchList->Sort(); return kJTrue; } else { return kJFalse; } }
JSFunction JSValue::ToFunction() const { assert(IsFunction()); return JSFunction(ctx_, instance()); }