double postfixEvaluation(string pfix) { stack<double> operand; double result; double op1,op2; int i=0; int j; while (i<pfix.length()) { if (pfix[i]==',') { i++; } if (IsOperand(pfix[i]) || pfix[i]=='.') { j=1; result=(((double)pfix[i])-48); while (IsOperand(pfix[i+1])) { result*=10; result+=(((double)pfix[i+1])-48); i++; } if (pfix[i+1]=='.') { i++; while (IsOperand(pfix[i+1])) { result+=(((double)pfix[i+1])-48)/(pow(10,j++)); i++; } } operand.push(result); } else if(IsOperator(pfix[i])) { op2=operand.pop(); op1=operand.pop(); result=evaluate(op1, pfix[i], op2); operand.push(result); } i++; } return operand.pop(); }
/* * Show operators. Code from IrcBg, slightly modified. -kre */ static void ss_showopers(struct Luser *lptr, int ac, char **av) { int iCnt = 0; struct Luser *tempuser; RecordCommand("%s: %s!%s@%s SHOWOPERS", n_StatServ, lptr->nick, lptr->username, lptr->hostname); notice(n_StatServ, lptr->nick, "Currently online irc operators"); notice(n_StatServ, lptr->nick, "-------------------------------"); for (tempuser = ClientList; tempuser; tempuser = tempuser->next) { if (IsOperator(tempuser)) notice(n_StatServ, lptr->nick , "[%d] %s", ++iCnt,tempuser->nick ); } notice(n_StatServ, lptr->nick, "-------------------------------"); notice(n_StatServ, lptr->nick, " %d operators online.", iCnt); }
std::string BoolOp::InfixToPostfix(const std::string& infix) { std::string postfix ; std::stack<char> opstack; for (int i = 0; i< infix.size(); i++) { if (!IsOperator(infix[i])) { postfix +=infix[i]; continue; } postfix +=' '; if (opstack.empty() || (opstack.top() == '(' && infix[i] !=')')) opstack.push(infix[i]); else { while (OperatorPriority(infix[i]) <= OperatorPriority(opstack.top())) { if(opstack.top() != '(') { postfix +=opstack.top(); opstack.pop(); if (opstack.empty()) break ; }else break; } if (infix[i] != ')') opstack.push(infix[i]); else if (opstack.top() == '(') opstack.pop(); } } while (!opstack.empty()) { postfix+= opstack.top(); opstack.pop(); } return postfix; }
CToken* CBaseLexer::scan() { if (IsEOF())return 0; SkipSpaces(); SkipPreprocessor(); SkipSpaces(); CToken* tkn = 0; tkn = IsMacrosToken(); //ѕровер¤ет идентификатор макроса и "переключает" поток на чтение текста макроса if (tkn != 0)return tkn; tkn = IsComplexToken(); //выдел¤ю составные токены if (tkn != 0)return tkn; tkn = IsDigitalToken(); //выдел¤ю число (как целое, так и дробное) if (tkn != 0)return tkn; tkn = IsOperator(); //арифметический оператор if (tkn != 0)return tkn; tkn = IsWordToken(); //ключевое слово, идентификатор if (tkn != 0)return tkn; tkn = IsStringToken(); //строка, заключенна¤ в кавычки if (tkn != 0)return tkn; //всЄ остальное, что не удалось распознать tkn = new CToken(peek); peek = ' '; return tkn; }
bool Disasm::ParsePCL6() { uint8 byte; while (fStream->ReadUByte(byte)) { if (IsOperator(byte)) { if (!DecodeOperator(byte)) return false; } else if (IsDataType(byte)) { if (!PushData(byte)) return false; } else if (IsAttribute(byte)) { bool ok = DecodeAttribute(byte); ClearAttrs(); if (!ok) return false; } else if (IsEmbedData(byte)) { if (!DecodeEmbedData(byte)) return false; } else if (IsWhiteSpace(byte)) { // nothing to do } else if (IsEsc(byte)) { return true; } else { Error("Unknown byte in input stream"); return false; } } return true; }
asCScriptNode *asCParser::ParseExpression() { asCScriptNode *node = new asCScriptNode(snExpression); node->AddChildLast(ParseExprTerm()); if( isSyntaxError ) return node; for(;;) { sToken t; GetToken(&t); RewindTo(&t); if( !IsOperator(t.type) ) return node; node->AddChildLast(ParseExprOperator()); if( isSyntaxError ) return node; node->AddChildLast(ParseExprTerm()); if( isSyntaxError ) return node; } return 0; }
int Preprocessor::EvaluateConvertedExpression( DefineTable& define_table, LexemList& expr ) { std::vector<int> stack; while( expr.size() ) { Lexem lexem = expr.front(); expr.pop_front(); if( IsIdentifier( lexem ) ) { if( lexem.Type == Lexem::NUMBER ) stack.push_back( atoi( lexem.Value.c_str() ) ); else { LexemList ll; ll.push_back( lexem ); ExpandDefine( ll.begin(), ll.end(), ll, define_table ); LexemList out; bool success = ConvertExpression( ll, out ); if( !success ) { PrintErrorMessage( "Error while expanding macros." ); return 0; } stack.push_back( EvaluateConvertedExpression( define_table, out ) ); } } else if( IsOperator( lexem ) ) { if( lexem.Value == "!" ) { if( !stack.size() ) { PrintErrorMessage( "Syntax error in #if: no argument for ! operator." ); return 0; } stack.back() = stack.back() != 0 ? 0 : 1; } else { if( stack.size() < 2 ) { PrintErrorMessage( "Syntax error in #if: not enough arguments for " + lexem.Value + " operator." ); return 0; } int rhs = stack.back(); stack.pop_back(); int lhs = stack.back(); stack.pop_back(); std::string op = lexem.Value; if( op == "*" ) stack.push_back( lhs * rhs ); if( op == "/" ) stack.push_back( lhs / rhs ); if( op == "%" ) stack.push_back( lhs % rhs ); if( op == "+" ) stack.push_back( lhs + rhs ); if( op == "-" ) stack.push_back( lhs - rhs ); if( op == "<" ) stack.push_back( lhs < rhs ); if( op == "<=" ) stack.push_back( lhs <= rhs ); if( op == ">" ) stack.push_back( lhs > rhs ); if( op == ">=" ) stack.push_back( lhs >= rhs ); if( op == "==" ) stack.push_back( lhs == rhs ); if( op == "!=" ) stack.push_back( lhs != rhs ); if( op == "&&" ) stack.push_back( ( lhs != 0 && rhs != 0 ) ? 1 : 0 ); if( op == "||" ) stack.push_back( ( lhs != 0 || rhs != 0 ) ? 1 : 0 ); } } else { PrintErrorMessage( "Internal error on lexem " + lexem.Value + "." ); return 0; } } if( stack.size() == 1 ) return stack.back(); PrintErrorMessage( "Invalid #if expression." ); return 0; }
bool Preprocessor::ConvertExpression( LexemList& expression, LexemList& output ) { if( expression.empty() ) { PrintMessage( "Empty expression." ); return true; } // Convert to RPN std::vector<Lexem> stack; for( LLITR it = expression.begin(); it != expression.end(); ++it ) { PreprocessLexem( it, expression ); Lexem& lexem = *it; if( IsIdentifier( lexem ) ) { output.push_back( lexem ); } else if( IsOperator( lexem ) ) { while( stack.size() ) { Lexem& lex = stack.back(); if( IsOperator( lex ) && ( (OperLeftAssoc( lexem ) && ( OperPrecedence( lexem ) <= OperPrecedence( lex ))) || (OperPrecedence( lexem ) < OperPrecedence( lex )) ) ) { output.push_back( lex ); stack.pop_back(); } else break; } stack.push_back( lexem ); } else if( IsLeft( lexem ) ) { stack.push_back( lexem ); } else if( IsRight( lexem ) ) { bool foundLeft = false; while( stack.size() ) { Lexem& lex = stack.back(); if( IsLeft( lex ) ) { foundLeft = true; break; } else { output.push_back( lex ); stack.pop_back(); } } if( !foundLeft ) { PrintErrorMessage( "Mismatched parentheses." ); return false; } stack.pop_back(); } else { PrintErrorMessage( "Unknown token: " + lexem.Value ); return false; } } // input end, flush the stack while( stack.size() ) { Lexem& lex = stack.back(); if( IsLeft( lex ) || IsRight( lex ) ) { PrintErrorMessage( "Mismatched parentheses." ); return false; } output.push_back( lex ); stack.pop_back(); } return true; }
bool Preprocessor::IsIdentifier( const Lexem& lexem ) { return ( !IsOperator( lexem ) && lexem.Type == Lexem::IDENTIFIER ) || lexem.Type == Lexem::NUMBER; }
int Parser::Compute(const char *line) { static const char opp[] = { '<', '=', '>', 'X'}; enum { STAT_INIT, STAT_OPR1, STAT_OPR2, STAT_OPND, STAT_DEFINED, /* defined */ STAT_DEFINED1, /* defined( */ STAT_DEFINED2, /* defined(X */ } state; CC_STACK<sym_t> opr_stack; CC_STACK<SynToken> opnd_stack; sym_t last_opr = SSID_SHARP; SynToken last_token; char sign; const char *symbol = NULL; LOG_VERB dml = LOGV_DEBUG; CC_STRING expansion; if(!gvar_preprocess_mode) { /* * Keep `#if 0' blocks which are usually user comments. */ char *copied_line = strdup(line); const char *first = strtok(copied_line, " \t"); int ignore = 0; /* Simple code and work properly in most cases */ if(first && first[0] == '0') ignore = 1; free(copied_line); if(ignore) return TSV_X; } expansion = ExpandLine(intab, false, line, errmsg); if( !errmsg.isnull() ) { return TSV_X; } ReadReq req(expansion.c_str()); SynToken& token = req.token; opr_stack.push(SSID_SHARP); log(dml, "PUSH OPR: #\n"); sign = 0; state = STAT_OPR1; while(1) { sym_t opr; const char *last_pos = req.cp; int ret; ret = ReadToken(intab, &req, false); if( ret == 0 ) break; else if( ret < 0 ) goto error; if( token.attr == SynToken::TA_CHAR ) token.attr = SynToken::TA_INT; if( sign != 0 ) { if(token.attr != SynToken::TA_UINT && token.id != SSID_DEFINED) { errmsg.Format("%s following %c", TR(intab,token.id), sign); goto error; } if(sign == '-') { token.attr = SynToken::TA_INT; token.i32_val = -token.i32_val; } sign = 0; } else if( (token.id == SSID_ADDITION || token.id == SSID_SUBTRACTION) && CheckPrevOperator(last_opr)) { sign = token.id == SSID_ADDITION ? '+' : '-'; goto next; } switch(state) { case STAT_INIT: if(IsOperator(token.id)) state = STAT_OPR1; else if(token.id == SSID_DEFINED) state = STAT_DEFINED; else if(token.attr == SynToken::TA_IDENT) state = STAT_OPND; break; case STAT_OPND: if(IsOperator(token.id)) state = STAT_OPR1; else { errmsg = "Adjacent operands"; goto error; } break; case STAT_OPR1: if(IsOperator(token.id)) state = STAT_OPR2; else if(token.id == SSID_DEFINED) state = STAT_DEFINED; else state= STAT_INIT; break; case STAT_OPR2: if(IsOperator(token.id)) { } else if(token.id == SSID_DEFINED) state = STAT_DEFINED; else state = STAT_INIT; break; case STAT_DEFINED: if(token.id == SSID_LEFT_PARENTHESIS) state = STAT_DEFINED1; else if(token.attr == SynToken::TA_IDENT) { CheckSymbolDefined(last_pos, false, &token); if(!errmsg.isnull()) goto error; state = STAT_INIT; } break; case STAT_DEFINED1: if(token.attr == SynToken::TA_IDENT) { state = STAT_DEFINED2; symbol = last_pos; } else { errmsg = "Syntax error: "; goto error; } break; case STAT_DEFINED2: if(token.id == SSID_RIGHT_PARENTHESIS) { CheckSymbolDefined(symbol, false, &token); if(!errmsg.isnull()) goto error; state = STAT_INIT; opnd_stack.push(token); opr = token.id; goto next; } else { errmsg = "Unmatched ("; goto error; } break; } if(state == STAT_DEFINED || state == STAT_DEFINED1 || state == STAT_DEFINED2) goto next; if( token.id == SynToken::TA_UINT || token.id == SynToken::TA_INT ) log(dml, "Current: %u\n", token.u32_val); else log(dml, "Current: %s\n", TR(intab,token.id)); // log(dml, "OPR Stack: \n", opr_stack); // log(dml, "OPND Stack: \n", opnd_stack); opr = token.id; if( IsOperator(opr) ) { sym_t opr0; int result; again: opr0 = opr_stack.top(); result = intab->opMat.Compare(opr0, opr); log(dml, "Compare: %s %c %s\n", TR(intab,opr0),opp[1+result],TR(intab,opr)); switch(result) { case _EQ: opr_stack.pop(opr0); break; case _GT: opr_stack.pop(opr0); if( ! CalculateOnStackTop(opr0, opnd_stack, opr_stack) ) { goto error; } goto again; case _LT: opr_stack.push(opr); break; case _XX: errmsg.Format("Cannot compare \"%s\" and \"%s\"", TR(intab,opr0), TR(intab,opr)); log(LOGV_ERROR, "*ERROR* %s\n", errmsg.c_str()); goto error; } } else { opnd_stack.push(token); } next: last_opr = opr; } do { sym_t opr0; int result; if( ! opr_stack.pop(opr0) ) goto error; result = intab->opMat.Compare(opr0, SSID_SHARP); log(dml, "Compare: %s %c #\n", TR(intab,opr0),opp[result]); switch(result) { case _EQ: break; case _GT: if( ! CalculateOnStackTop(opr0, opnd_stack, opr_stack) ) { goto error; } break; default: log(LOGV_ERROR, "%s:%u: Bad expression\n", __func__, __LINE__); errmsg = "[1] Bad expression"; goto error; } } while( opr_stack.size() != 0 ); if( opnd_stack.size() != 1 ) { log(LOGV_ERROR, "%s:%u: Bad expression\n", __func__, __LINE__); errmsg = "[2] Bad expression"; goto error; } if( opnd_stack.top().attr == SynToken::TA_IDENT ) { if( gvar_preprocess_mode ) { return TSV_0; } return TSV_X; } log(dml, "Numberic Value: %u\n", opnd_stack.top().i32_val);; return !!opnd_stack.top().i32_val; error: log(LOGV_ERROR, "*Error* %s\n", errmsg.c_str()); return gvar_preprocess_mode ? TSV_0 : TSV_X; }
bool CArithWordAnalyser::GenerateWord(CCalculator& Cal){ if(*m_pCurrentLocation == ' '){ //跳过空格 do { m_pCurrentLocation++; } while(*m_pCurrentLocation == ' '); } //如果是操作符 if(IsOperator(*m_pCurrentLocation)){ //如果是单目的,转化成双目的(单目操作符必须用()括起来) if(((*m_pCurrentLocation == '+')||(*m_pCurrentLocation == '-'))&&(*m_pLastLocation == '(')){ Cal.m_Words[m_CurrentWordNum][0] = '0'; // -10 = 0-10 ; +10 = 0+10 Cal.m_WordsAttribute[m_CurrentWordNum] = 0; //为数值,属性为0 Cal.m_nNumWords++; m_CurrentWordNum++; } Cal.m_Words[m_CurrentWordNum][0] = *m_pCurrentLocation;//加入单词表 Cal.m_WordsAttribute[m_CurrentWordNum] = 2; //操作符,属性为 2 m_CurrentWordNum++; m_pLastLocation = m_pCurrentLocation; //向后移进 m_pCurrentLocation++; return true; } else if(IsNumber(*m_pCurrentLocation)){ int i ; i = 0; do { Cal.m_Words[m_CurrentWordNum][i++] = *m_pCurrentLocation; m_pLastLocation = m_pCurrentLocation; m_pCurrentLocation++; }while(IsNumber(*m_pCurrentLocation)); //Cal.m_WordsAttribute[m_CurrentWordNum]不变为0,为整数 if(*m_pCurrentLocation == '.') //小数点 { Cal.m_Words[m_CurrentWordNum][i++] = *m_pCurrentLocation; m_pCurrentLocation++; if(!IsNumber(*m_pCurrentLocation)) //小数点后应该为数字 return false; while(IsNumber(*m_pCurrentLocation)) { Cal.m_Words[m_CurrentWordNum][i++] = *m_pCurrentLocation; m_pLastLocation = m_pCurrentLocation; m_pCurrentLocation++; } //数的属性为 0,不变 //Cal.m_WordsAttribute[m_CurrentWordNum]不变为0,为整数 //Cal.m_WordsAttribute[m_CurrentWordNum] = 1; //小数 属性为 1 m_CurrentWordNum ++; return true; } else { m_CurrentWordNum ++; return true; } } else if(IsAlpha(*m_pCurrentLocation)){ int i ; i = 0; do { Cal.m_Words[m_CurrentWordNum][i++] = *m_pCurrentLocation; m_pLastLocation = m_pCurrentLocation; m_pCurrentLocation++; }while(IsAlpha(*m_pCurrentLocation)); Cal.m_WordsAttribute[m_CurrentWordNum] = 1;//变量 m_CurrentWordNum++; } else //若每个单词不以以上形式开始,则词法错误 return false; }
bool ExpressionTree::SetInfixExpression(const char* inFix) { cout << "Infix:" << inFix << "\n"; vector<ItemTokenInfo>().swap(vecPostfixResult); //vecPostfixResult.shrink_to_fit(); CTokenParser parser; parser.PutExpression((char*)inFix); stack<ItemTokenInfo> opStack; string postFixString = ""; bool bErrorOccurred = false; while (1) { ItemTokenInfo token; memset(&token, 0x00, sizeof(token)); if (!parser.GetToken(&token)) { bErrorOccurred = true; break; } if (0 == token.nLength) { break; } #ifdef _DEBUG_MORE_ cout << __LINE__ << ": token.nLength=" << token.nLength << " token.nType=" << token.nType << " token.strTokenValue= " << token.strValue << "\n"; #endif if (IsUserFunction(&token)) { opStack.push(token); //no precedence between functions } else if (IsOperand(&token)) { postFixString += " "; postFixString += token.strValue; vecPostfixResult.push_back(token); } else if (IsOperator(&token)) { while ( !opStack.empty() && LEFT_PARENTHESIS != opStack.top().nDetailedType && GetOperatorPrecedence(&opStack.top(), &token) <= 0 ) { postFixString += " "; postFixString += opStack.top().strValue; vecPostfixResult.push_back(opStack.top()); opStack.pop(); } opStack.push(token); } else if (COMMA == token.nDetailedType && token.bThisTokenBelongsToTheUserFunctions ) // SumInt(1+1, 2) { while (!opStack.empty() && LEFT_PARENTHESIS != opStack.top().nDetailedType ) { postFixString += " "; postFixString += opStack.top().strValue; vecPostfixResult.push_back(opStack.top()); opStack.pop(); } } else if (LEFT_PARENTHESIS == token.nDetailedType) { opStack.push(token); } else if (RIGHT_PARENTHESIS == token.nDetailedType) { //pop till starting '(' while (!opStack.empty()) { if (LEFT_PARENTHESIS == opStack.top().nDetailedType) { if (token.bThisTokenBelongsToTheUserFunctions) { //pop till starting function name opStack.pop(); if (opStack.top().nDetailedType == LEFT_PARENTHESIS) { // (SumInt(1,1)) opStack.pop(); } else { postFixString += " "; postFixString += opStack.top().strValue; //function name vecPostfixResult.push_back(opStack.top()); opStack.pop(); } break; } else { opStack.pop(); break; } } postFixString += " "; postFixString += opStack.top().strValue; vecPostfixResult.push_back(opStack.top()); opStack.pop(); } } //RIGHT_PARENTHESIS } if (bErrorOccurred) { return false; } while (!opStack.empty()) { postFixString += " "; postFixString += opStack.top().strValue; vecPostfixResult.push_back(opStack.top()); opStack.pop(); } cout << "Postfix is: " << postFixString << endl; return BuildExpressionTree(); }
PNode CreateInfixTree(char* exp) { // create a dummy root with minimal precedence // its content is trivial PNode root = CreateNode("0"); root->precedence = 0; // the previous operand of current operator PNode preOperand = NULL; // the previous operator of current operator PNode preOperator = root; // the impact of preceding parenthesis, if any int correction = 0; int i = 0; char* token = strtok( exp, " " ); while(token) { if (IsOperand(token)) { preOperand = CreateNode(token); } else if (IsOperator(token)) { printf("entrou em eh operador\n"); PNode p = CreateNode(token); p->precedence = GetPrecedence(token) + correction; if (p->precedence > preOperator->precedence) { p->left = preOperand; preOperator->right = p; p->parent = preOperator; } else { preOperator->right = preOperand; PNode q = preOperator->parent; while (p->precedence <= q->precedence) q = q->parent; p->left = q->right; q->right = p; p->parent = q; } preOperand = NULL; preOperator = p; }//else if (IsOperator(exp[i]) else if (IsLeftParenthesis(token)) { correction += 2; } else if (IsRightParenthesis(token)) { correction -= 2; } else { printf("illegal token found: %c\n", exp[i]); break; } token = strtok(NULL, " "); }//while if (preOperand == NULL) printf("illegal expression: cannot end with operator: %s\n", preOperator->data); else preOperator->right = preOperand; // delete dummy root PNode realRoot = root->right; //delete root; free(root); if (realRoot) realRoot->parent = NULL; return realRoot; }
static void g_gnote(struct Luser *lptr, int ac, char **av) { int cnt, alen, bad, ii; int all, ops, opers, admins; char *message; char argbuf[MAXLINE + 1]; char temp[MAXLINE * 2]; struct Luser *tempuser; struct Userlist *userptr; if (!GlobalNotices) { notice(n_Global, lptr->nick, "Global notices are disabled"); return; } if (ac < 2) { notice(n_Global, lptr->nick, "Syntax: \002GNOTE [options] <message>\002"); return; } all = 0; ops = 0; opers = 0; admins = 0; message = NULL; for (cnt = 1; cnt < ac; ++cnt) { alen = strlen(av[cnt]); if (!ircncmp(av[cnt], "-all", alen)) all = 1; else if (!ircncmp(av[cnt], "-ops", alen)) ops = 1; else if (!ircncmp(av[cnt], "-opers", alen)) opers = 1; else if (!ircncmp(av[cnt], "-admins", alen)) admins = 1; else { message = GetString(ac - cnt, av + cnt); break; } } if (!message) { notice(n_Global, lptr->nick, "No message specified"); return; } if (!all && !ops && !opers && !admins) all = 1; /* -all is the default */ *argbuf = '\0'; if (all) strcat(argbuf, "-all "); if (ops) strcat(argbuf, "-ops "); if (opers) strcat(argbuf, "-opers "); if (admins) strcat(argbuf, "-admins "); ircsprintf(temp, "%s%s", argbuf, message); strncpy(argbuf, temp, MAXLINE); argbuf[MAXLINE] = '\0'; RecordCommand("%s: %s!%s@%s GNOTE %s", n_Global, lptr->nick, lptr->username, lptr->hostname, argbuf); cnt = 0; for (tempuser = ClientList; tempuser; tempuser = tempuser->next) { if (FindService(tempuser)) continue; if (!ircncmp(Me.name, tempuser->server->name, strlen(tempuser->server->name))) continue; bad = 0; if (!all) { if (opers && !IsOperator(tempuser)) bad = 1; else { if (tempuser->flags & L_OSREGISTERED) ii = 1; else ii = 0; userptr = GetUser(ii, tempuser->nick, tempuser->username, tempuser->hostname); if (ops && !IsOper(userptr)) bad = 1; else if (admins && !IsAdmin(userptr)) bad = 1; } } if (bad) continue; notice(n_Global, tempuser->nick, message); ++cnt; } notice(n_Global, lptr->nick, "Message sent (%d match%s)", cnt, (cnt == 1) ? "" : "es"); MyFree(message); } /* g_gnote() */
BOOL CMatrixDoc::StringsToMatrixs(CString * pVar,CTypedPtrList<CObList,CArrayMatrix *> & m_List,int num) { for(int i=0;i<num;i++) { pVar[i].TrimLeft(); pVar[i].TrimRight(); if(pVar[i]==_T("")) return FALSE; if(IsCharAlpha(pVar[i][0]))//pVar[i]是变量 { int nVarNum=m_VariablePtrList.GetCount(); POSITION pos=m_VariablePtrList.GetHeadPosition(); POSITION tippos=NULL; for(int j=0;j<nVarNum;j++) { CString sVarName=pVar[i]; sVarName.TrimRight("\'"); sVarName.TrimLeft("~"); CArrayMatrix * pt=m_VariablePtrList.GetAt(pos); if(pt->GetName()==sVarName) {tippos=pos;break;} m_VariablePtrList.GetNext(pos); } if(tippos==NULL) return FALSE; else { CArrayMatrix *pMatrix=new CArrayMatrix; *pMatrix=*(m_VariablePtrList.GetAt(tippos)); //对多次求转置的处理,比如A''''的求值 { int len=lstrlen(pVar[i]); int index=len-1; if(pVar[i][index]==TCHAR('\'')) { while(pVar[i][index]==TCHAR('\'')&&index>0) { (*pMatrix)=pMatrix->T(); index--; } } } m_List.AddTail(pMatrix); } } else if(pVar[i][0]==TCHAR('~'))//处理~~~A的值 { int glen=lstrlen(pVar[i]); int gnum=0; for(int g=0;g<glen&&pVar[i][g]==TCHAR('~');g++) gnum++; if(glen==num) return FALSE; CString Var=pVar[i].Right(glen-gnum); int nVarNum=m_VariablePtrList.GetCount(); POSITION pos=m_VariablePtrList.GetHeadPosition(); POSITION tippos=NULL; for(int j=0;j<nVarNum;j++) { CArrayMatrix * pt=m_VariablePtrList.GetAt(pos); if(pt->GetName()==Var) {tippos=pos;break;} m_VariablePtrList.GetNext(pos); } if(tippos==NULL) return FALSE; else { CArrayMatrix *pMatrix=new CArrayMatrix; *pMatrix=*(m_VariablePtrList.GetAt(tippos)); int k=gnum%2; if(k==1) { if(!(*pMatrix).CanContrary()) {delete pMatrix;return FALSE;} (*pMatrix)=~(*pMatrix); } m_List.AddTail(pMatrix); } } else { if(IsCharAlphaNumeric(pVar[i][0])||(IsOperator(pVar[i][0])&&IsCharAlphaNumeric(pVar[i][1]))) { CString sName="hyx="; sName=sName+pVar[i]; sName=sName+";"; CArrayMatrix * Ptr=new CArrayMatrix; if(!Ptr->ProcessInput(sName)) {delete Ptr;return FALSE;} m_List.AddTail(Ptr); } else return FALSE; } } return TRUE; }
int CMatrixDoc::GetVariableNum(const CString &m,CString * & pVar) { pVar=NULL; int CharNum=0; bool bSign=true; int num=0; int len=lstrlen(m); { for(int pos=0;pos<len;pos++) { if(IsCharAlpha(m[pos])) CharNum++; } } if(CharNum==0) { pVar=new CString[1]; *pVar=m; pVar->TrimLeft(); pVar->TrimRight(); return 1; } for(int i=0;i<len;i++) { if(!IsOperator(m[i])) { if(bSign) { num++; bSign=false; } else continue; } else bSign=true; } if(num==0) return num; else { int tpnum=0; pVar=new CString[num]; CString temp; int slen=0; bSign=true; for(int i=0;i<len;i++) { if(!IsOperator(m[i])) { if(bSign) { tpnum++; if(tpnum==num) { int j=i; int number=0; CString stp; while(j<len&&!IsOperator(m[i])) { stp.GetBufferSetLength(number+1); stp.SetAt(number,m[j]); number++; j++; } pVar[num-1]=stp; } else if(tpnum>1) { pVar[tpnum-1]=temp; } temp=_T(""); slen=1; temp.GetBufferSetLength(slen); temp.SetAt(0,m[i]); if(i<len-1&&IsOperator(m[i+1])) pVar[tpnum-1]=temp; bSign=false; } else { slen++; temp.GetBufferSetLength(slen); temp.SetAt(slen-1,m[i]); } } else bSign=true; } } return num; }
BOOL CMatrixDoc::GetResult(const CString &data,CArrayMatrix & matrix) { //在这可以通过修改data字符串和m_VariablePtrList变量链表来实现 //具体方法是首先假如data是包含多个运算符的 CString sDataString=data; sDataString.TrimLeft("\n"); sDataString.TrimRight("\n"); CString *pVar; CArrayMatrix result; bool ok; int VarNum=GetVariableNum(sDataString,pVar); if(VarNum==0) return FALSE; CTypedPtrList<CObList,CArrayMatrix *> tpVarList; if(!StringsToMatrixs(pVar,tpVarList,VarNum)) { if(pVar!=NULL) delete []pVar; return FALSE; } TurnString(sDataString); //表达式求值 { sDataString=sDataString+"#"; CStack<TCHAR> OPTR; CStack<CArrayMatrix *> OPND; OPTR.Push('#'); int index=0; TCHAR c=sDataString[index]; int nVarIndex=0; while(c!=TCHAR('#')||OPTR.GetTop()!=TCHAR('#')) { if(!IsOperator(c)) { POSITION pos=tpVarList.GetHeadPosition(); CArrayMatrix * pt=NULL; for(int i=0;i<=nVarIndex&&i<tpVarList.GetCount();i++) { pt=tpVarList.GetAt(pos); tpVarList.GetNext(pos); } if(pt==NULL) return FALSE; OPND.Push(pt); nVarIndex++; index++; c=sDataString[index]; } else { switch(Precede(OPTR.GetTop(),c)) { case -1: { OPTR.Push(c); index++; c=sDataString[index]; break; } case 0: { TCHAR x; OPTR.Pop(x); index++; c=sDataString[index]; break; } case 1: { TCHAR theta; OPTR.Pop(theta); CArrayMatrix * b=NULL; CArrayMatrix * a=NULL; OPND.Pop(b); OPND.Pop(a); OPND.Push(Operate(a,theta,b,ok)); break; } } } } result=*(OPND.GetTop()); } //销毁tpvarlist变量里面的东西 { POSITION pos=tpVarList.GetHeadPosition(); int len=tpVarList.GetCount(); for(int i=0;i<len;i++) { CArrayMatrix * tp=tpVarList.GetAt(pos); delete tp; tpVarList.GetNext(pos); } tpVarList.RemoveAll(); } if(pVar!=NULL) delete []pVar; if(!ok) return FALSE; matrix=result; return TRUE; }
string Eval (const string& o_operation) { string operation = OperatorsToFunctionCalls (o_operation); //really redundant operation = StripWhitespaceBE (operation); operation = StripParens (operation); //auto operands = SeparateOperands (operation); operand count has to be one at this point list <string> operands = SeparateOperands (operation); if (operands.size() == 1) { // literal value if (IsNumericValue (operation)) return tostr (NumEval (operation)); //maybe return operation directly function_t fcode; string function_name = GetFunctionName(operation); //function if (IsFunctionCall (operation)) { SeparateArguments (StripB (function_name, operation)); return run_function (function_name, SeparateArguments (StripB (function_name, operation))); } // if // only one operand at this point, which is a variable if (IsVariable (operation)) return GetVariable (operands.front())-> Value (); // check for Literals // TODO: OperationType does so many unncessasry checks (for variables, waveforms, etc) // its better to figure out some way to skip those checks type_t optype = OperationType (operation); if (optype == TYPE_TEXT or optype == TYPE_NUM) return operation; // NaV: Not a value if (operation == "NaV") error ("operation did not return a valid value"); // Unknown object error ("object `" + operation + "' is unsupported."); } // if else { string result = ""; for (list<string>::iterator o = operands.begin(); o != operands.end(); o++) { if (IsOperator (*o)) { result += *o; } /* if */ else { result += Eval (*o); } /* else */ } /* for */ return StripE (" ", result); } /* else */ } /* eval */
bool dNonDeterministicFiniteAutonata::CheckInsertConcatenation (int left, int right) const { bool test = (((!IsOperator(left)) || (left == m_closeParentesis) || (left == m_closeSquareBrakect) || (left == m_zeroOrMore) || (left == m_oneOrMore) || (left == m_zeroOrOne) || (left == m_balancedCharacterExpresion)) && ((!IsOperator(right))|| (right == m_openParentesis) || (right == m_openSquareBrakect))); return test; }
void CMatrixDoc::ProcInput(const CString &all) { CString DisplayData=_T(""); CString temp=all;//包含了';'号 CString sName=_T(""); int IsError=100;//1代表无此变量;2代表变量显示错误 //3代表赋值有误;4代表字符串变量信息输入有误 //5格式输入不合法 if(CArrayMatrix::SetStringName(temp,sName)) //输入的第一个数组 { CArrayMatrix::ProcString(temp); CString result=temp; temp=temp+";"; int number=0; for(int i=0;i<lstrlen(temp);i++) { if(temp[i]!=TCHAR('\n')&&temp[i]!=TCHAR(';')&&temp[i]!=TCHAR(' ')&&!IsOperator(temp[i])) number++; } if(number==0||temp.IsEmpty()) { CArrayMatrix * p; if(!IsFood(sName,p)) IsError=1; else { if(!p->DisPlay(DisplayData)) IsError=2; else IsError=-1; } } else { CArrayMatrix *pt; if(IsFood(sName,pt)) { CArrayMatrix tp; if(GetResult(result,tp)) { *pt=tp; IsError=0; } else { IsError=3; } } else { pt=new CArrayMatrix; if(!(pt->SetName(sName)&&GetResult(result,*pt))) {IsError=4;delete pt;} else { m_VariablePtrList.AddTail(pt); IsError=0; } } } } else IsError=5; //打开剪贴板 if(IsError!=0) { switch(IsError) { case 1: { DisplayData="\n!!!变量未定义,不存在此变量!;"; break; } case 2: { DisplayData="\n!!!变量未初始化,或则变量内无数据!;"; break; } case 3: { DisplayData="\n!!!变量赋值错误,赋值格式不合法!;"; break; } case 4: { DisplayData="\n!!!初始化新变量时,字符输入不合法!;"; break; } case 5: { DisplayData="\n!!!变量名输入有误!;"; break; } case -1: { CString tpok="\n"; tpok=tpok+sName; tpok=tpok+"=\n"; DisplayData.TrimLeft("\n"); DisplayData.TrimLeft("\xd\xa"); DisplayData=tpok+DisplayData; break; } default: { DisplayData="\n系统出错,请马上推出程序!;"; } } } //获得视图的指针 POSITION pos=GetFirstViewPosition(); CView *p=GetNextView(pos); // if(IsError!=0) { DisplayData.Replace("\n","\xd\xa"); int len=lstrlen(DisplayData); HGLOBAL hGlobal; PTSTR pGlobal; hGlobal=GlobalAlloc(GHND|GMEM_SHARE,len*sizeof(TCHAR)+1); pGlobal=(PTSTR)GlobalLock(hGlobal); for(int g=0;g<len;g++) *pGlobal++=DisplayData[g]; GlobalUnlock(hGlobal); p->OpenClipboard(); EmptyClipboard(); SetClipboardData(CF_TEXT,hGlobal); CloseClipboard(); } else { p->OpenClipboard(); EmptyClipboard(); CloseClipboard(); } }
bool ExpressionTree::BuildExpressionTree() { nDepthOfTree = 0; DeleteExpressionTree(root_node); stack<expression_node*> treeNodeStack; stack<expression_node*> funcArgsNodeStack; for (vector<ItemTokenInfo>::iterator it = vecPostfixResult.begin(); it != vecPostfixResult.end(); ++it) { //------------------------------------------------------- if (IsUserFunction(&(*it))) { int nArgCnt = it->userFuncInfo.ntotalInputArgCnt; if (nArgCnt == 0) { expression_node* node = CreateTreeNode(); expression_node* nodeEmptyR = CreateTreeNode(); //empty node expression_node* nodeEmptyL = CreateTreeNode(); //empty node nodeEmptyR->nType = NODE_EMPTY; nodeEmptyL->nType = NODE_EMPTY; node->right = nodeEmptyR; node->left = nodeEmptyL; node->nType = it->nType; node->nDetailedType = it->nDetailedType; node->expressionResult.nResultType = it->nType; node->expressionResult.nResultDetailedType = it->nDetailedType; memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo)); treeNodeStack.push(node); } else if (nArgCnt == 1) { int nArgType = it->userFuncInfo.nFuncArgsTypes[0]; if (treeNodeStack.empty()) //20140314 { cout << "ERROR : Wrong Expression!!\n"; return false; } expression_node* nodeStack = treeNodeStack.top(); if (FUNC_ARG_STR == nArgType) { userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeStack->strVal); userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeStack->expressionResult.strResult ); } treeNodeStack.pop(); expression_node* nodeEmpty = CreateTreeNode(); //empty node nodeEmpty->nType = NODE_EMPTY; expression_node* node = CreateTreeNode(); node->left = nodeStack ; node->right = nodeEmpty; node->nType = it->nType; node->nDetailedType = it->nDetailedType; node->expressionResult.nResultType = it->nType; node->expressionResult.nResultDetailedType = it->nDetailedType; memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo)); treeNodeStack.push(node); } else if (nArgCnt == 2) { int nArgType = it->userFuncInfo.nFuncArgsTypes[1]; // 1 if (treeNodeStack.empty()) //20140314 { //Error!!! cout << "ERROR : Wrong Expression!!\n"; return false; } expression_node* nodeArgR = treeNodeStack.top(); if (FUNC_ARG_STR == nArgType) { userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeArgR->strVal); userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeArgR->expressionResult.strResult ); } treeNodeStack.pop(); nArgType = it->userFuncInfo.nFuncArgsTypes[0]; if (treeNodeStack.empty()) //20140314 { //Error!!! cout << "ERROR : Wrong Expression!!\n"; return false; } expression_node* nodeArgL = treeNodeStack.top(); if (FUNC_ARG_STR == nArgType) { userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeArgL->strVal); userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeArgL->expressionResult.strResult ); } treeNodeStack.pop(); expression_node* node = CreateTreeNode(); node->right = nodeArgR; //스택에서 먼저 나온것이 오른쪽. node->left = nodeArgL; node->nType = it->nType; node->nDetailedType = it->nDetailedType; node->expressionResult.nResultType = it->nType; node->expressionResult.nResultDetailedType = it->nDetailedType; memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo)); treeNodeStack.push(node); } else if (nArgCnt > 2) { expression_node* node = CreateTreeNode(); expression_node* nodeRight = NULL; for (int i = 0; i < nArgCnt; i++) { int nArgType = it->userFuncInfo.nFuncArgsTypes[nArgCnt -i -1]; //args type XXX //'1','2','3' 경우 '3','2',1' 순서로 pop // StrCat3 // '1' '2','3' if (i == nArgCnt - 1) // last pop -> left { if (treeNodeStack.empty()) //20140314 { //Error!!! cout << "ERROR : Wrong Expression!!\n"; return false; } expression_node* nodeLeft = treeNodeStack.top(); treeNodeStack.pop(); if (FUNC_ARG_STR == nArgType) { userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeLeft->strVal); userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeLeft->expressionResult.strResult ); } node->left = nodeLeft; } else if (i == nArgCnt - 2) // right { if (treeNodeStack.empty()) //20140314 { //Error!!! cout << "ERROR : Wrong Expression!!\n"; return false; } nodeRight = treeNodeStack.top(); treeNodeStack.pop(); if (FUNC_ARG_STR == nArgType) { userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeRight->strVal); userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeRight->expressionResult.strResult ); } } else { if (treeNodeStack.empty()) //20140314 { //Error!!! cout << "ERROR : Wrong Expression!!\n"; return false; } expression_node* nodeForMore2Args = treeNodeStack.top(); treeNodeStack.pop(); if (FUNC_ARG_STR == nArgType) { userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeForMore2Args->strVal); userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeForMore2Args->expressionResult.strResult ); } funcArgsNodeStack.push(nodeForMore2Args); } }//for expression_node* nodePosForFuncArgs = NULL; while (!funcArgsNodeStack.empty() ) { if (nodePosForFuncArgs == NULL) { nodePosForFuncArgs = nodeRight->rightSiblingForMore2funcArgs = funcArgsNodeStack.top(); } else { nodePosForFuncArgs->rightSiblingForMore2funcArgs = CreateTreeNode(); nodePosForFuncArgs->rightSiblingForMore2funcArgs = funcArgsNodeStack.top(); nodePosForFuncArgs = nodePosForFuncArgs->rightSiblingForMore2funcArgs; } funcArgsNodeStack.pop(); } node->right = nodeRight; node->nType = it->nType; node->nDetailedType = it->nDetailedType; node->expressionResult.nResultType = it->nType; node->expressionResult.nResultDetailedType = it->nDetailedType; memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo)); treeNodeStack.push(node); } } //------------------------------------------------------- else if (IsOperand(&(*it))) { expression_node* node = CreateTreeNode(); if (NODE_NUMBER == it->nType) { if (NUMBER_LONG == it->nDetailedType) { node-> nLongValue = atol(it->strValue); node->expressionResult.nResultLong = node->nLongValue; } else if (NUMBER_FLOAT == it->nDetailedType) { node-> nFloatValue = (float)atof(it->strValue); node->expressionResult.nResultFloat = node->nFloatValue; } else { cout << "Error \n"; } } else { memcpy(&node->strVal, it->strValue, sizeof(node->strVal)); memcpy ( &node->expressionResult.strResult, it->strValue, sizeof( node->expressionResult.strResult ) ); } node->nType = it->nType; node->nDetailedType = it->nDetailedType; node->expressionResult.nResultType = it->nType; node->expressionResult.nResultDetailedType = it->nDetailedType; treeNodeStack.push(node); } //------------------------------------------------------- else if (IsOperator(&(*it))) { if (treeNodeStack.empty()) //2-14-314 { return false; } expression_node* node1 = treeNodeStack.top(); treeNodeStack.pop(); if (treeNodeStack.empty()) //2-14-314 { return false; } expression_node* node2 = treeNodeStack.top(); treeNodeStack.pop(); expression_node* node = CreateTreeNode(); node->right = node1; node->left = node2; node->nType = it->nType; node->nDetailedType = it->nDetailedType; node->expressionResult.nResultType = it->nType; node->expressionResult.nResultDetailedType = it->nDetailedType; treeNodeStack.push(node); } else { cout << "-- Not Operator/Operand" << "\n"; } } if (treeNodeStack.empty()) //20140314 { cout << "ERROR : Wrong Expression!!\n"; return false; } root_node = treeNodeStack.top(); treeNodeStack.pop(); return true; }
void UpdateUserModes(struct Luser *user, char *modes) { int PLUS = 1; int umode; unsigned int ii; if (!modes || !user) return; for (ii = 0; ii < strlen(modes); ii++) { if (modes[ii] == '+') { PLUS = 1; continue; } if (modes[ii] == '-') { PLUS = 0; continue; } umode = 0; if (modes[ii] == 'i') umode = UMODE_I; if (modes[ii] == 's') umode = UMODE_S; if (modes[ii] == 'w') umode = UMODE_W; if (modes[ii] == 'o') umode = UMODE_O; #ifdef DANCER if (modes[ii] == 'e') if (PLUS) { struct NickInfo* realptr = FindNick(user->nick); if (realptr) { realptr->flags |= NS_IDENTIFIED; RecordCommand("User %s has +e umode, marking as identified",user->nick); umode = UMODE_E; } else { /* Blech, who is screwing with us? */ toserv(":%s MODE %s -e\r\n", Me.name, user->nick); RecordCommand("User %s has +e umode but is not known to me, setting -e", user->nick); umode = 0; } } #endif /* DANCER */ if (!umode) continue; if (PLUS) { if ((umode == UMODE_O) && (!IsOperator(user))) { #ifdef STATSERVICES char *hostname, *domain; struct HostHash *hosth, *domainh; time_t currtime = current_ts; #endif #ifdef NICKSERVICES CheckOper(user); #endif Network->TotalOperators++; if (SafeConnect) SendUmode(OPERUMODE_O, "*** New Operator: %s (%s@%s) [%s]", user->nick, user->username, user->hostname, user->server ? user->server->name : "*unknown*"); #ifdef STATSERVICES if (Network->TotalOperators > Network->MaxOperators) { Network->MaxOperators = Network->TotalOperators; Network->MaxOperators_ts = current_ts; if ((Network->MaxOperators % 5) == 0) { /* inform +y people of new max oper count */ SendUmode(OPERUMODE_Y, "*** New Max Operator Count: %ld", Network->MaxOperators); putlog(LOG2, "New Max Operator Count: %ld", Network->MaxOperators); } } if (Network->TotalOperators > Network->MaxOperatorsT) { Network->MaxOperatorsT = Network->TotalOperators; Network->MaxOperatorsT_ts = current_ts; } #endif if (user->server) { user->server->numopers++; #ifdef STATSERVICES if (user->server->numopers > user->server->maxopers) { user->server->maxopers = user->server->numopers; user->server->maxopers_ts = current_ts; } #endif } #ifdef STATSERVICES hostname = user->hostname; if ((hosth = FindHost(hostname))) { hosth->curropers++; if (hosth->curropers > hosth->maxopers) { hosth->maxopers = hosth->curropers; hosth->maxopers_ts = currtime; } } if ((domain = GetDomain(hostname))) { if ((domainh = FindDomain(domain))) { domainh->curropers++; if (domainh->curropers > domainh->maxopers) { domainh->maxopers = domainh->curropers; domainh->maxopers_ts = currtime; } } } #endif /* STATSERVICES */ } user->umodes |= umode; } else { if ((umode == UMODE_O) && (IsOperator(user))) { #ifdef STATSERVICES char *hostname, *domain; struct HostHash *hosth, *domainh; #endif Network->TotalOperators--; if (user->server) user->server->numopers--; #ifdef STATSERVICES hostname = user->hostname; if ((hosth = FindHost(hostname))) hosth->curropers--; if ((domain = GetDomain(hostname))) if ((domainh = FindDomain(domain))) domainh->curropers--; #endif } user->umodes &= ~umode; } } } /* UpdateUserModes() */
vector<Token> LexFileContents(char* fileContents, int fileLength){ Token currToken; currToken.start = fileContents; currToken.length = 0; currToken.type = SourceTokenType::EMPTY; vector<Token> tokens; for(int i = 0; i < fileLength; i++){ char currChar = fileContents[i]; bool isWhitespace = IsWhitespace(currChar); bool isQuote = (currChar == '"'); bool isOperator = IsOperator(currChar); bool isNumber = IsNumber(currChar); switch (currToken.type){ case SourceTokenType::EMPTY:{ if(!isWhitespace){ currToken.start = &fileContents[i]; currToken.length = 1; if(isQuote){ currToken.start++; currToken.length = 0; currToken.type = SourceTokenType::STRING; } else if(isOperator){ currToken.type = SourceTokenType::OPERATOR; } else if(isNumber){ currToken.type = SourceTokenType::NUMBER; } else{ currToken.type = SourceTokenType::IDENTIFIER; } } }break; case SourceTokenType::NUMBER: case SourceTokenType::IDENTIFIER:{ if(isWhitespace){ tokens.push_back(currToken); currToken.length = 0; currToken.type = SourceTokenType::EMPTY; } else if(isOperator){ tokens.push_back(currToken); currToken.start = &fileContents[i]; currToken.length = 1; currToken.type = SourceTokenType::OPERATOR; } else{ currToken.length++; } }break; case SourceTokenType::STRING:{ if(isQuote){ tokens.push_back(currToken); currToken.length = 0; currToken.type = SourceTokenType::EMPTY; } else{ currToken.length++; } }break; case SourceTokenType::OPERATOR:{ tokens.push_back(currToken); currToken.length = 1; currToken.start = &fileContents[i]; if(isWhitespace){ currToken.length = 0; currToken.type = SourceTokenType::EMPTY; } else if(isNumber){ currToken.type = SourceTokenType::NUMBER; } else if(isOperator){ currToken.type = SourceTokenType::OPERATOR; } else if(isQuote){ currToken.start++; currToken.length = 0; currToken.type = SourceTokenType::STRING; } else{ currToken.type = SourceTokenType::IDENTIFIER; } }break; default: break; } } return tokens; }