JsVm::JsVm(const std::string &code) : m_isolate(v8::Isolate::New()) , m_isolateScope(m_isolate) , m_locker(m_isolate) #ifdef HAVE_V8_WITH_MOST_CONSTRUCTORS_ISOLATE , m_scope(m_isolate) #endif , m_global(v8::ObjectTemplate::New()) { v8::Handle<v8::ObjectTemplate> console = v8::ObjectTemplate::New(); m_global->Set(newUtf8String("console"), console); console->Set(newUtf8String("log"), newFunctionTemplate(&Js::log)); console->Set(newUtf8String("error"), newFunctionTemplate(&Js::error)); /** * We can't do this inside initialization list, since we are modifying * "m_global", and during ths gc can update references to it, since we are * adding _properties_ to it. * * And also to avoid Context::Scope for every call(), just enter context * here, since this module already provides "box" for executing * user-specific code in current thread. */ m_context = newContext(NULL, m_global); m_context->Enter(); m_source = newUtf8String(code.c_str()); }
std::pair<SCORE, void*> LanguageModel::Score( const std::vector<const Factor*> &context) const { //cerr << "context="; //DebugContext(context); std::pair<SCORE, void*> ret; typedef Node<const Factor*, LMScores> LMNode; const LMNode *node = m_root.getNode(context); if (node) { ret.first = node->getValue().prob; ret.second = (void*) node; } else { SCORE backoff = 0; std::vector<const Factor*> backOffContext(context.begin() + 1, context.end()); node = m_root.getNode(backOffContext); if (node) { backoff = node->getValue().backoff; } std::vector<const Factor*> newContext(context.begin(), context.end() - 1); std::pair<SCORE, void*> newRet = Score(newContext); ret.first = backoff + newRet.first; ret.second = newRet.second; } //cerr << "score=" << ret.first << endl; return ret; }
int main(int argc, const char * argv[]) { char code[1000] = ""; FILE *fp = fopen(argv[1], "r"); int i = 0; char c; while((c = fgetc(fp)) != EOF){ code[i++] = c; } fclose(fp); code[i] = '\0'; VM* vm = newVM(); Context* global = newContext(); Contexts* contexts = newContexts(); pushContext(contexts, global); Method* methods[MAX_METHOD_NUM] = { defineMethod("+", method_add), defineMethod("add", method_add), defineMethod("-", method_minus), defineMethod("minus", method_minus), defineMethod("*", method_multiply), defineMethod("multiply", method_multiply), defineMethod("/", method_divide), defineMethod("divide", method_divide), defineMethod("\\", method_last), defineMethod("last", method_last) }; return execute(code, vm, contexts, methods); }
void NSFThread::handleException(const std::exception& exception) { // NSFExceptionContext maintains exception as a reference, so use two statements for proper scoping std::runtime_error newException(getName() + " thread exception: " + exception.what()); NSFExceptionContext newContext(this, newException); ExceptionActions.execute(newContext); NSFExceptionHandler::getExceptionHandler().handleException(newContext); }
/*! * @if jp * @brief 新しいコンテキストを bind する * @else * pbrief Bind new namingContext * @endif */ CosNaming::NamingContext_ptr CorbaNaming::bindNewContext(const CosNaming::Name& name, bool force) throw (SystemException, NotFound, CannotProceed, InvalidName, AlreadyBound) { try { return m_rootContext->bind_new_context(name); } catch (NotFound& e) { force ? bindRecursive(m_rootContext, name, newContext()) : throw e; } catch (CannotProceed& e) { #ifndef ORB_IS_RTORB force ? bindRecursive(e.cxt, e.rest_of_name, newContext()) : throw e; #else // ORB_IS_RTORB force ? bindRecursive(e.cxt(), e.rest_of_name(), newContext()) : throw e; #endif // ORB_IS_RTORB } return CosNaming::NamingContext::_nil(); }
void RecordingRenderer::renderResource(const physx::apex::NxApexRenderContext& context) { RecordingRenderResource* resource = reinterpret_cast<RecordingRenderResource*>(context.renderResource); resource->render(); physx::apex::NxUserRenderResource* child = resource->getChild(); if (mChild != NULL && child != NULL) { physx::apex::NxApexRenderContext newContext(context); newContext.renderResource = child; mChild->renderResource(newContext); } }
void GDExporter::GetUniqueRenderContexts( MFnTransform& transform, std::list<GDRenderContext>& uniqueContexts ) { for(unsigned int i = 0; i < transform.childCount(); ++i) { if( transform.child(i).apiType() == MFn::kMesh ) { MFnMesh childMesh( transform.child(i) ); if( childMesh.isIntermediateObject() ) continue; MDagPath meshPath; childMesh.getPath(meshPath); MFnDependencyNode depNode(meshPath.node()); MStatus fpResult; MPlug gdRenderContextPlug = childMesh.findPlug("GDRenderContext", &fpResult); if( fpResult != MS::kSuccess ) continue; GDRenderContext newContext(gdRenderContextPlug); bool bFound = false; std::list<GDRenderContext>::iterator uniqueIter = uniqueContexts.begin(); for(; uniqueIter != uniqueContexts.end(); ++uniqueIter ) { if( (*uniqueIter) == newContext ) { bFound = true; break; } } if( bFound == false ) uniqueContexts.push_back( newContext ); else gdRenderContextPlug.child(0).setValue( (*uniqueIter).name.c_str() ); } else if( transform.child(i).apiType() == MFn::kTransform ) { MFnTransform childTransform( transform.child(i) ); GetUniqueRenderContexts( childTransform, uniqueContexts ); } } }
int main(int argc, char **args) { if (argc < 3) { printf(" barrier <threadcount> <repetitions>\n"); exit(0); } int threadCount = atoi(args[1]); int repetitionCount = atoll(args[2]); assert(threadCount > 0); assert(repetitionCount > 0); Context *context = newContext(threadCount, repetitionCount); pthread_t t[threadCount]; ThreadInfo infos[threadCount]; printContext(context); printf("\n"); /* start all threads */ for (int i = 0; i < threadCount; ++i) { infos[i].index = i; infos[i].c = context; if(pthread_create( &t[i], NULL, Thread, (void *)&(infos[i]))){ perror("pthread_create"); exit(-1); } } /* join all threads */ for (int i = 0; i < threadCount; ++i){ if(pthread_join(t[i], NULL)){ perror("pthread_join"); exit(-1); } } printContext(context); finishContext(context); return 0; }
/** * @brief Creates a new context from peer *ids* of an *oldContext* * */ Context createContext(const std::vector<VAddr> vAddrs, const Context oldContext){ assert(vAddrs.size() > 0); VAddr myVAddr = oldContext.getVAddr(); bool isPartOfNewContext = false; for(VAddr vAddr : vAddrs){ if(vAddr == myVAddr){ isPartOfNewContext = true; } } mpi::communicator newComm = oldContext.comm.split(isPartOfNewContext); if(isPartOfNewContext){ std::array<Uri, 1> uri; Context newContext(++contextCount, newComm); uri[0] = newContext.getVAddr(); // Update UriMap uriMap.push_back(std::vector<Uri>(newContext.size())); std::vector<Uri> otherUris(newContext.size()); allGather(newContext, uri, otherUris); std::copy(otherUris.begin(), otherUris.end(), uriMap[newContext.getID()].begin()); return newContext; } else { // return invalid context // for peers not anymore included return Context(); } }
static void doPaint(uiArea *a, HDC dc, RECT *client, RECT *clip) { uiAreaHandler *ah = a->ah; uiAreaDrawParams dp; dp.Context = newContext(dc); dp.ClientWidth = client->right - client->left; dp.ClientHeight = client->bottom - client->top; dp.ClipX = clip->left; dp.ClipY = clip->top; dp.ClipWidth = clip->right - clip->left; dp.ClipHeight = clip->bottom - clip->top; // TODO is this really the best for multimonitor setups? dp.DPIX = GetDeviceCaps(dc, LOGPIXELSX); dp.DPIY = GetDeviceCaps(dc, LOGPIXELSY); dp.HScrollPos = a->hscrollpos; dp.VScrollPos = a->vscrollpos; (*(ah->Draw))(ah, a, &dp); }
OOH323CallData* ooCreateCall(char* type, char*callToken) { OOH323CallData *call=NULL; OOCTXT *pctxt=NULL; pctxt = newContext(); if(!pctxt) { OOTRACEERR1("ERROR:Failed to create OOCTXT for new call\n"); return NULL; } call = (OOH323CallData*)memAlloc(pctxt, sizeof(OOH323CallData)); if(!call) { OOTRACEERR1("ERROR:Memory - ooCreateCall - call\n"); return NULL; } /* memset(call, 0, sizeof(OOH323CallData));*/ call->pctxt = pctxt; call->callMode = gH323ep.callMode; sprintf(call->callToken, "%s", callToken); sprintf(call->callType, "%s", type); call->callReference = 0; if(gH323ep.callerid) { strncpy(call->ourCallerId, gH323ep.callerid, sizeof(call->ourCallerId)-1); call->ourCallerId[sizeof(call->ourCallerId)-1] = '\0'; } else { call->ourCallerId[0] = '\0'; } memset(&call->callIdentifier, 0, sizeof(H225CallIdentifier)); memset(&call->confIdentifier, 0, sizeof(H225ConferenceIdentifier)); call->flags = 0; if (OO_TESTFLAG(gH323ep.flags, OO_M_TUNNELING)) OO_SETFLAG (call->flags, OO_M_TUNNELING); if(gH323ep.gkClient) { if(OO_TESTFLAG(gH323ep.flags, OO_M_GKROUTED)) { OO_SETFLAG(call->flags, OO_M_GKROUTED); } } if (OO_TESTFLAG(gH323ep.flags, OO_M_FASTSTART)) OO_SETFLAG (call->flags, OO_M_FASTSTART); if (OO_TESTFLAG(gH323ep.flags, OO_M_MEDIAWAITFORCONN)) OO_SETFLAG (call->flags, OO_M_MEDIAWAITFORCONN); call->callState = OO_CALL_CREATED; call->callEndReason = OO_REASON_UNKNOWN; call->pCallFwdData = NULL; if(!strcmp(call->callType, "incoming")) { call->callingPartyNumber = NULL; } else{ if(ooUtilsIsStrEmpty(gH323ep.callingPartyNumber)) { call->callingPartyNumber = NULL; } else{ call->callingPartyNumber = (char*) memAlloc(call->pctxt, strlen(gH323ep.callingPartyNumber)+1); if(call->callingPartyNumber) { strcpy(call->callingPartyNumber, gH323ep.callingPartyNumber); } else{ OOTRACEERR3("Error:Memory - ooCreateCall - callingPartyNumber" ".(%s, %s)\n", call->callType, call->callToken); freeContext(pctxt); return NULL; } } } call->calledPartyNumber = NULL; call->h245ConnectionAttempts = 0; call->h245SessionState = OO_H245SESSION_IDLE; call->dtmfmode = gH323ep.dtmfmode; call->mediaInfo = NULL; strcpy(call->localIP, gH323ep.signallingIP); call->pH225Channel = NULL; call->pH245Channel = NULL; call->h245listener = NULL; call->h245listenport = NULL; call->remoteIP[0] = '\0'; call->remotePort = 0; call->remoteH245Port = 0; call->remoteDisplayName = NULL; call->remoteAliases = NULL; call->ourAliases = NULL; call->masterSlaveState = OO_MasterSlave_Idle; call->statusDeterminationNumber = 0; call->localTermCapState = OO_LocalTermCapExchange_Idle; call->remoteTermCapState = OO_RemoteTermCapExchange_Idle; call->ourCaps = NULL; call->remoteCaps = NULL; call->jointCaps = NULL; dListInit(&call->remoteFastStartOLCs); call->remoteTermCapSeqNo =0; call->localTermCapSeqNo = 0; memcpy(&call->capPrefs, &gH323ep.capPrefs, sizeof(OOCapPrefs)); call->logicalChans = NULL; call->noOfLogicalChannels = 0; call->logicalChanNoBase = 1001; call->logicalChanNoMax = 1100; call->logicalChanNoCur = 1001; call->nextSessionID = 4; /* 1,2,3 are reserved for audio, video and data */ dListInit(&call->timerList); call->msdRetries = 0; call->pFastStartRes = NULL; call->usrData = NULL; OOTRACEINFO3("Created a new call (%s, %s)\n", call->callType, call->callToken); /* Add new call to calllist */ ooAddCallToList (call); if(gH323ep.h323Callbacks.onNewCallCreated) gH323ep.h323Callbacks.onNewCallCreated(call); return call; }
/*! * @if jp * @brief 名前をバインドまたは解決する * @else * @brief Bind or resolve the given name component * @endif */ CosNaming::NamingContext_ptr CorbaNaming::bindOrResolveContext(CosNaming::NamingContext_ptr context, const CosNaming::Name& name) { return bindOrResolveContext(context, name, newContext()); }
/* reinitialize Metric - only for live host */ int /* 1: ok, 0: try again later, -1: fail */ reinitMetric(Metric *m) { char *hname = symName(m->hname); char *mname = symName(m->mname); char **inames; int *iids; int handle; int ret = 1; int sts; int i, j; /* set up temporary context */ if ((handle = newContext(hname)) < 0) return 0; host_state_changed(hname, STATE_RECONN); if ((sts = pmLookupName(1, &mname, &m->desc.pmid)) < 0) { ret = 0; goto end; } /* fill in performance metric descriptor */ if ((sts = pmLookupDesc(m->desc.pmid, &m->desc)) < 0) { ret = 0; goto end; } if (m->desc.type == PM_TYPE_STRING || m->desc.type == PM_TYPE_AGGREGATE || m->desc.type == PM_TYPE_AGGREGATE_STATIC || m->desc.type == PM_TYPE_EVENT || m->desc.type == PM_TYPE_HIGHRES_EVENT || m->desc.type == PM_TYPE_UNKNOWN) { fprintf(stderr, "%s: metric %s has non-numeric type\n", pmProgname, mname); ret = -1; } else if (m->desc.indom == PM_INDOM_NULL) { if (m->specinst != 0) { fprintf(stderr, "%s: metric %s has no instances\n", pmProgname, mname); ret = -1; } else m->m_idom = 1; } else { if ((sts = pmGetInDom(m->desc.indom, &iids, &inames)) < 0) { /* full profile */ ret = 0; } else { if (m->specinst == 0) { /* all instances */ m->iids = iids; m->m_idom = sts; m->inames = alloc(m->m_idom*sizeof(char *)); for (i = 0; i < m->m_idom; i++) { m->inames[i] = sdup(inames[i]); } } else { /* explicit instance profile */ m->m_idom = 0; for (i = 0; i < m->specinst; i++) { /* look for first matching instance name */ for (j = 0; j < sts; j++) { if (eqinst(m->inames[i], inames[j])) { m->iids[i] = iids[j]; m->m_idom++; break; } } if (j == sts) { m->iids[i] = PM_IN_NULL; ret = 0; } } if (sts > 0) { /* * pmGetInDom or pmGetInDomArchive returned some * instances above */ free(iids); } /* * if specinst != m_idom, then some not found ... move these * to the end of the list */ for (j = m->specinst-1; j >= 0; j--) { if (m->iids[j] != PM_IN_NULL) break; } for (i = 0; i < j; i++) { if (m->iids[i] == PM_IN_NULL) { /* need to swap */ char *tp; tp = m->inames[i]; m->inames[i] = m->inames[j]; m->iids[i] = m->iids[j]; m->inames[j] = tp; m->iids[j] = PM_IN_NULL; j--; } } } #if PCP_DEBUG if (pmDebug & DBG_TRACE_APPL1) { int numinst; fprintf(stderr, "reinitMetric: %s from %s: instance domain specinst=%d\n", mname, hname, m->specinst); if (m->m_idom < 1) fprintf(stderr, " %d instances!\n", m->m_idom); if (m->specinst == 0) numinst = m->m_idom; else numinst = m->specinst; for (i = 0; i < numinst; i++) { fprintf(stderr, " indom[%d]", i); if (m->iids[i] == PM_IN_NULL) fprintf(stderr, " ?missing"); else fprintf(stderr, " %d", m->iids[i]); fprintf(stderr, " \"%s\"\n", m->inames[i]); } } #endif if (sts > 0) { /* * pmGetInDom or pmGetInDomArchive returned some instances * above */ free(inames); } } } if (ret == 1) { /* compute conversion factor into canonical units - non-zero conversion factor flags initialized metric */ m->conv = scale(m->desc.units); /* automatic rate computation */ if (m->desc.sem == PM_SEM_COUNTER) { m->vals = (double *) ralloc(m->vals, m->m_idom * sizeof(double)); for (j = 0; j < m->m_idom; j++) m->vals[j] = 0; } } if (ret >= 0) { /* * re-shape, starting here are working up the expression until * we reach the top of the tree or the designated metrics * associated with the node are not the same */ Expr *x = m->expr; while (x) { /* * only re-shape expressions that may have set values */ if (x->op == CND_FETCH || x->op == CND_NEG || x->op == CND_ADD || x->op == CND_SUB || x->op == CND_MUL || x->op == CND_DIV || x->op == CND_SUM_HOST || x->op == CND_SUM_INST || x->op == CND_SUM_TIME || x->op == CND_AVG_HOST || x->op == CND_AVG_INST || x->op == CND_AVG_TIME || x->op == CND_MAX_HOST || x->op == CND_MAX_INST || x->op == CND_MAX_TIME || x->op == CND_MIN_HOST || x->op == CND_MIN_INST || x->op == CND_MIN_TIME || x->op == CND_EQ || x->op == CND_NEQ || x->op == CND_LT || x->op == CND_LTE || x->op == CND_GT || x->op == CND_GTE || x->op == CND_NOT || x->op == CND_AND || x->op == CND_OR || x->op == CND_RISE || x->op == CND_FALL || x->op == CND_INSTANT || x->op == CND_MATCH || x->op == CND_NOMATCH) { instFetchExpr(x); findEval(x); #if PCP_DEBUG if (pmDebug & DBG_TRACE_APPL1) { fprintf(stderr, "reinitMetric: re-shaped ...\n"); dumpExpr(x); } #endif } if (x->parent) { x = x->parent; if (x->metrics == m) continue; } break; } } end: /* destroy temporary context */ pmDestroyContext(handle); return ret; }
/* initialize Metric */ int /* 1: ok, 0: try again later, -1: fail */ initMetric(Metric *m) { char *hname = symName(m->hname); char *mname = symName(m->mname); char **inames; int *iids; int handle; int ret = 1; int sts; int i, j; /* set up temporary context */ if ((handle = newContext(hname)) < 0) return 0; host_state_changed(hname, STATE_RECONN); if ((sts = pmLookupName(1, &mname, &m->desc.pmid)) < 0) { fprintf(stderr, "%s: metric %s not in namespace for %s\n" "pmLookupName failed: %s\n", pmProgname, mname, findsource(hname), pmErrStr(sts)); ret = 0; goto end; } /* fill in performance metric descriptor */ if ((sts = pmLookupDesc(m->desc.pmid, &m->desc)) < 0) { fprintf(stderr, "%s: metric %s not currently available from %s\n" "pmLookupDesc failed: %s\n", pmProgname, mname, findsource(hname), pmErrStr(sts)); ret = 0; goto end; } if (m->desc.type == PM_TYPE_STRING || m->desc.type == PM_TYPE_AGGREGATE || m->desc.type == PM_TYPE_AGGREGATE_STATIC || m->desc.type == PM_TYPE_EVENT || m->desc.type == PM_TYPE_HIGHRES_EVENT || m->desc.type == PM_TYPE_UNKNOWN) { fprintf(stderr, "%s: metric %s has non-numeric type\n", pmProgname, mname); ret = -1; } else if (m->desc.indom == PM_INDOM_NULL) { if (m->specinst != 0) { fprintf(stderr, "%s: metric %s has no instances\n", pmProgname, mname); ret = -1; } else m->m_idom = 1; } else { /* metric has instances, get full instance profile */ if (archives) { if ((sts = pmGetInDomArchive(m->desc.indom, &iids, &inames)) < 0) { fprintf(stderr, "Metric %s from %s - instance domain not " "available in archive\npmGetInDomArchive failed: %s\n", mname, findsource(hname), pmErrStr(sts)); ret = -1; } } else if ((sts = pmGetInDom(m->desc.indom, &iids, &inames)) < 0) { fprintf(stderr, "Instance domain for metric %s from %s not (currently) available\n" "pmGetIndom failed: %s\n", mname, findsource(hname), pmErrStr(sts)); ret = 0; } if (ret == 1) { /* got instance profile */ if (m->specinst == 0) { /* all instances */ m->iids = iids; m->m_idom = sts; m->inames = alloc(m->m_idom*sizeof(char *)); for (i = 0; i < m->m_idom; i++) { m->inames[i] = sdup(inames[i]); } } else { /* selected instances only */ m->m_idom = 0; for (i = 0; i < m->specinst; i++) { /* look for first matching instance name */ for (j = 0; j < sts; j++) { if (eqinst(m->inames[i], inames[j])) { m->iids[i] = iids[j]; m->m_idom++; break; } } if (j == sts) { __pmNotifyErr(LOG_ERR, "metric %s from %s does not " "(currently) have instance \"%s\"\n", mname, findsource(hname), m->inames[i]); m->iids[i] = PM_IN_NULL; ret = 0; } } if (sts > 0) { /* * pmGetInDom or pmGetInDomArchive returned some * instances above */ free(iids); } /* * if specinst != m_idom, then some not found ... move these * to the end of the list */ for (j = m->specinst-1; j >= 0; j--) { if (m->iids[j] != PM_IN_NULL) break; } for (i = 0; i < j; i++) { if (m->iids[i] == PM_IN_NULL) { /* need to swap */ char *tp; tp = m->inames[i]; m->inames[i] = m->inames[j]; m->iids[i] = m->iids[j]; m->inames[j] = tp; m->iids[j] = PM_IN_NULL; j--; } } } #if PCP_DEBUG if (pmDebug & DBG_TRACE_APPL1) { int numinst; fprintf(stderr, "initMetric: %s from %s: instance domain specinst=%d\n", mname, hname, m->specinst); if (m->m_idom < 1) fprintf(stderr, " %d instances!\n", m->m_idom); numinst = m->specinst == 0 ? m->m_idom : m->specinst; for (i = 0; i < numinst; i++) { fprintf(stderr, " indom[%d]", i); if (m->iids[i] == PM_IN_NULL) fprintf(stderr, " ?missing"); else fprintf(stderr, " %d", m->iids[i]); fprintf(stderr, " \"%s\"\n", m->inames[i]); } } #endif if (sts > 0) { /* * pmGetInDom or pmGetInDomArchive returned some instances * above */ free(inames); } } } if (ret == 1) { /* compute conversion factor into canonical units - non-zero conversion factor flags initialized metric */ m->conv = scale(m->desc.units); /* automatic rate computation */ if (m->desc.sem == PM_SEM_COUNTER) { m->vals = (double *) ralloc(m->vals, m->m_idom * sizeof(double)); for (j = 0; j < m->m_idom; j++) m->vals[j] = 0; } } end: /* destroy temporary context */ pmDestroyContext(handle); /* retry not meaningful for archives */ if (archives && (ret == 0)) ret = -1; return ret; }
/* find Fetch bundle for Metric */ static Fetch * findFetch(Host *h, Metric *m) { Fetch *f; int sts; int i; int n; pmID pmid = m->desc.pmid; pmID *p; struct timeval tv; /* find existing Fetch bundle */ f = h->fetches; /* create new Fetch bundle */ if (! f) { f = newFetch(h); if ((f->handle = newContext(symName(h->name))) < 0) { free(f); h->down = 1; return NULL; } if (archives) { int tmp_ival; int tmp_mode = PM_MODE_INTERP; getDoubleAsXTB(&h->task->delta, &tmp_ival, &tmp_mode); __pmtimevalFromReal(start, &tv); if ((sts = pmSetMode(tmp_mode, &tv, tmp_ival)) < 0) { fprintf(stderr, "%s: pmSetMode failed: %s\n", pmProgname, pmErrStr(sts)); exit(1); } #if PCP_DEBUG if (pmDebug & DBG_TRACE_APPL1) { fprintf(stderr, "findFetch: fetch=0x%p host=0x%p delta=%.6f handle=%d\n", f, h, h->task->delta, f->handle); } #endif } f->next = NULL; f->prev = NULL; h->fetches = f; } /* look for existing pmid */ p = f->pmids; n = f->npmids; for (i = 0; i < n; i++) { if (*p == pmid) break; p++; } /* add new pmid */ if (i == n) { p = f->pmids; p = ralloc(p, (n+1) * sizeof(pmID)); p[n] = pmid; f->npmids = n + 1; f->pmids = p; } return f; }
int calc(Vnode* expr, VM* vm, Contexts* contexts, Method** methods){ // Already calculated if(expr->obj){ return 0; } // Variable if(expr->name){ if(strEqual(expr->name, "assign") || strEqual(expr->name, "$") || strEqual(expr->name, "lamda")){ expr->isMethod = true; }else{ for(int i = 0; methods[i]; i++){ if(strEqual(expr->name, methods[i]->name)){ expr->isMethod = true; break; } } } if(!expr->isMethod){ expr->obj = findFromContexts(contexts, expr->name); assert(expr->obj, "Error: %s not defined!", expr->name); } } // Calculate if(expr->childrenNum){ calc(expr->children[0], vm, contexts, methods); Vnode* firstNode = expr->children[0]; int argNum = expr->childrenNum - 1; printf("====================== Calc =======================\n"); printf("Calc: %s \n", firstNode->name); printContexts(contexts); printf("End : %s\n", firstNode->name); // Native method if(firstNode->isMethod){ if(strEqual(firstNode->name, "assign") || strEqual(firstNode->name, "$")){ assert(argNum == 2 && expr->children[1]->name, "Error: Wrong arguments for def!"); char* key = expr->children[1]->name; calc(expr->children[2], vm, contexts, methods); Object* value = expr->children[2]->obj; Context* curr = getTopContext(contexts); defineInContext(curr, key, value); }else if(strEqual(firstNode->name, "lamda")){ expr->obj = pushLamda(vm, expr->node); expr->obj->lamdaId = lamdaNum; lamdaContexts[lamdaNum] = copyContexts(contexts, NULL); lamdaNum++; }else{ for(int i = 0; methods[i]; i++){ if(strEqual(firstNode->name, methods[i]->name)){ Object** args = malloc(sizeof(Object*) * argNum); for(int i = 0; i < argNum; i++){ calc(expr->children[i+1], vm, contexts, methods); args[i] = cloneObject(vm, expr->children[i+1]->obj); } expr->obj = methods[i]->callee(argNum, args, vm); break; } } } return 0; } Object* firstVal = firstNode->obj; // First value if(firstVal->type != OBJ_LAMDA){ expr->obj = cloneObject(vm, firstVal); return 0; } // Lamda call // get args Contexts* cxts = copyContexts(lamdaContexts[firstVal->lamdaId], NULL); Context* runCxt = newContext(); for(int i = 0; i < argNum; i++){ calc(expr->children[i+1], vm, contexts, methods); defineInContext(runCxt, firstVal->args[i], cloneObject(vm, expr->children[i+1]->obj)); } pushContext(cxts, runCxt); Vnode* vn = getVnode(firstVal->grammarTree->root, vm); calc(vn, vm, cxts, methods); expr->obj = vn->obj; return 0; } return 0; }