void QGeoCodeReplyNokia::networkFinished() { if (!m_reply) return; if (m_reply->error() != QNetworkReply::NoError) return; QGeoCodeXmlParser *parser = new QGeoCodeXmlParser; parser->setBounds(viewport()); connect(parser, SIGNAL(results(QList<QGeoLocation>)), this, SLOT(appendResults(QList<QGeoLocation>))); connect(parser, SIGNAL(error(QString)), this, SLOT(parseError(QString))); m_parsing = true; parser->parse(m_reply->readAll()); m_reply->deleteLater(); m_reply = 0; }
ScriptResult PythonEngine::runPythonScript(const QString &script, const QString &fileName) { m_isRunning = true; m_stdOut = ""; QSettings settings; // enable user module deleter if (settings.value("PythonEngine/UserModuleDeleter", true).toBool()) deleteUserModules(); runPythonHeader(); PyObject *output = NULL; if (QFile::exists(fileName)) { QString str = QString("from os import chdir; chdir(u'" + QFileInfo(fileName).absolutePath() + "')"); PyRun_String(str.toStdString().c_str(), Py_single_input, m_dict, m_dict); } // compile PyObject *code = Py_CompileString(script.toStdString().c_str(), fileName.toStdString().c_str(), Py_file_input); // run if (code) output = PyEval_EvalCode((PyCodeObject *) code, m_dict, m_dict); ScriptResult scriptResult; if (output) { scriptResult.isError = false; scriptResult.text = m_stdOut.trimmed(); } else { scriptResult = parseError(); } Py_XDECREF(output); m_isRunning = false; emit executedScript(); return scriptResult; }
bool HttpServer::readRequestHeader() { #ifdef DEBUG_XMLRPC qDebug() << this << "readRequestHeader()"; #endif // code from qhttp.cpp bool end = false; QByteArray tmp; QByteArray rn("\r\n",2), n("\n",1); while (!end && socket->canReadLine()) { tmp = socket->readLine(); if (tmp == rn || tmp == n || tmp.isEmpty()) end = true; else requestHeaderBody.append( tmp ); } if( !end ) { #ifdef DEBUG_XMLRPC qDebug() << this << "readRequestHeader(): waiting more data, readed" << endl << requestHeaderBody; #endif return false; } requestHeader = QHttpRequestHeader( requestHeaderBody ); requestHeaderBody.clear(); requestBody.clear(); if( requestHeader.isValid() ) { #ifdef DEBUG_XMLRPC qDebug() << this << "readRequestHeader(): header valid" << endl << requestHeader.toString(); #endif return true; } qWarning() << this << "readRequestHeader(): invalid requestHeader, emit parseError()" << endl << requestHeader.toString(); emit parseError( this ); return false; }
void Parser::SubAdd_1() { switch(lookahead) { int tempVal; int tempVal_2; case T_PLUS: match(T_PLUS); if( evaluate == true) { tempVal = value; } MultDiv(); if( evaluate == true) { value = tempVal + value; } SubAdd_1(); break; case T_MINUS: match(T_MINUS); if( evaluate == true) { tempVal_2 = value; } MultDiv(); if( evaluate == true) { value = tempVal_2 - value; } SubAdd_1(); break; case T_SEMICOLON: case T_EOF: case T_CLOSEPAREN: case T_CLOSEBRACKET: //epsilon break; default: parseError(scanner.lineNumber(), lookahead); break; } }
void Parser::checkArity(Kind kind, unsigned numArgs) throw(ParserException) { if (!d_checksEnabled) { return; } unsigned min = d_exprManager->minArity(kind); unsigned max = d_exprManager->maxArity(kind); if (numArgs < min || numArgs > max) { stringstream ss; ss << "Expecting "; if (numArgs < min) { ss << "at least " << min << " "; } else { ss << "at most " << max << " "; } ss << "arguments for operator '" << kind << "', "; ss << "found " << numArgs; parseError(ss.str()); } }
User::User(const QString &userXMLStr, QObject *parent) : QObject(parent) { // <user id="[uuid]" ip="[ip]" name="[name]" logTime="[logTime]" info="[info]" status="[status]" iconData="[iconData]" /> QDomDocument userDoc; QString errorMsg; userDoc.setContent(userXMLStr, &errorMsg); if(!errorMsg.isEmpty()) { emit parseError(errorMsg); } QDomElement userE = userDoc.firstChildElement(); uuid = QUuid(userE.attribute("id")); ip = QHostAddress(userE.attribute("ip")); name = userE.attribute("name"); logTime = QDateTime::fromString(userE.attribute("logTime")); info = userE.attribute("info"); status = (Status) userE.attribute("status").toInt(); icon = getIconFromCompressData(userE.attribute("iconData")); }
void ScitemQueryResponse::parseNormalResponse() { parseError(); if (responseParser->hasName("page_index")) { pageIndex = responseParser->getNumByName("page_index"); } if (responseParser->hasName("page_size")) { pageSize = responseParser->getNumByName("page_size"); } if (responseParser->hasName("query_pagination")) { queryPagination.setParser(responseParser->getObjectParser("query_pagination")); queryPagination.parseResponse(); } if (responseParser->hasName("sc_item_list")) { QList<Parser *> listParser = responseParser->getListObjectParser("sc_item_list"); Parser *parser; foreach (parser, listParser) { ScItem tmp; tmp.setParser(parser); tmp.parseResponse(); scItemList.append(tmp); }
SetOf<Word> PresentationParser::parseRelatorList(const VectorOf<Chars>& names,Chars& errMesg) { genNames = names; SetOf<Word> result; if ( curToken == INIT ) getToken(); while ( atStartOfWord() ) { Word u = parseWord( names, errMesg ); if ( errMesg.length() > 0 ) { return result; } if ( curToken != EQUALS ) result.adjoinElement( u.cyclicallyReduce() ); else { while ( curToken == EQUALS ) { getToken(); Word v = parseWord( names, errMesg ); if ( errMesg.length() > 0 ) { return result; } result.adjoinElement( ((Word)(u * v.inverse())).cyclicallyReduce() ); } } if ( curToken == COMMA ) { getToken(); if ( !atStartOfWord() ) { parseError("Expected a word here"); errMesg = parseErrorMessage; return result; } } } return result; }
void Parser::Exp_1(int *p) { int tempVal; int q; int base; if(lookahead == T_POWER) { match(T_POWER); Paren(); if (evaluate == true) { base = value; } Exp_1(&q); if(evaluate == true) { *p = pow(base,q); } } else { //do nothing switch(lookahead) { case T_SEMICOLON: case T_EOF: case T_PLUS: case T_MINUS: case T_MULTIPLY: case T_DIVIDE: case T_CLOSEPAREN: case T_CLOSEBRACKET: //epsilon break; default: parseError(scanner.lineNumber(), lookahead); break; } if(evaluate == true) { *p = 1; //default power is set to 1 } } }
IntrusiveRefCntPtr<PatternExpr> Parser::pattern(bool se) { // TODO: Proper pattern syntax if(token == TTypeIdent) { string const& ctorName = nextIdent(se); IntrusiveRefCntPtr<PatternNamedCtorExpr> pt( new PatternNamedCtorExpr()); pt->name = ctorName; if(test(TLParen)) { do { pt->subPatterns.push_back(pattern(false)); } while(test(TComma)); expect(TRParen); } return IntrusiveRefCntPtr<PatternExpr>(pt.getPtr()); } else if(token == TIdent) { string const& bindingName = nextIdent(se); auto varDecl = declVar(bindingName, TypePtr()); IntrusiveRefCntPtr<PatternBindingExpr> pt( new PatternBindingExpr()); pt->var = varDecl; return IntrusiveRefCntPtr<PatternExpr>(pt.getPtr()); } parseError(); return IntrusiveRefCntPtr<PatternExpr>(); }
QVariant QuickInterpreter::execute(QObject *obj, const QString &c, const QString &name) { QString code = c + QString::fromLatin1("\n"); int sourceId = debugger ? debugger->freeSourceId() : -1; if(!name.isNull() && sourceId >= 0) sourceIdNames[sourceId] = name; QSObject t, oldThis; if (obj) { if (!name.isNull() && sourceId >= 0) addSourceId(sourceId, obj); if (!hasTopLevelParent(obj)) addTopLevelObject(obj); t = wrap(obj); oldThis = env()->thisValue(); env()->setThisValue(t); } QSEngine::evaluate(t, code); // restore this value if (obj) env()->setThisValue(oldThis); if (hadError()) if(errorType() == QSErrParseError) emit parseError(); else emit runtimeError(); // Make sure we dereference the engines return value to avoid pooling QVariant a = convertToArgument(returnValue()); setReturnValue(QSObject()); return a; }
/** parese number of resources */ static SCIP_RETCODE getNResources( SCIP* scip, /**< SCIP data structure */ int lineno, /**< current line number of input file */ char* linestr, /**< current line */ STATE* state, /**< pointer to current reading state */ SCIP_RCPSPDATA* rcpspdata /**< pointer to resources constrained project scheduling data */ ) { SCIP_Real nresources; char* endptr; char* number; assert(linestr != NULL); assert(state != NULL); if( strncmp(linestr, "RESOURCES", 4) == 0 ) return SCIP_OKAY; /* truncate the line via ':' and ignore the first part */ (void)SCIPstrtok(linestr, ":", &endptr); number = SCIPstrtok(NULL, ":", &endptr); if( !SCIPstrToRealValue(number, &nresources, &endptr) ) { parseError(scip, lineno, "expexted number of resources", linestr, state); return SCIP_OKAY; } rcpspdata->nresources = (int)(nresources + 0.5); SCIP_CALL( SCIPallocBufferArray(scip, &rcpspdata->capacities, nresources) ); SCIP_CALL( SCIPallocBufferArray(scip, &rcpspdata->resourcenames, nresources) ); *state = NEXT; return SCIP_OKAY; }
Http_t Parse_parse (int fd) { http400 = generate400(); getToken(fd, 1); ReqLine_t reqline; Http_t http = 0; reqline = parseRequestLine (fd); parseHeaders(fd); if (token.kind!=TOKEN_CRLF) parseError(fd); parseBody(fd); http = Http_new (HTTP_KIND_REQUEST , reqline , 0 , 0 , 0); if (DEBUG) Http_print (1, http); return http; }
cbool parseQuoted( parse *p, char *name ) { char c; int i = 0; if ( parseLexThisChar( p, '"' ) ) { while ( parseAChar( p, &c ) && c != '"' && c != '\n' && assign ( name[i++] = c ) ); if ( c == '"' ) { name[i] = '\0'; return true; } else parseError( p, "Could not parse quoted string" ); } return false; }
Foam::token::compound& Foam::token::transferCompoundToken() { if (type_ == COMPOUND) { if (compoundTokenPtr_->empty()) { FatalErrorIn("token::transferCompoundToken()") << "compound has already been transfered from token\n " << info() << abort(FatalError); } else { compoundTokenPtr_->empty() = true; } return *compoundTokenPtr_; } else { parseError("compound"); return *compoundTokenPtr_; } }
static void hostError(const char *spec, const char *point, char *msg, char **rslt) { parseError("pmParseHostSpec", spec, point, msg, rslt); }
void Parser::checkFunctionLike(const std::string& name) throw(ParserException) { if (d_checksEnabled && !isFunctionLike(name)) { parseError("Expecting function-like symbol, found '" + name + "'"); } }
parseTree parseInputSourceCode(char *testcaseFile, table T, grammar G) { FILE *fp = fopen(testcaseFile,"r"); parseTree pt = (parseTree)calloc(1,sizeof(parseTree_t)); pt->parent = NULL; stack st = (stack)calloc(1,sizeof(stack_t)); st->size = 0; st = push(DOLLAR,st); pt->tk = (tokenInfo)calloc(1,sizeof(token_struct)); st = push(mainFunction,st); pt->tk->sym = mainFunction; parseTree curNode = pt; tokenInfo tk = getNextToken(fp); int t; while(st->size != 1) { if(tk == NULL) { tk = getNextToken(fp); while(tk == NULL || tk->sym != EPSILON) tk = getNextToken(fp); return NULL; } symbol_name symbol = tk->sym; t = (int)symbol - nNonTerminals; if(st->head->sym == symbol) { curNode->tk = tk; while(curNode->right == NULL && curNode->parent != NULL) curNode = curNode->parent; curNode = curNode->right; st = pop(st); tk = getNextToken(fp); } else if(st->head->sym == EPSILON) { st = pop(st); while(curNode->right == NULL) curNode = curNode->parent; curNode = curNode->right; } else if(st->head->sym >= nNonTerminals) { parseError(tk, st, G, &T); return NULL; } else if((*T)->array[st->head->sym][t] == -1) { parseError(tk, st, G, &T); return NULL; } else { int i = (*T)->array[st->head->sym][t]; nodeptr n1 = G->rules[i]->rhs; while(n1->next != NULL) { n1 = n1->next; } st = pop(st); curNode->child = (parseTree)calloc(1,sizeof(parseTree_t)); curNode->child->parent = curNode; curNode = curNode->child; curNode->tk = (tokenInfo)calloc(1,sizeof(token_struct)); curNode->tk->sym = n1->sym; st = push(n1->sym,st); n1 = n1->prev; while(n1!=NULL) { curNode->left = (parseTree)calloc(1,sizeof(parseTree_t)); curNode->left->right = curNode; curNode->left->parent = curNode->parent; curNode = curNode->left; curNode->tk = (tokenInfo)calloc(1,sizeof(token_struct)); curNode->tk->sym = n1->sym; //strcpy(curNode->tk->stringValue, "----"); st = push(n1->sym,st); n1 = n1->prev; } } } if((tk = getNextToken(fp))->sym != EPSILON) { parseError(tk, st, G, &T); return NULL; } printf("Compiled Successfully: Input source code is syntactically correct!!\n"); return pt; }
static void metricError(const char *spec, const char *point, char *msg, char **rslt) { parseError("pmParseMetricSpec", spec, point, msg, rslt); }
/** This is the body of the REPL. It attempts to parse the first line or expression of its input, and optionally request input from the user if none is available. If the input can be parsed correctly, i) the resulting expression is evaluated, ii) the result assigned to .Last.Value, iii) top-level task handlers are invoked. If the input cannot be parsed, i.e. there is a syntax error, it is incomplete, or we encounter an end-of-file, then we change the prompt accordingly. The "cursor" for the input buffer is moved to the next starting point, i.e. the end of the first line or after the first ;. */ int Rf_ReplIteration(SEXP rho, int savestack, int browselevel, R_ReplState *state) { int c, browsevalue; SEXP value, thisExpr; Rboolean wasDisplayed = FALSE; if(!*state->bufp) { R_Busy(0); if (R_ReadConsole(R_PromptString(browselevel, state->prompt_type), state->buf, CONSOLE_BUFFER_SIZE, 1) == 0) return(-1); state->bufp = state->buf; } #ifdef SHELL_ESCAPE /* not default */ if (*state->bufp == '!') { R_system(&(state->buf[1])); state->buf[0] = '\0'; return(0); } #endif /* SHELL_ESCAPE */ while((c = *state->bufp++)) { R_IoBufferPutc(c, &R_ConsoleIob); if(c == ';' || c == '\n') break; } R_PPStackTop = savestack; R_CurrentExpr = R_Parse1Buffer(&R_ConsoleIob, 0, &state->status); switch(state->status) { case PARSE_NULL: /* The intention here is to break on CR but not on other null statements: see PR#9063 */ if (browselevel && !R_DisableNLinBrowser && !strcmp((char *) state->buf, "\n")) return -1; R_IoBufferWriteReset(&R_ConsoleIob); state->prompt_type = 1; return 1; case PARSE_OK: R_IoBufferReadReset(&R_ConsoleIob); R_CurrentExpr = R_Parse1Buffer(&R_ConsoleIob, 1, &state->status); if (browselevel) { browsevalue = ParseBrowser(R_CurrentExpr, rho); if(browsevalue == 1) return -1; if(browsevalue == 2) { R_IoBufferWriteReset(&R_ConsoleIob); return 0; } /* PR#15770 We don't want to step into expressions entered at the debug prompt. The 'S' will be changed back to 's' after the next eval. */ if (R_BrowserLastCommand == 's') R_BrowserLastCommand = 'S'; } R_Visible = FALSE; R_EvalDepth = 0; resetTimeLimits(); PROTECT(thisExpr = R_CurrentExpr); R_Busy(1); value = eval(thisExpr, rho); SET_SYMVALUE(R_LastvalueSymbol, value); wasDisplayed = R_Visible; if (R_Visible) PrintValueEnv(value, rho); if (R_CollectWarnings) PrintWarnings(); Rf_callToplevelHandlers(thisExpr, value, TRUE, wasDisplayed); R_CurrentExpr = value; /* Necessary? Doubt it. */ UNPROTECT(1); if (R_BrowserLastCommand == 'S') R_BrowserLastCommand = 's'; R_IoBufferWriteReset(&R_ConsoleIob); state->prompt_type = 1; return(1); case PARSE_ERROR: state->prompt_type = 1; parseError(R_NilValue, 0); R_IoBufferWriteReset(&R_ConsoleIob); return(1); case PARSE_INCOMPLETE: R_IoBufferReadReset(&R_ConsoleIob); state->prompt_type = 2; return(2); case PARSE_EOF: return(-1); break; } return(0); }
/* Parse a complete file from the stream in 's'. If a parse error happens, do not return; instead exit via parseError(). If an out-of-memory condition happens, do not return; instead exit via mallocError(). */ static CacheProfFile* parse_CacheProfFile ( SOURCE* s ) { #define M_TMP_DESCLINES 10 Int i; Bool b; char* tmp_desclines[M_TMP_DESCLINES]; char* p; int n_tmp_desclines = 0; CacheProfFile* cpf; Counts* summaryRead; char* curr_fn_init = "???"; char* curr_fl_init = "???"; char* curr_fn = curr_fn_init; char* curr_fl = curr_fl_init; cpf = new_CacheProfFile( NULL, NULL, NULL, 0, NULL, NULL, NULL ); if (cpf == NULL) mallocFail(s, "parse_CacheProfFile(1)"); // Parse "desc:" lines while (1) { b = readline(s); if (!b) break; if (!streqn(line, "desc: ", 6)) break; if (n_tmp_desclines >= M_TMP_DESCLINES) barf(s, "M_TMP_DESCLINES too low; increase and recompile"); tmp_desclines[n_tmp_desclines++] = strdup(line); } if (n_tmp_desclines == 0) parseError(s, "parse_CacheProfFile: no DESC lines present"); cpf->desc_lines = malloc( (1+n_tmp_desclines) * sizeof(char*) ); if (cpf->desc_lines == NULL) mallocFail(s, "parse_CacheProfFile(2)"); cpf->desc_lines[n_tmp_desclines] = NULL; for (i = 0; i < n_tmp_desclines; i++) cpf->desc_lines[i] = tmp_desclines[i]; // Parse "cmd:" line if (!streqn(line, "cmd: ", 5)) parseError(s, "parse_CacheProfFile: no CMD line present"); cpf->cmd_line = strdup(line); if (cpf->cmd_line == NULL) mallocFail(s, "parse_CacheProfFile(3)"); // Parse "events:" line and figure out how many events there are b = readline(s); if (!b) parseError(s, "parse_CacheProfFile: eof before EVENTS line"); if (!streqn(line, "events: ", 8)) parseError(s, "parse_CacheProfFile: no EVENTS line present"); // figure out how many events there are by counting the number // of space-alphanum transitions in the events_line cpf->events_line = strdup(line); if (cpf->events_line == NULL) mallocFail(s, "parse_CacheProfFile(3)"); cpf->n_events = 0; assert(cpf->events_line[6] == ':'); for (p = &cpf->events_line[6]; *p; p++) { if (p[0] == ' ' && isalpha(p[1])) cpf->n_events++; } // create the running cross-check summary cpf->summary = new_Counts_Zeroed( cpf->n_events ); if (cpf->summary == NULL) mallocFail(s, "parse_CacheProfFile(4)"); // create the outer map (file+fn name --> inner map) cpf->outerMap = newFM ( malloc, free, cmp_FileFn ); if (cpf->outerMap == NULL) mallocFail(s, "parse_CacheProfFile(5)"); // process count lines while (1) { b = readline(s); if (!b) parseError(s, "parse_CacheProfFile: eof before SUMMARY line"); if (isdigit(line[0])) { handle_counts(s, cpf, curr_fl, curr_fn, line); continue; } else if (streqn(line, "fn=", 3)) { if (curr_fn != curr_fn_init) free(curr_fn); curr_fn = strdup(line+3); continue; } else if (streqn(line, "fl=", 3)) { if (curr_fl != curr_fl_init) free(curr_fl); curr_fl = strdup(line+3); continue; } else if (streqn(line, "summary: ", 9)) { break; } else parseError(s, "parse_CacheProfFile: unexpected line in main data"); } // finally, the "summary:" line if (!streqn(line, "summary: ", 9)) parseError(s, "parse_CacheProfFile: missing SUMMARY line"); cpf->summary_line = strdup(line); if (cpf->summary_line == NULL) mallocFail(s, "parse_CacheProfFile(6)"); // there should be nothing more b = readline(s); if (b) parseError(s, "parse_CacheProfFile: " "extraneous content after SUMMARY line"); // check the summary counts are as expected summaryRead = splitUpCountsLine( s, NULL, &cpf->summary_line[8] ); if (summaryRead == NULL) mallocFail(s, "parse_CacheProfFile(7)"); if (summaryRead->n_counts != cpf->n_events) parseError(s, "parse_CacheProfFile: wrong # counts in SUMMARY line"); for (i = 0; i < summaryRead->n_counts; i++) { if (summaryRead->counts[i] != cpf->summary->counts[i]) { parseError(s, "parse_CacheProfFile: " "computed vs stated SUMMARY counts mismatch"); } } free(summaryRead->counts); sdel_Counts(summaryRead); // since the summary counts are OK, free up the summary_line text // which contains the same info. if (cpf->summary_line) { free(cpf->summary_line); cpf->summary_line = NULL; } if (curr_fn != curr_fn_init) free(curr_fn); if (curr_fl != curr_fl_init) free(curr_fl); // All looks OK return cpf; #undef N_TMP_DESCLINES }
////////////////////////////// // Parse an IRC command (private) void IRCClient::parseCommand(const IRCClient::IRCCommand &cmd) { /*printf("IRC: sender '%s' cmd '%s'", cmd.sender.c_str(), cmd.cmd.c_str() ); for( size_t i=0; i<cmd.params.size(); i++ ) printf(" param %i '%s'", i, cmd.params[i].c_str()); printf("\n");*/ // Process depending on the command bool fail = false; int num_command = from_string<int>(cmd.cmd, fail); // String commands if (fail) { if (cmd.cmd == "PING") parsePing(cmd); else if (cmd.cmd == "MODE") parseMode(cmd); else if (cmd.cmd == "PRIVMSG") parsePrivmsg(cmd); else if (cmd.cmd == "KICK") parseKicked(cmd); else if (cmd.cmd == "PART" || cmd.cmd == "QUIT") parseDropped(cmd); else if (cmd.cmd == "JOIN") parseJoin(cmd); else if (cmd.cmd == "NICK") parseNick(cmd); else if (cmd.cmd == "NOTICE") parseNotice(cmd); else if (cmd.cmd == "ERROR") parseError(cmd); else warnings("IRC: unknown command " + cmd.cmd + "\n"); // Numeric commands } else { switch (num_command) { // Nick in use case LIBIRC_RFC_ERR_NICKNAMEINUSE: parseNickInUse(cmd); break; // List of names case LIBIRC_RFC_RPL_NAMREPLY: parseNameReply(cmd); break; // End of name list case LIBIRC_RFC_RPL_ENDOFNAMES: parseEndOfNames(cmd); break; case LIBIRC_RFC_RPL_AWAY: parseAway(cmd); break; case LIBIRC_RFC_RPL_WHOISUSER: parseWhois(cmd); break; case LIBIRC_RFC_RPL_ENDOFWHOIS: parseEndOfWhois(cmd); break; case LIBIRC_RFC_RPL_TOPIC: parseTopic(cmd); break; // Message of the day case LIBIRC_RFC_RPL_MOTDSTART: case LIBIRC_RFC_RPL_MOTD: case LIBIRC_RFC_RPL_ENDOFMOTD: // Message of the day (ignored currently) break; // Messages sent upon a successful join case LIBIRC_RFC_RPL_WELCOME: case LIBIRC_RFC_RPL_YOURHOST: case LIBIRC_RFC_RPL_CREATED: case LIBIRC_RFC_RPL_MYINFO: // Quite useless stuff... break; default: {} // Just ignore, there are many "pro" commands that we don't need } } }
/* FIXME: this should be re-written to use Rf_ReplIteration since it gets out of sync with it over time */ int R_ReplDLLdo1(void) { int c; ParseStatus status; SEXP rho = R_GlobalEnv, lastExpr; Rboolean wasDisplayed = FALSE; if(!*DLLbufp) { R_Busy(0); if (R_ReadConsole(R_PromptString(0, prompt_type), DLLbuf, CONSOLE_BUFFER_SIZE, 1) == 0) return -1; DLLbufp = DLLbuf; } while((c = *DLLbufp++)) { R_IoBufferPutc(c, &R_ConsoleIob); if(c == ';' || c == '\n') break; } R_PPStackTop = 0; R_CurrentExpr = R_Parse1Buffer(&R_ConsoleIob, 0, &status); switch(status) { case PARSE_NULL: R_IoBufferWriteReset(&R_ConsoleIob); prompt_type = 1; break; case PARSE_OK: R_IoBufferReadReset(&R_ConsoleIob); R_CurrentExpr = R_Parse1Buffer(&R_ConsoleIob, 1, &status); R_Visible = FALSE; R_EvalDepth = 0; resetTimeLimits(); PROTECT(R_CurrentExpr); R_Busy(1); lastExpr = R_CurrentExpr; R_CurrentExpr = eval(R_CurrentExpr, rho); SET_SYMVALUE(R_LastvalueSymbol, R_CurrentExpr); wasDisplayed = R_Visible; if (R_Visible) PrintValueEnv(R_CurrentExpr, rho); if (R_CollectWarnings) PrintWarnings(); Rf_callToplevelHandlers(lastExpr, R_CurrentExpr, TRUE, wasDisplayed); UNPROTECT(1); R_IoBufferWriteReset(&R_ConsoleIob); R_Busy(0); prompt_type = 1; break; case PARSE_ERROR: parseError(R_NilValue, 0); R_IoBufferWriteReset(&R_ConsoleIob); prompt_type = 1; break; case PARSE_INCOMPLETE: R_IoBufferReadReset(&R_ConsoleIob); prompt_type = 2; break; case PARSE_EOF: return -1; break; } return prompt_type; }
bool PresentationParser::getGeneratorRange( const Chars& name, VectorOf<Chars>& result, Chars& errMesg ) { if ( curToken != DOT ) error("bool PresentationParser::getGeneratorRange() " "can't read the range"); // Make sure, that we have 3 dots in a row for (int i = 0;i<2;i++){ getToken(); if ( curToken != DOT ) { parseError("Expected '.' here"); errMesg = parseErrorMessage; return false; } } getToken(); // Supose to be ',' if ( curToken != COMMA ) { parseError("Expected ',' here"); errMesg = parseErrorMessage; return false; } getToken(); // Supose to be a generator if ( curToken != GENERATOR ) { parseError("Expected a generator here"); errMesg = parseErrorMessage; return false; } Chars name1; int beginRange; // Generators must be in the form: <name><index>, where // index is the first and the last generator index in a range. // Chars rangeErrMsg = "When defining a set of generators using a range of " "subscripts, both the smallest subscript and the largest subscript" " must be given and the smallest subscript mast be less then the " "largest one"; if ( !getRangeOf(name,name1,beginRange)) { parseError(rangeErrMsg); errMesg = parseErrorMessage; return false; } Chars name2; int endRange; if ( !getRangeOf(tokenName,name2,endRange)) { parseError(rangeErrMsg); errMesg = parseErrorMessage; return false; } // The last index must be greater than the first one if ( endRange <= beginRange) { parseError(rangeErrMsg); errMesg = parseErrorMessage; return false; } // Names gave to be equal if ( name2 != name1) { parseError(rangeErrMsg); errMesg = parseErrorMessage; return false; } // Generate generators of type: name1<index>, where // beginRange < index < endRange int numberOfGens = endRange - beginRange - 1; if (numberOfGens > 0){ VectorOf<Chars> gens(numberOfGens); for(int i = 0;i<numberOfGens;i++){ gens[i] = name1+Chars(beginRange + 1 + i); // Check for duplication and presence of inverses. if ( result.indexOf(gens[i]) >= 0 ) { parseError("Duplicate generator"); errMesg = parseErrorMessage; return false; } else { char str[100]; strcpy(str,gens[i]); invertName(str); if ( result.indexOf(Chars(str)) >= 0 ) { parseError("Duplicate generator: formal inverse"); errMesg = parseErrorMessage; return false; } } } result = concatenate(result, gens); } return true; }
void DirectiveParser::parseDirective(Token *token) { assert(token->type == Token::PP_HASH); mTokenizer->lex(token); if (isEOD(token)) { // Empty Directive. return; } DirectiveType directive = getDirective(token); // While in an excluded conditional block/group, // we only parse conditional directives. if (skipping() && !isConditionalDirective(directive)) { skipUntilEOD(mTokenizer, token); return; } switch(directive) { case DIRECTIVE_NONE: mDiagnostics->report(Diagnostics::PP_DIRECTIVE_INVALID_NAME, token->location, token->text); skipUntilEOD(mTokenizer, token); break; case DIRECTIVE_DEFINE: parseDefine(token); break; case DIRECTIVE_UNDEF: parseUndef(token); break; case DIRECTIVE_IF: parseIf(token); break; case DIRECTIVE_IFDEF: parseIfdef(token); break; case DIRECTIVE_IFNDEF: parseIfndef(token); break; case DIRECTIVE_ELSE: parseElse(token); break; case DIRECTIVE_ELIF: parseElif(token); break; case DIRECTIVE_ENDIF: parseEndif(token); break; case DIRECTIVE_ERROR: parseError(token); break; case DIRECTIVE_PRAGMA: parsePragma(token); break; case DIRECTIVE_EXTENSION: parseExtension(token); break; case DIRECTIVE_VERSION: parseVersion(token); break; case DIRECTIVE_LINE: parseLine(token); break; default: assert(false); break; } skipUntilEOD(mTokenizer, token); if (token->type == Token::LAST) { mDiagnostics->report(Diagnostics::PP_EOF_IN_DIRECTIVE, token->location, token->text); } }
SQSException::SQSException (const QueryErrorResponse& aError) { theErrorMessage = aError.getErrorMessage(); theOrigErrorCode = aError.getErrorCode(); theErrorCode = parseError(theOrigErrorCode); theRequestId = aError.getRequestId(); }
int HSPReadConfigFile(HSP *sp) { EnumHSPObject level[HSP_MAX_CONFIG_DEPTH + 5]; int depth = 0; level[depth] = HSPOBJ_HSP; // could have used something like bison to make a complete parser with // strict rules, but for simplicity we just allow the current object // to double as a state variable that determines what is allowed next. for(HSPToken *tok = readTokens(sp); tok; tok = tok->nxt) { if(depth > HSP_MAX_CONFIG_DEPTH) { // depth overrun parseError(sp, tok, "too many '{'s", ""); return NO; } else if(tok->stok == HSPTOKEN_ENDOBJ) { // end of level, pop the stack if(depth > 0) --depth; else { parseError(sp, tok, "too many '}'s ", ""); return NO; } } else switch(level[depth]) { case HSPOBJ_HSP: // must start by opening an sFlow object if((tok = expectToken(sp, tok, HSPTOKEN_SFLOW)) == NULL) return NO; if((tok = expectToken(sp, tok, HSPTOKEN_STARTOBJ)) == NULL) return NO; newSFlow(sp); level[++depth] = HSPOBJ_SFLOW; break; case HSPOBJ_SFLOW: switch(tok->stok) { case HSPTOKEN_LOOPBACK: if((tok = expectLoopback(sp, tok)) == NULL) return NO; break; case HSPTOKEN_DNSSD: if((tok = expectDNSSD(sp, tok)) == NULL) return NO; break; case HSPTOKEN_DNSSD_DOMAIN: if((tok = expectDNSSD_domain(sp, tok)) == NULL) return NO; break; case HSPTOKEN_COLLECTOR: if((tok = expectToken(sp, tok, HSPTOKEN_STARTOBJ)) == NULL) return NO; newCollector(sp->sFlow->sFlowSettings_file); level[++depth] = HSPOBJ_COLLECTOR; break; case HSPTOKEN_SAMPLING: case HSPTOKEN_PACKETSAMPLINGRATE: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->samplingRate, 0, 65535)) == NULL) return NO; break; case HSPTOKEN_POLLING: case HSPTOKEN_COUNTERPOLLINGINTERVAL: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->pollingInterval, 0, 300)) == NULL) return NO; break; case HSPTOKEN_AGENTIP: if((tok = expectIP(sp, tok, &sp->sFlow->agentIP, NULL)) == NULL) return NO; sp->sFlow->explicitAgentIP = YES; break; case HSPTOKEN_AGENTCIDR: { HSPCIDR cidr = { 0 }; if((tok = expectCIDR(sp, tok, &cidr)) == NULL) return NO; addAgentCIDR(sp->sFlow->sFlowSettings_file, &cidr); } break; case HSPTOKEN_AGENT: if((tok = expectDevice(sp, tok, &sp->sFlow->agentDevice)) == NULL) return NO; sp->sFlow->explicitAgentDevice = YES; break; case HSPTOKEN_SUBAGENTID: if((tok = expectInteger32(sp, tok, &sp->sFlow->subAgentId, 0, HSP_MAX_SUBAGENTID)) == NULL) return NO; break; case HSPTOKEN_UUID: if((tok = expectUUID(sp, tok, sp->uuid)) == NULL) return NO; break; case HSPTOKEN_HEADERBYTES: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->headerBytes, 0, HSP_MAX_HEADER_BYTES)) == NULL) return NO; break; case HSPTOKEN_ULOGGROUP: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->ulogGroup, 1, 32)) == NULL) return NO; break; case HSPTOKEN_ULOGPROBABILITY: if((tok = expectDouble(sp, tok, &sp->sFlow->sFlowSettings_file->ulogProbability, 0.0, 1.0)) == NULL) return NO; break; case HSPTOKEN_JSONPORT: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->jsonPort, 1025, 65535)) == NULL) return NO; break; default: // handle wildcards here - allow sampling.<app>=<n> and polling.<app>=<secs> if(tok->str && strncasecmp(tok->str, "sampling.", 9) == 0) { char *app = tok->str + 9; uint32_t sampling_n=0; if((tok = expectInteger32(sp, tok, &sampling_n, 0, 65535)) == NULL) return NO; setApplicationSampling(sp->sFlow->sFlowSettings_file, app, sampling_n); } else if(tok->str && strncasecmp(tok->str, "polling.", 8) == 0) { char *app = tok->str + 8; uint32_t polling_secs=0; if((tok = expectInteger32(sp, tok, &polling_secs, 0, 300)) == NULL) return NO; setApplicationPolling(sp->sFlow->sFlowSettings_file, app, polling_secs); } else { parseError(sp, tok, "unexpected sFlow setting", ""); return NO; } break; } break; case HSPOBJ_COLLECTOR: { HSPCollector *col = sp->sFlow->sFlowSettings_file->collectors; switch(tok->stok) { case HSPTOKEN_IP: if((tok = expectIP(sp, tok, &col->ipAddr, (struct sockaddr *)&col->sendSocketAddr)) == NULL) return NO; break; case HSPTOKEN_UDPPORT: if((tok = expectInteger32(sp, tok, &col->udpPort, 1, 65535)) == NULL) return NO; break; default: parseError(sp, tok, "unexpected collector setting", ""); return NO; break; } } break; default: parseError(sp, tok, "unexpected state", ""); } } // OK we consumed all the tokens, but we still need to run some sanity checks to make sure // we have a usable configuration... int parseOK = YES; if(sp->sFlow == NULL) { myLog(LOG_ERR, "parse error in %s : sFlow not found", sp->configFile); parseOK = NO; } else { if(sp->sFlow->sFlowSettings_file->numCollectors == 0 && sp->DNSSD == NO) { myLog(LOG_ERR, "parse error in %s : DNS-SD is off and no collectors are defined", sp->configFile); parseOK = NO; } for(HSPCollector *coll = sp->sFlow->sFlowSettings_file->collectors; coll; coll = coll->nxt) { //////////////////////// collector ///////////////////////// if(coll->ipAddr.type == 0) { myLog(LOG_ERR, "parse error in %s : collector has no IP", sp->configFile); parseOK = NO; } } if(sp->sFlow->sFlowSettings_file->ulogProbability > 0) { sp->sFlow->sFlowSettings_file->ulogSamplingRate = (uint32_t)(1.0 / sp->sFlow->sFlowSettings_file->ulogProbability); } } return parseOK; }
bool FormatFile::load( const QString& fileName ) { setFileName( fileName ); if( !TibiaFile::open( QIODevice::ReadOnly ) ){ emit parseError( QObject::tr( "Open Error" ), TibiaFile::error() ); return false; } QString error; int line; QDomDocument doc( "formats" ); if( !doc.setContent( this, true, &error, &line ) ){ emit documentError( fileName, error, line ); TibiaFile::close(); return false; } TibiaFile::close(); QDomElement docElem = doc.documentElement(); if( docElem.tagName().compare( "formats", Qt::CaseInsensitive ) == 0 ) { QDomNode node = docElem.firstChild(); while( !node.isNull() ) { if( node.isElement() ) { QDomElement element = node.toElement(); if( !element.isNull() ) { if( element.tagName().compare( "format", Qt::CaseInsensitive ) == 0 ) { ItemFormat format; format.name = element.attribute( "name" ); format.version = element.attribute( "version" ).toInt(); format.redirect = element.attribute( "redirect" ).toInt(); format.ZDivFactor = element.attribute( "zdiv", "1" ).toInt(); QDomElement subelement = element.firstChildElement( "property" ); while( !subelement.isNull() ) { FormatProperty formatProperty; formatProperty.header = subelement.attribute( "header", "255" ).toInt(); if( format.version == -1 ) formatProperty.base = formatProperty.header; else formatProperty.base = subelement.attribute( "base", "255" ).toInt(); formatProperty.name = subelement.attribute( "name" ); formatProperty.tooltip = subelement.attribute( "tooltip" ); QDomElement child = subelement.firstChildElement( "child" ); while( !child.isNull() ) { PropertyValue propertyValue; propertyValue.size = child.attribute( "size", "0" ).toInt(); propertyValue.name = child.attribute( "name" ); propertyValue.tooltip = child.attribute( "tooltip" ); formatProperty.propertyValues.push_back( propertyValue ); child = child.nextSiblingElement( "child" ); } format.properties.push_back( formatProperty ); subelement = subelement.nextSiblingElement( "property" ); } format.valid = true; formats.insert( format.version, format ); } } } node = node.nextSibling(); } } else { emit documentError( fileName, tr( "Invalid Element: " ) + docElem.tagName(), -1 ); return false; } _loaded = true; return true; }
int HSPReadConfigFile(HSP *sp) { EnumHSPObject level[HSP_MAX_CONFIG_DEPTH + 5]; int depth = 0; level[depth] = HSPOBJ_HSP; // could have used something like bison to make a complete parser with // strict rules, but for simplicity we just allow the current object // to double as a state variable that determines what is allowed next. for(HSPToken *tok = readTokens(sp); tok; tok = tok->nxt) { if(depth > HSP_MAX_CONFIG_DEPTH) { // depth overrun parseError(sp, tok, "too many '{'s", ""); return NO; } else if(tok->stok == HSPTOKEN_ENDOBJ) { // end of level, pop the stack if(depth > 0) --depth; else { parseError(sp, tok, "too many '}'s ", ""); return NO; } } else switch(level[depth]) { case HSPOBJ_HSP: // must start by opening an sFlow object if((tok = expectToken(sp, tok, HSPTOKEN_SFLOW)) == NULL) return NO; if((tok = expectToken(sp, tok, HSPTOKEN_STARTOBJ)) == NULL) return NO; newSFlow(sp); level[++depth] = HSPOBJ_SFLOW; break; case HSPOBJ_SFLOW: switch(tok->stok) { case HSPTOKEN_DNSSD: if((tok = expectDNSSD(sp, tok)) == NULL) return NO; break; case HSPTOKEN_DNSSD_DOMAIN: if((tok = expectDNSSD_domain(sp, tok)) == NULL) return NO; break; case HSPTOKEN_COLLECTOR: if((tok = expectToken(sp, tok, HSPTOKEN_STARTOBJ)) == NULL) return NO; newCollector(sp->sFlow->sFlowSettings_file); level[++depth] = HSPOBJ_COLLECTOR; break; case HSPTOKEN_SAMPLING: case HSPTOKEN_PACKETSAMPLINGRATE: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->samplingRate, 0, 65535)) == NULL) return NO; break; case HSPTOKEN_POLLING: case HSPTOKEN_COUNTERPOLLINGINTERVAL: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->pollingInterval, 0, 300)) == NULL) return NO; break; case HSPTOKEN_AGENTIP: if((tok = expectIP(sp, tok, &sp->sFlow->agentIP, NULL)) == NULL) return NO; break; case HSPTOKEN_AGENT: if((tok = expectDevice(sp, tok, &sp->sFlow->agentDevice)) == NULL) return NO; break; case HSPTOKEN_SUBAGENTID: if((tok = expectInteger32(sp, tok, &sp->sFlow->subAgentId, 0, HSP_MAX_SUBAGENTID)) == NULL) return NO; break; case HSPTOKEN_UUID: if((tok = expectUUID(sp, tok, sp->uuid)) == NULL) return NO; break; case HSPTOKEN_HEADERBYTES: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->headerBytes, 0, HSP_MAX_HEADER_BYTES)) == NULL) return NO; break; case HSPTOKEN_ULOGGROUP: if((tok = expectInteger32(sp, tok, &sp->sFlow->sFlowSettings_file->ulogGroup, 1, 32)) == NULL) return NO; break; case HSPTOKEN_ULOGPROBABILITY: if((tok = expectDouble(sp, tok, &sp->sFlow->sFlowSettings_file->ulogProbability, 0.0, 1.0)) == NULL) return NO; break; default: parseError(sp, tok, "unexpected sFlow setting", ""); return NO; break; } break; case HSPOBJ_COLLECTOR: { HSPCollector *col = sp->sFlow->sFlowSettings_file->collectors; switch(tok->stok) { case HSPTOKEN_IP: if((tok = expectIP(sp, tok, &col->ipAddr, (struct sockaddr *)&col->sendSocketAddr)) == NULL) return NO; break; case HSPTOKEN_UDPPORT: if((tok = expectInteger32(sp, tok, &col->udpPort, 1, 65535)) == NULL) return NO; break; default: parseError(sp, tok, "unexpected collector setting", ""); return NO; break; } } break; default: parseError(sp, tok, "unexpected state", ""); } } // OK we consumed all the tokens, but we still need to run some sanity checks to make sure // we have a usable configuration... int parseOK = YES; if(sp->sFlow == NULL) { myLog(LOG_ERR, "parse error in %s : sFlow not found", sp->configFile); parseOK = NO; } else { //////////////////////// sFlow ///////////////////////// if(sp->sFlow->agentIP.type == 0) { // it may have been defined as agent=<device> if(sp->sFlow->agentDevice) { SFLAdaptor *ad = adaptorListGet(sp->adaptorList, sp->sFlow->agentDevice); if(ad && ad->ipAddr.addr) { sp->sFlow->agentIP.type = SFLADDRESSTYPE_IP_V4; sp->sFlow->agentIP.address.ip_v4 = ad->ipAddr; } } } if(sp->sFlow->agentIP.type == 0) { // nae luck - try to automatically choose the first non-loopback IP address for(uint32_t i = 0; i < sp->adaptorList->num_adaptors; i++) { SFLAdaptor *adaptor = sp->adaptorList->adaptors[i]; // only the non-loopback devices should be listed here, so just take the first if(adaptor && adaptor->ipAddr.addr) { sp->sFlow->agentIP.type = SFLADDRESSTYPE_IP_V4; sp->sFlow->agentIP.address.ip_v4 = adaptor->ipAddr; // fill in the device that we picked too sp->sFlow->agentDevice = strdup(adaptor->deviceName); break; } } } if(sp->sFlow->agentIP.type == SFLADDRESSTYPE_IP_V4 && sp->sFlow->agentDevice == NULL) { // try to fill in the device field too (because we need to give that one to open vswitch). for(uint32_t i = 0; i < sp->adaptorList->num_adaptors; i++) { SFLAdaptor *adaptor = sp->adaptorList->adaptors[i]; if(adaptor && (adaptor->ipAddr.addr == sp->sFlow->agentIP.address.ip_v4.addr)) { sp->sFlow->agentDevice = strdup(adaptor->deviceName); break; } } } if(sp->sFlow->agentIP.type == 0) { // still no agentIP. That's a showstopper. myLog(LOG_ERR, "parse error in %s : agentIP not defined", sp->configFile); parseOK = NO; } if(sp->sFlow->sFlowSettings_file->numCollectors == 0 && sp->DNSSD == NO) { myLog(LOG_ERR, "parse error in %s : DNS-SD is off and no collectors are defined", sp->configFile); parseOK = NO; } for(HSPCollector *coll = sp->sFlow->sFlowSettings_file->collectors; coll; coll = coll->nxt) { //////////////////////// collector ///////////////////////// if(coll->ipAddr.type == 0) { myLog(LOG_ERR, "parse error in %s : collector has no IP", sp->configFile); parseOK = NO; } } if(sp->sFlow->sFlowSettings_file->ulogProbability > 0) { sp->sFlow->sFlowSettings_file->ulogSamplingRate = (uint32_t)(1.0 / sp->sFlow->sFlowSettings_file->ulogProbability); } } return parseOK; }
void MocParser::loadStringData(char *&stringdata) { stringdata = 0; QVarLengthArray<char, 1024> array; while (!input->atEnd()) { QByteArray line = readLine(); if (line == "};\n") { // end of data stringdata = new char[array.count()]; memcpy(stringdata, array.data(), array.count() * sizeof(*stringdata)); return; } int start = line.indexOf('"'); if (start == -1) parseError(); int len = line.length() - 1; line.truncate(len); // drop ending \n if (line.at(len - 1) != '"') parseError(); --len; ++start; for ( ; start < len; ++start) if (line.at(start) == '\\') { // parse escaped sequence ++start; if (start == len) parseError(); QChar c(QLatin1Char(line.at(start))); if (!c.isDigit()) { switch (c.toLatin1()) { case 'a': array.append('\a'); break; case 'b': array.append('\b'); break; case 'f': array.append('\f'); break; case 'n': array.append('\n'); break; case 'r': array.append('\r'); break; case 't': array.append('\t'); break; case 'v': array.append('\v'); break; case '\\': case '?': case '\'': case '"': array.append(c.toLatin1()); break; case 'x': if (start + 2 <= len) parseError(); array.append(char(line.mid(start + 1, 2).toInt(0, 16))); break; default: array.append(c.toLatin1()); fprintf(stderr, PROGRAMNAME ": warning: invalid escape sequence '\\%c' found in input", c.toLatin1()); } } else { // octal QRegExp octal(QLatin1String("([0-7]+)")); if (octal.indexIn(QLatin1String(line), start) == -1) parseError(); array.append(char(octal.cap(1).toInt(0, 8))); } } else { array.append(line.at(start)); } } parseError(); }