/* return true if expression is mathematically correct * Currently only checks... * brackets * Makes sure there's not a space or '*' after of before each '*' */ bool MathStringParser::isExpressionValid(const QString &str) { QStack<char> bracketStack; for (int i = 0; i < str.size(); ++i) { if (str[i] == ' ') { if (!bracketStack.empty()) { return false; } } else if (str[i] == '(') { bracketStack.push('('); } else if (str[i] == ')') { if (bracketStack.empty()) { return false; } else { bracketStack.pop(); } } } if (!bracketStack.empty()) { return false; } if (str.contains("**") || str.contains(" *") || str.contains("* ")) { return false; } return true; }
void CollectionScanner::scanDirectory(QDir directory) { QStack<QDir> stack; stack.push(directory); while(!stack.empty()) { const QDir dir = stack.pop(); const QFileInfoList flist = dir.entryInfoList( QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files | QDir::Readable ); QFileInfo fileInfo; Q_FOREACH(fileInfo, flist) { if(fileInfo.isFile() ) { processFile(fileInfo); } else if (fileInfo.isDir()) { QString subDirPath = fileInfo.absoluteFilePath(); #ifdef APP_MAC if (directoryBlacklist.contains(subDirPath)) { qDebug() << "Skipping directory" << subDirPath; continue; } #endif QDir subDir(subDirPath); stack.push(subDir); } } } }
void KoTextWriter::Private::writeBlocks(QTextDocument *document, int from, int to, QHash<QTextList *, QString> &listStyles, QTextTable *currentTable, QTextList *currentList) { pairedInlineObjectsStackStack.push(currentPairedInlineObjectsStack); currentPairedInlineObjectsStack = new QStack<KoInlineObject*>(); QTextBlock block = document->findBlock(from); // Here we are going to detect all sections that // are positioned entirely inside selection. // They will stay untouched, and others will be omitted. // So we are using stack to detect them, by going through // the selection and finding open/close pairs. QSet<QString> entireWithinSectionNames; QStack<QString> sectionNamesStack; QTextCursor cur(document); cur.setPosition(from); while (to == -1 || cur.position() <= to) { if (cur.block().position() >= from) { // Begin of the block is inside selection. foreach (const KoSection *sec, KoSectionUtils::sectionStartings(cur.blockFormat())) { sectionNamesStack.push_back(sec->name()); } } if (to == -1 || cur.block().position() + cur.block().length() - 1 <= to) { // End of the block is inside selection. foreach (const KoSectionEnd *sec, KoSectionUtils::sectionEndings(cur.blockFormat())) { if (!sectionNamesStack.empty() && sectionNamesStack.top() == sec->name()) { sectionNamesStack.pop(); entireWithinSectionNames.insert(sec->name()); } } }
QList<ListDigraph::Node> ProcessModel::topolSortReachableFrom(const QList<ListDigraph::Node>& s) { ListDigraph::NodeMap<bool > nodevisited(graph, false); QList<ListDigraph::Node> res; QStack<ListDigraph::Node> stack; ListDigraph::Node curnode; ListDigraph::Node pnode; ListDigraph::Node snode; QList<ListDigraph::Node> reachable = reachableFrom(s); // Reserve memory res.reserve(countNodes(graph)); stack.reserve(countNodes(graph)); for (int i = 0; i < s.size(); i++) { if (s[i] != INVALID) { stack.push(s[i]); } } bool psched; while (!stack.empty()) { curnode = stack.pop(); if (!nodevisited[curnode]) { // This node has not been visited yet // Check whether all predecessors in reachable are scheduled psched = true; for (ListDigraph::InArcIt iait(graph, curnode); iait != INVALID; ++iait) { pnode = graph.source(iait); if (reachable.contains(pnode)) { // Consider only nodes which can be reached from s if (!nodevisited[pnode]) { psched = false; break; } } } if (psched) { // All predecessors have been visited res.append(curnode); nodevisited[curnode] = true; // Push the succeeding nodes for (ListDigraph::OutArcIt oait(graph, curnode); oait != INVALID; ++oait) { snode = graph.target(oait); if (!nodevisited[snode]) { stack.push(snode); } } } else { stack.prepend(curnode); } } // Else ignore the visited node } return res; }
int MathStringParser::getClosingBracketIndex(const QString &str, int pos) { QStack<char> bracketStack; //qDebug() << str << pos; while (pos < str.size()) { if (str[pos] == '(') { bracketStack.push('('); } else if (str[pos] == ')') { bracketStack.pop(); if (bracketStack.empty()) { return pos; } } ++pos; } if (pos == str.size() || !bracketStack.empty()) { return -1; } return str.size()-1; }
void MainWindow::on_pushButton_clicked() { QStack<QString> stk; QString str = ui->textEdit->toPlainText(), str2=str; bool f=false; bool Pr=false, f2=true,f3=true; for(int i=0; i<str.count();i++) if ((str.at(i)=='0')||(str.at(i)=='1')) Pr= true; else Pr = false; // if(str.count("0")!=str.count("1")) // f3=false; if(str.isEmpty()||(Pr==false))//||(f3=false)) { ui->textEdit_2->insertPlainText("Error"); } else { for(int i=0;i<str.count();i++) { if (str.at(i)=='0') { stk.push("0"); f=true; } if ((str.at(i)=='1')) if(!stk.empty()) stk.pop(); else { ui->textEdit_2->insertPlainText("Error"); f2=false; break; } } } if ((f==true)&&(stk.isEmpty())&&(f2)) ui->textEdit_2->insertPlainText("Right"); }
Node* NavMesh::searchDepthFirst(Node *start, Node* goal) { QStack<Node*> stack; stack.push(start); while( !stack.empty() ) { Node* node = stack.pop(); if ( node->visited() ) continue; if ( node == goal ) return node; node->setVisited(true); AdjacencyList::Iterator arc; for( arc = node->adjacents.begin(); arc != node->adjacents.end(); ++arc ) { if ( ! (*arc)->to->visited() ) stack.push( (*arc)->to ); } } return 0; }
void Project::scanRoot() { QStack<QDir> directoryStack; directoryStack.push(m_root); while (!directoryStack.empty()) { QDir directory(directoryStack.pop()); qint64 updated = QDateTime::currentDateTime().toTime_t(); QFileInfoList entries(directory.entryInfoList(QDir::NoFilter, QDir::DirsLast)); for (int i = 0; i < entries.length(); i++) { if (entries[i].fileName() == "." || entries[i].fileName() == "..") continue; QString absolutePath(entries[i].absoluteFilePath()); addOrUpdateEntry(getRelativePath(absolutePath), updated); if (entries[i].isDir()) directoryStack.push(QDir(absolutePath)); } } }
void TestKoTextEditor::checkSectionModelLevel(TestDocument *doc) { // Assuming here that Formatting level is OK // Below I will rebuild sections structure from scratch // and compare it then with a KoSectionModel QVector<SectionHandle *> allSections, rootSections; QStack<SectionHandle *> sectionStack; QTextBlock curBlock = doc->m_document->firstBlock(); // This kind of cycle should visit all blocks // including ones in tables and frames. while (curBlock.isValid()) { QList<KoSection *> secStartings = KoSectionUtils::sectionStartings(curBlock.blockFormat()); QList<KoSectionEnd *> secEndings = KoSectionUtils::sectionEndings(curBlock.blockFormat()); foreach(KoSection *sec, secStartings) { SectionHandle *handle = new SectionHandle(sec); if (sectionStack.empty()) { rootSections.push_back(handle); handle->parent = 0; } else { sectionStack.top()->children.push_back(handle); handle->parent = sectionStack.top()->sec; } allSections.push_back(handle); sectionStack.push(handle); } foreach(KoSectionEnd *secEnd, secEndings) { sectionStack.pop(); } curBlock = curBlock.next(); }
void Parser::RPN() { if (sourceStr.at(0) == '-') sourceStr = "0"+sourceStr; sourceStr.replace("(-","(0-"); sourceStr.replace("( -","(0-"); sourceStr.replace("+"," + "); sourceStr.replace("-"," - "); sourceStr.replace("*"," * "); sourceStr.replace("/"," / "); sourceStr.replace("^"," ^ "); sourceStr.replace(")"," ) "); sourceStr.replace("("," ( "); QStringList tokens; QStringList op; op << "+" << "-" << "*" << "/" << "^"; QStack <QString> stack; rpnStr = ""; tokens = sourceStr.split(QRegExp("\\s+")); qDebug() << "tokens: " << tokens; for (int it = 0; it < tokens.size(); ++it) { qDebug() << "rpnStr: " << rpnStr ; if ((tokens.at(it).at(0) >='0' && tokens.at(it).at(0) <='9') || (tokens.at(it).at(0) >='a' && tokens.at(it).at(0) <='z') ) { rpnStr += tokens.at(it); rpnStr += " "; continue; } if (tokens.at(it) == "(") { stack.push(tokens.at(it)); continue; } if (tokens.at(it) == ")") { while (stack.top() != "(") { rpnStr += stack.pop(); rpnStr += " "; } stack.pop(); continue; } if (op.indexOf(tokens.at(it)) >= 0) { if (tokens.at(it) == "^") { stack.push(tokens.at(it)); continue; } if (tokens.at(it) == "*" || tokens.at(it) == "/") { if (!stack.isEmpty()) { while(!stack.isEmpty() && (stack.top() == "^") ) { rpnStr += stack.pop(); rpnStr += " "; } } stack.push(tokens.at(it)); continue; } if (tokens.at(it) == "+" || tokens.at(it) == "-") { if (!stack.isEmpty()) { while(!stack.isEmpty() && (stack.top() == "^" || stack.top() == "/" || stack.top() == "*" || stack.top() == "+" || stack.top() == "-")) { rpnStr += stack.pop(); rpnStr += " "; } } stack.push(tokens.at(it)); continue; } } } while (!stack.empty()) { if (stack.top() != "") { rpnStr += stack.pop(); rpnStr += " "; } else { stack.pop(); } } qDebug() << "rpnStr: " << rpnStr ; qDebug() << "source: " << sourceStr; }
bool SimpleJsonParser::parse(const QByteArray& json) { resetState(); m_source = json; m_ptr = m_source.data(); m_end = m_ptr + m_source.length(); QStack<QString> stack; QVariantMap result; QVector<Token> expectedTokens; expectedTokens.push_back(Token_Begin); Token prevToken = Token_ERROR; QString lastStr; QString prefix; QString lastKey; for (;;) { Token token = nextToken(); if (expectedTokens.indexOf(token) < 0) { DBGLOG(LOG_ERROR, 2, QString::fromUtf8("unexpected token %1").arg(token)); return false; } switch (token) { case Token_ERROR: return false; case Token_EOF: if (!stack.empty()) { DBGLOG(LOG_ERROR, 2, QString::fromUtf8("unblanced { }, bad json!")); return false; } m_result = result; return true; case Token_Begin: DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token BEGIN")); if (stack.empty()) { stack.push_back(QString::fromUtf8("")); } else { stack.push_back(prefix); prefix.append(lastKey); prefix.append(QChar::fromAscii('.')); } expectedTokens.clear(); expectedTokens.push_back(Token_End); expectedTokens.push_back(Token_String); break; case Token_End: DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token END")); prefix = stack.pop(); if (!stack.empty()) { expectedTokens.clear(); expectedTokens.push_back(Token_Comma); expectedTokens.push_back(Token_End); } else { expectedTokens.push_back(Token_EOF); } break; case Token_Comma: DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token COMMA")); expectedTokens.clear(); expectedTokens.push_back(Token_End); expectedTokens.push_back(Token_String); break; case Token_Colon: DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token COLON")); expectedTokens.clear(); expectedTokens.push_back(Token_Begin); expectedTokens.push_back(Token_String); expectedTokens.push_back(Token_Number); break; case Token_String: DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token STRING [%1]").arg(QString::fromUtf8(m_str))); if (prevToken == Token_Colon) { DBGLOG(LOG_DEBUG, 12, QString::fromUtf8("submit '%3%1'='%2'").arg(lastKey).arg(QString::fromUtf8(m_str)).arg(prefix)); result.insert(prefix + lastKey, QString::fromUtf8(m_str)); } else { lastKey = QString::fromUtf8(m_str); } // TODO: expectedTokens.clear(); expectedTokens.push_back(Token_End); expectedTokens.push_back(Token_Comma); expectedTokens.push_back(Token_Colon); break; case Token_Number: DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token NUMBER [%1]").arg(m_num)); DBGLOG(LOG_DEBUG, 12, QString::fromUtf8("submit '%3%1'=%2").arg(lastKey).arg(m_num).arg(prefix)); result.insert(prefix + lastKey, m_num); expectedTokens.clear(); expectedTokens.push_back(Token_End); expectedTokens.push_back(Token_Comma); break; } prevToken = token; } return false; }
QString RPN_utility::main_parser(QString &formula) { QString output_string; QTextStream iss(&formula); QTextStream output(&output_string); QStack <QString> s; QString token; while(!iss.atEnd()) { iss >> token; //If token is a number if( isnumber(token) || ( token.length() == 1 && token[0].isLetter() ) ) { output << token << " "; //if function separator } else if (token[0] == ',') { while (s.top() != "(" ) { output << s.top() << " "; s.pop(); } //If token is an operator } else if( token.length() == 1 && isoperator(token) ) { while ( !s.isEmpty() && ( (TAB_OP[token[0]].second == LEFT && TAB_OP[token[0]].first <= TAB_OP[s.top()[0]].first) || (TAB_OP[token[0]].second == RIGHT && TAB_OP[token[0]].first < TAB_OP[s.top()[0]].first) ) ) { output << s.top() << " "; s.pop(); } s.push(token); //Si c'est une fonction } else if (token.length() > 1 ) { s.push(token); //Si c'est une parenthèse ouvrante } else if (token == "(" ) { s.push(token); //Si c'est une parenthèse fermante } else if (token == ")" ) { while (s.top() != "(" ) { output << s.top() << " "; s.pop(); } s.pop(); if ( !s.empty() && s.top().length() > 1 ) { output << s.top() << " "; s.pop(); } } token = ""; } while (!s.empty()) { output << s.top() << " "; s.pop(); } output.flush(); return output_string; }
bool KoEnhancedPathFormula::compile( const TokenList & tokens ) { // sanity check if( tokens.count() == 0 ) return false; FormulaTokenStack syntaxStack; QStack<int> argStack; unsigned argCount = 1; for( int i = 0; i <= tokens.count(); i++ ) { // helper token: InvalidOp is end-of-formula FormulaToken token = ( i < tokens.count() ) ? tokens[i] : FormulaToken( FormulaToken::TypeOperator ); FormulaToken::Type tokenType = token.type(); // unknown token is invalid if( tokenType == FormulaToken::TypeUnknown ) break; // for constants, push immediately to stack // generate code to load from a constant if( tokenType == FormulaToken::TypeNumber ) { syntaxStack.push( token ); m_constants.append( QVariant( token.asNumber() ) ); m_codes.append( Opcode( Opcode::Load, m_constants.count()-1 ) ); } // for identifier, push immediately to stack // generate code to load from reference if( tokenType == FormulaToken::TypeFunction || tokenType == FormulaToken::TypeReference ) { syntaxStack.push( token ); m_constants.append( QVariant( token.text() ) ); m_codes.append( Opcode( Opcode::Ref, m_constants.count()-1 ) ); } // are we entering a function ? // if token is operator, and stack already has: id ( arg if( tokenType == FormulaToken::TypeOperator && syntaxStack.itemCount() >= 3 ) { FormulaToken arg = syntaxStack.top(); FormulaToken par = syntaxStack.top( 1 ); FormulaToken id = syntaxStack.top( 2 ); if( !arg.isOperator() && par.asOperator() == FormulaToken::OperatorLeftPar && id.isFunction() ) { argStack.push( argCount ); argCount = 1; } } // for any other operator, try to apply all parsing rules if( tokenType == FormulaToken::TypeOperator ) { // repeat until no more rule applies for( ; ; ) { bool ruleFound = false; // rule for function arguments, if token is , or ) // id ( arg1 , arg2 -> id ( arg if( !ruleFound ) if( syntaxStack.itemCount() >= 5 ) if( ( token.asOperator() == FormulaToken::OperatorRightPar ) || ( token.asOperator() == FormulaToken::OperatorComma ) ) { FormulaToken arg2 = syntaxStack.top(); FormulaToken sep = syntaxStack.top( 1 ); FormulaToken arg1 = syntaxStack.top( 2 ); FormulaToken par = syntaxStack.top( 3 ); FormulaToken id = syntaxStack.top( 4 ); if( !arg2.isOperator() ) if( sep.asOperator() == FormulaToken::OperatorComma ) if( !arg1.isOperator() ) if( par.asOperator() == FormulaToken::OperatorLeftPar ) if( id.isFunction() ) { ruleFound = true; syntaxStack.pop(); syntaxStack.pop(); argCount++; } } // rule for function last argument: // id ( arg ) -> arg if( !ruleFound ) if( syntaxStack.itemCount() >= 4 ) { FormulaToken par2 = syntaxStack.top(); FormulaToken arg = syntaxStack.top( 1 ); FormulaToken par1 = syntaxStack.top( 2 ); FormulaToken id = syntaxStack.top( 3 ); if( par2.asOperator() == FormulaToken::OperatorRightPar ) if( !arg.isOperator() ) if( par1.asOperator() == FormulaToken::OperatorLeftPar ) if( id.isFunction() ) { ruleFound = true; syntaxStack.pop(); syntaxStack.pop(); syntaxStack.pop(); syntaxStack.pop(); syntaxStack.push( arg ); m_codes.append( Opcode( Opcode::Function, argCount ) ); argCount = argStack.empty() ? 0 : argStack.pop(); } } // rule for parenthesis: ( Y ) -> Y if( !ruleFound ) if( syntaxStack.itemCount() >= 3 ) { FormulaToken right = syntaxStack.top(); FormulaToken y = syntaxStack.top( 1 ); FormulaToken left = syntaxStack.top( 2 ); if( right.isOperator() ) if( !y.isOperator() ) if( left.isOperator() ) if( right.asOperator() == FormulaToken::OperatorRightPar ) if( left.asOperator() == FormulaToken::OperatorLeftPar ) { ruleFound = true; syntaxStack.pop(); syntaxStack.pop(); syntaxStack.pop(); syntaxStack.push( y ); } } // rule for binary operator: A (op) B -> A // conditions: precedence of op >= precedence of token // action: push (op) to result // e.g. "A * B" becomes 'A' if token is operator '+' if( !ruleFound ) if( syntaxStack.itemCount() >= 3 ) { FormulaToken b = syntaxStack.top(); FormulaToken op = syntaxStack.top( 1 ); FormulaToken a = syntaxStack.top( 2 ); if( !a.isOperator() ) if( !b.isOperator() ) if( op.isOperator() ) if( token.asOperator() != FormulaToken::OperatorLeftPar ) if( opPrecedence( op.asOperator() ) >= opPrecedence( token.asOperator() ) ) { ruleFound = true; syntaxStack.pop(); syntaxStack.pop(); syntaxStack.pop(); syntaxStack.push( b ); switch( op.asOperator() ) { // simple binary operations case FormulaToken::OperatorAdd: m_codes.append( Opcode::Add ); break; case FormulaToken::OperatorSub: m_codes.append( Opcode::Sub ); break; case FormulaToken::OperatorMul: m_codes.append( Opcode::Mul ); break; case FormulaToken::OperatorDiv: m_codes.append( Opcode::Div ); break; default: break; }; } } // rule for unary operator: (op1) (op2) X -> (op1) X // conditions: op2 is unary, token is not '(' // action: push (op2) to result // e.g. "* - 2" becomes '*' if( !ruleFound ) if( token.asOperator() != FormulaToken::OperatorLeftPar ) if( syntaxStack.itemCount() >= 3 ) { FormulaToken x = syntaxStack.top(); FormulaToken op2 = syntaxStack.top( 1 ); FormulaToken op1 = syntaxStack.top( 2 ); if( !x.isOperator() ) if( op1.isOperator() ) if( op2.isOperator() ) if( ( op2.asOperator() == FormulaToken::OperatorAdd ) || ( op2.asOperator() == FormulaToken::OperatorSub ) ) { ruleFound = true; syntaxStack.pop(); syntaxStack.pop(); syntaxStack.push( x ); if( op2.asOperator() == FormulaToken::OperatorSub ) m_codes.append( Opcode( Opcode::Neg ) ); } } // auxiliary rule for unary operator: (op) X -> X // conditions: op is unary, op is first in syntax stack, token is not '(' // action: push (op) to result if( !ruleFound ) if( token.asOperator() != FormulaToken::OperatorLeftPar ) if( syntaxStack.itemCount() == 2 ) { FormulaToken x = syntaxStack.top(); FormulaToken op = syntaxStack.top( 1 ); if( !x.isOperator() ) if( op.isOperator() ) if( ( op.asOperator() == FormulaToken::OperatorAdd ) || ( op.asOperator() == FormulaToken::OperatorSub ) ) { ruleFound = true; syntaxStack.pop(); syntaxStack.pop(); syntaxStack.push( x ); if( op.asOperator() == FormulaToken::OperatorSub ) m_codes.append( Opcode( Opcode::Neg ) ); } } if( !ruleFound ) break; } syntaxStack.push( token ); } } // syntaxStack must left only one operand and end-of-formula (i.e. InvalidOp) m_valid = false; if( syntaxStack.itemCount() == 2 ) if( syntaxStack.top().isOperator() ) if( syntaxStack.top().asOperator() == FormulaToken::OperatorInvalid ) if( !syntaxStack.top(1).isOperator() ) m_valid = true; // bad parsing ? clean-up everything if( ! m_valid ) { m_constants.clear(); m_codes.clear(); kWarning() << "compiling of "<< m_text << " failed"; } return m_valid; }
void FileIndexThread::run() { struct PathToIndex { QString path; bool recursive; QStringList filter; }; #ifdef Q_OS_UNIX static const QList<PathToIndex> pathsToIndex = { { "/usr/share/applications", true, { "*.desktop" } }, { QDir(QDir::homePath()).relativeFilePath(".local/share/applications"), true, { "*.desktop" } }, { QDir(QDir::homePath()).relativeFilePath("Desktop"), true, { "*.desktop" } }, }; #elif defined(Q_OS_WIN) QList<PathToIndex> pathsToIndex = { { QSettings("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", QSettings::NativeFormat).value("Common Desktop").toString(), true, { "*.lnk" } }, { QSettings("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", QSettings::NativeFormat).value("Common Start Menu").toString(), true, { "*.lnk" } }, }; { // There are newer API functions for this; but they are only for Vista and newer WCHAR szPath[MAX_PATH]; HRESULT hr = SHGetFolderPathW(0, CSIDL_STARTMENU, 0, 0, szPath); if (SUCCEEDED(hr)) pathsToIndex.push_back({ QString::fromWCharArray(szPath), true, { "*.lnk" } }); hr = SHGetFolderPathW(0, CSIDL_DESKTOPDIRECTORY, 0, 0, szPath); if (SUCCEEDED(hr)) pathsToIndex.push_back({ QString::fromWCharArray(szPath), true, { "*.lnk" } }); } #else #error "Not implemented for this operating system" #endif for (const PathToIndex& pathInfo : pathsToIndex) { const QString pathString = expandEnvironmentPath(pathInfo.path); QStack<QString> dirstack; dirstack.push_back(expandEnvironmentPath(pathString)); while (dirstack.empty() == false) { QDir path(dirstack.pop()); path.setNameFilters(pathInfo.filter); for (const QString& filename : path.entryList()) { int dot = filename.lastIndexOf('.'); const QString basename = dot > 0 ? filename.left(dot) : filename; dbLock.lockForWrite(); this->db.add(basename, basename, path.absoluteFilePath(filename), QStringList()); dbLock.unlock(); } // For now, no symlink traversal to avoid loops for (const QString& dirname : path.entryList(QStringList(), QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)) { dirstack.push_back(path.absoluteFilePath(dirname)); } } } #ifdef Q_OS_WIN const QString systemPath = getWindowsSystemPath(); for (const QString& filename : QDir(systemPath).entryList({ "*.cpl" })) { readCpl(filename, this->db, this->dbLock); } #endif emit indexDone(); }
bool KMacroExpanderBase::expandMacrosShellQuote( QString &str, int &pos ) { int len; int pos2; ushort ec = d->escapechar.unicode(); State state = { noquote, false }; QStack<State> sstack; QStack<Save> ostack; QStringList rst; QString rsts; while (pos < str.length()) { ushort cc = str.unicode()[pos].unicode(); if (ec != 0) { if (cc != ec) goto nohit; if (!(len = expandEscapedMacro( str, pos, rst ))) goto nohit; } else { if (!(len = expandPlainMacro( str, pos, rst ))) goto nohit; } if (len < 0) { pos -= len; continue; } if (state.dquote) { rsts = rst.join( QLatin1String(" ") ); rsts.replace( QRegExp(QLatin1String("([$`\"\\\\])")), QLatin1String("\\\\1") ); } else if (state.current == dollarquote) { rsts = rst.join( QLatin1String(" ") ); rsts.replace( QRegExp(QLatin1String("(['\\\\])")), QLatin1String("\\\\1") ); } else if (state.current == singlequote) { rsts = rst.join( QLatin1String(" ") ); rsts.replace( QLatin1Char('\''), QLatin1String("'\\''") ); } else { if (rst.isEmpty()) { str.remove( pos, len ); continue; } else { rsts = joinArgs( rst ); } } rst.clear(); str.replace( pos, len, rsts ); pos += rsts.length(); continue; nohit: if (state.current == singlequote) { if (cc == '\'') state = sstack.pop(); } else if (cc == '\\') { // always swallow the char -> prevent anomalies due to expansion pos += 2; continue; } else if (state.current == dollarquote) { if (cc == '\'') state = sstack.pop(); } else if (cc == '$') { cc = str.unicode()[++pos].unicode(); if (cc == '(') { sstack.push( state ); if (str.unicode()[pos + 1].unicode() == '(') { Save sav = { str, pos + 2 }; ostack.push( sav ); state.current = math; pos += 2; continue; } else { state.current = paren; state.dquote = false; } } else if (cc == '{') { sstack.push( state ); state.current = subst; } else if (!state.dquote) { if (cc == '\'') { sstack.push( state ); state.current = dollarquote; } else if (cc == '"') { sstack.push( state ); state.current = doublequote; state.dquote = true; } } // always swallow the char -> prevent anomalies due to expansion } else if (cc == '`') { str.replace( pos, 1, QLatin1String("$( " )); // add space -> avoid creating $(( pos2 = pos += 3; for (;;) { if (pos2 >= str.length()) { pos = pos2; return false; } cc = str.unicode()[pos2].unicode(); if (cc == '`') break; if (cc == '\\') { cc = str.unicode()[++pos2].unicode(); if (cc == '$' || cc == '`' || cc == '\\' || (cc == '"' && state.dquote)) { str.remove( pos2 - 1, 1 ); continue; } } pos2++; } str[pos2] = QLatin1Char(')'); sstack.push( state ); state.current = paren; state.dquote = false; continue; } else if (state.current == doublequote) { if (cc == '"') state = sstack.pop(); } else if (cc == '\'') { if (!state.dquote) { sstack.push( state ); state.current = singlequote; } } else if (cc == '"') { if (!state.dquote) { sstack.push( state ); state.current = doublequote; state.dquote = true; } } else if (state.current == subst) { if (cc == '}') state = sstack.pop(); } else if (cc == ')') { if (state.current == math) { if (str.unicode()[pos + 1].unicode() == ')') { state = sstack.pop(); pos += 2; } else { // false hit: the $(( was a $( ( in fact // ash does not care, but bash does pos = ostack.top().pos; str = ostack.top().str; ostack.pop(); state.current = paren; state.dquote = false; sstack.push( state ); } continue; } else if (state.current == paren) state = sstack.pop(); else break; } else if (cc == '}') { if (state.current == KMacroExpander::group) state = sstack.pop(); else break; } else if (cc == '(') { sstack.push( state ); state.current = paren; } else if (cc == '{') { sstack.push( state ); state.current = KMacroExpander::group; } pos++; } return sstack.empty(); }
Litterale* Expression::evaluer() const{ QString s = value; //On vire les ' s=s.remove(0,1); s=s.remove(s.length()-1,s.length()); QString::iterator it = s.begin(); //QString contenant le résultat QString postfix; //Stack d'opérations QStack<QString> stack; //Map des opérateurs const QMap<QString, Operateur*> op_map = OperateurFactory::getMap(); //Map de tous les symboles const QMap<QString,WordIdentifier*>& interpretation_map = Controleur::getInterpretationMap(); //Traduction de Infix vers Postfix QString tmp; bool found; while(it!=s.end()){ found=false; if(*it==' ' || *it==','){ it++; continue; } //Verification que ce n'est pas une litterale avec 2 symboles exemple : Expression ou Programme if(tmp == "" && interpretation_map.find(*it)!=interpretation_map.end()){ WordIdentifier *identifier = interpretation_map.find(*it).value(); WordIdentifier *try1; WordIdentifier *try2; try1=dynamic_cast<RecursiveEncapsulatorIdentifier*>(identifier); try2=dynamic_cast<EncapsulatorIdentifier*>(identifier); if(try1 || try2) { throw LitteraleException("Litterale "+ QString(*it) +" non permise","Inconnu"); } } //On tombe dans le cas ou on a une valeur while(it!=s.end() && ((*it<='9' && *it>='0') || (interpretation_map.find(*it)!=interpretation_map.end()))){ tmp+=*it; if(it!=s.end()) it++; } //Pour vider ce qu'on a trouvé if(tmp!=""){ postfix+=tmp+" "; tmp.clear(); found=true; } //On tombe dans le cas d'un morçeau de texte if((*it<='Z' && *it>='A')){ while(it!=s.end() && ((*it<='Z' && *it>='A') || (*it<='9' && *it>='0'))){ tmp+=* it; if(it!=s.end()) it++; } if(isOperator(tmp)){ found=true; while(!stack.empty() && stack.top() != "(" && CompareOperators(stack.top(),tmp)<=0){ postfix += stack.top()+" "; stack.pop(); } stack.push(tmp); tmp.clear(); } else if(isVariable(tmp)){ found=true; Litterale* l = VariablesManager::getVariable(tmp); if(estdeType<Programme>(l)) throw OperateurException("Un programme est dans l'expression !"); QString rep = l->toString(); int length_it = s.indexOf(tmp); s.replace(tmp,rep); it = s.begin(); for(int i=0; i<length_it;i++,it++); tmp.clear(); } else throw(LitteraleException("Le mot "+tmp+" est inconnu","Inconnu")); } if(*it=='('){ stack.push(*it); if(it!=s.end()) it++; found=true; } if(*it==')'){ while(stack.top()!="("){ postfix+= stack.top()+" "; stack.pop(); } stack.pop(); if(it!=s.end()) it++; found=true; } //On tombe dans le cas d'un opérateur à caractère if(!found){ while(it!=s.end() && !op_map.contains(tmp)){ tmp+=*it++; } if(it==s.end() && !op_map.contains(tmp)) throw LitteraleException("Expression non valide dès "+tmp,"Expression"); while(!stack.empty() && stack.top() != "(" && CompareOperators(stack.top(),tmp)<=0){ postfix += stack.top()+" "; stack.pop(); } stack.push(tmp); tmp.clear(); } } while(!stack.empty()){ postfix+= stack.top() + " "; stack.pop(); } MainWindow::getInstanceMainWindow()->getNextCommande(postfix,"INFIX"); return nullptr; }
QString MessageValidator::validateMessage(QString message, bool* illformed, HTMLTextFormatter* formatter) { // qDebug() << "IMG val0" << message; QDomDocument doc("document"); *illformed = false; QString errorMessage; int line, column; QDomDocument tmpDoc; //used by textformatter xmlSource.setData(message); if (!doc.setContent(&xmlSource, &xmlReader, &errorMessage, &line, &column)) { qDebug() << errorMessage << " " << line << " " << column << message; *illformed = true; qDebug() << "WARNING: MessageValidator::validateMessage() - illformed message"; return "illformed message!!!"; } //now DOM tree will be traversed in preorder. QStack<QDomElement> stack; //current element, QStack is used to avoid possible stack overflow in ordinary recursion stack.push(doc.documentElement()); while (!stack.empty()) { QDomElement cur = stack.top(); stack.pop(); // Traverse through DOM Tree(cur), cut off bad elements/attributes // and format text nodes using textFormatter // qDebug() << QString(4, ' ') << cur.tagName(); QString parentName = cur.tagName(); NodeInfo curNI = allowed[parentName]; //delete disallowed attributes for (int i = 0; i < cur.attributes().count(); i++) { QString attrName = cur.attributes().item(i).toAttr().name(); if (!curNI.allowedAttributes.contains(attrName)) { // qDebug() << "VALIDATIN ERR" << "TA" << attrName << " in " << parentName; // qDebug() << "note allowed attributes are:" << curNI.allowedAttributes; cur.attributes().removeNamedItem(attrName); i--; } } QDomNodeList children = cur.childNodes(); for (int i = children.size() - 1; i >= 0; i--) { QDomNode node = children.at(i); if (node.isElement()) { QString childName = node.toElement().tagName(); if (childName == "a") { // always show hyperlink destination QString href = node.toElement().attribute("href"); node.appendChild(doc.createTextNode(" [ " + href + " ]")); } if (childName == "style") { //NOTE: this action is not XHTML-IM compliant! (css rules should be displayed, but it's stupid) cur.removeChild(node); } else if (childName == "img") { //disabling images until they are whitelisted QString href = node.toElement().attribute("src"); QDomElement newElement = doc.createElement("a"); newElement.setAttribute("class", "psi_disabled_image"); newElement.setAttribute("href", "javascript:psi_addToWhiteList('" + href + "')"); newElement.appendChild(doc.createTextNode("[ click here to display: " + href + " ]")); cur.replaceChild(newElement, node); } else if (!curNI.allowedTags.contains(childName)) {//is subElement valid here? qDebug() << "VALIDATIN ERR" << "TS" << childName << " in " << parentName; qDebug() << "note allowed subElements are:" << curNI.allowedTags; //append bad node's children (they will be validated in next loop iteration) int j = 0; while (node.hasChildNodes()) { cur.insertBefore(node.firstChild(), node); j++; } i = i + j; //j nodes were inserted //delete bad node cur.removeChild(node); } else { stack.push(node.toElement()); } } else if (node.isText() && !node.isCDATASection()) { if (!curNI.canHaveText) { cur.removeChild(node); } else { //format text QString formattedText = "<tmp>" + formatter->format(Qt::escape(node.toText().data()), cur) + "</tmp>"; //NOTE: we don't need to escape quotes, and we want this code be more reusable/decoupled, //NOTE: so we use Qt::escape() instead of TextUtil::escape() xmlSource.setData(formattedText); tmpDoc.setContent(&xmlSource, &xmlReader); QDomNode tmpElement = tmpDoc.firstChild(); while (tmpElement.hasChildNodes()) { //append <tmp>'s children. They won't be validated cur.insertBefore(tmpElement.firstChild(), node); } cur.removeChild(node); } } }//foreach child } //stack/dfs // qDebug() << "IMG MV:" << doc.toString(0); return doc.toString(0); }