Beispiel #1
0
int Highlighter::highlightLine(const QString &text, int state)
{
    m_currentBlockParentheses.clear();

    Scanner scanner(&text);
    scanner.setState(state & 0xfffff);

    static QString openParenthesis = QStringLiteral("([{");
    static QString closeParenthesis = QStringLiteral(")]}");

    Token token;
    while ((token = scanner.read()).kind != Token::EndOfBlock) {
        setFormat(token.position, token.length, formatForToken(token));
        if (token.isParenthesisLike()) {
            QChar ch = text[token.position];
            if (openParenthesis.contains(ch))
                m_currentBlockParentheses << Parenthesis(Parenthesis::Opened, ch, token.position);
            else if (closeParenthesis.contains(ch))
                m_currentBlockParentheses << Parenthesis(Parenthesis::Closed, ch, token.position);
        }
    }

    int indentLevel = state >> 20;
    int nextIndentLevel = indentLevel + scanner.indentVariation();
    if (scanner.didBlockInterrupt())
        indentLevel--;

    if (nextIndentLevel < 0)
        nextIndentLevel = 0;

    TextEditor::TextDocumentLayout::setFoldingIndent(currentBlock(), indentLevel);
    TextEditor::TextDocumentLayout::setParentheses(currentBlock(), m_currentBlockParentheses);
    return (nextIndentLevel << 20) | scanner.state();
}
Beispiel #2
0
/** handle nested comments and simple minded attributes
  */
void lqGvSynCol::highlightBlock(const QString &text)
{
    QString begComm("/\\*");
    QString number("\\d+(?:\\.\\d+)?");
    QString symbol("\\w+");
    QString quoted("\"[^\"]*\"");
    QString edges("--|->");

    QRegExp tokens(QString("(%1)|(%2)|(%3)|(%4)|(%5)|#").arg(begComm, number, symbol, quoted, edges));
    QRegExp endComm("\\*/");

    // simple state machine
    if (currentBlock().blockNumber() > 0)
        setCurrentBlockState(previousBlockState());
    else
        setCurrentBlockState(0);

    for (int i = 0, j, l; ; i = j + l)
        if (currentBlockState()) {              // in multiline comment
            if ((j = endComm.indexIn(text, i)) == -1) {
                setFormat(i, text.length() - i, fmt[Comm]);
                break;
            }
            setFormat(i, j - i + (l = 2), fmt[Comm]);
            setCurrentBlockState(0);
        } else {
            if ((j = tokens.indexIn(text, i)) == -1)
                break;
            QStringList ml = tokens.capturedTexts();
            Q_ASSERT(ml.length() == 5+1);
            if ((l = ml[1].length())) {         // begin multiline comment
                setFormat(j, l, fmt[Comm]);
                setCurrentBlockState(1);
            } else if ((l = ml[2].length())) {  // number
                setFormat(j, l, fmt[Number]);
            } else if ((l = ml[3].length())) {  // symbol
                if (keyws.contains(ml[3]))
                    setFormat(j, l, fmt[Keyw]);
                else if (attrs.contains(ml[3]))
                    setFormat(j, l, fmt[Attr]);
                else
                    setFormat(j, l, fmt[Unknown]);
            } else if ((l = ml[4].length())) {  // quoted
                setFormat(j, l, fmt[Quoted]);
            } else if ((l = ml[5].length())) {  // edge
                setFormat(j, l, fmt[Edge]);
            } else {                            // single line comment
                setFormat(j, text.length() - i, fmt[Comm]);
                break;
            }
        }

    // rather useless - anyway textChanged will fire after completion
    if (currentBlock().blockNumber() == document()->blockCount() - 1)
        emit completed();
}
void ParenMatcherHighlighter::highlightBlock(const QString &text) {
  ParenInfoTextBlockData *data = new ParenInfoTextBlockData;

  QString modifiedText = text;
  QRegExp dblQuotesRegexp("\"[^\"]*\"");
  QRegExp simpleQuotesRegexp("'[^']*'");

  int pos = dblQuotesRegexp.indexIn(modifiedText);

  while (pos != -1) {
    for (int i = pos ; i < pos + dblQuotesRegexp.matchedLength() ; ++i) {
      modifiedText[i] = ' ';
    }

    pos = dblQuotesRegexp.indexIn(modifiedText, pos + dblQuotesRegexp.matchedLength());
  }

  pos = simpleQuotesRegexp.indexIn(modifiedText);

  while (pos != -1) {
    for (int i = pos ; i < pos + simpleQuotesRegexp.matchedLength() ; ++i) {
      modifiedText[i] = ' ';
    }

    pos = simpleQuotesRegexp.indexIn(modifiedText, pos + simpleQuotesRegexp.matchedLength());
  }

  for (int i = 0 ; i < _leftParensToMatch.size() ; ++i) {
    int leftPos = modifiedText.indexOf(_leftParensToMatch.at(i));

    while (leftPos != -1) {
      ParenInfo info;
      info.character = _leftParensToMatch.at(i);
      info.position = currentBlock().position() + leftPos;
      data->insert(info);
      leftPos = modifiedText.indexOf(_leftParensToMatch.at(i), leftPos+1);
    }
  }

  for (int i = 0 ; i < _rightParensToMatch.size() ; ++i) {
    int rightPos = modifiedText.indexOf(_rightParensToMatch.at(i));

    while (rightPos != -1) {
      ParenInfo info;
      info.character = _rightParensToMatch.at(i);
      info.position = currentBlock().position() + rightPos;
      data->insert(info);
      rightPos = modifiedText.indexOf(_rightParensToMatch.at(i), rightPos+1);
    }
  }

  data->sortParenInfos();
  setCurrentBlockUserData(data);
}
Beispiel #4
0
/** handle nested comments and simple minded Prolog syntax
  */
void plMiniSyntax::highlightBlock(const QString &text)
{
    // simple state machine
    int nb = currentBlock().blockNumber();
    if (nb > 0) {
        setCurrentBlockState(previousBlockState());
        if (nb % 10 == 0)
            do_events();
    }
    else {
        startToEnd.start();
        qDebug() << "starting at " << QTime::currentTime();
        setCurrentBlockState(0);
    }

    for (int i = 0, j, l; ; i = j + l)
        if (currentBlockState()) {              // in multiline comment
            if ((j = text.indexOf("*/", i)) == -1) {
                setFormat(i, text.length() - i, fmt[Comment]);
                break;
            }
            setFormat(i, j - i + (l = 2), fmt[Comment]);
            setCurrentBlockState(0);
        } else {
            if ((j = text.indexOf("/*", i)) >= 0) {         // begin multiline comment
                setFormat(j, l = 2, fmt[Comment]);
                setCurrentBlockState(1);
            } else {
                if ((j = tokens.indexIn(text, i)) == -1)
                    break;
                QStringList ml = tokens.capturedTexts();
                Q_ASSERT(ml.length() == 5+1);
                if ((l = ml[1].length())) {         // number
                    setFormat(j, l, fmt[Number]);
                } else if ((l = ml[2].length())) {  // symbol
                    setFormat(j, l, fmt[Atom]);
                } else if ((l = ml[3].length())) {  // var
                    setFormat(j, l, fmt[Variable]);
                } else if ((l = ml[4].length())) {  // quoted
                    setFormat(j, l, fmt[String]);
                } else if ((l = ml[5].length())) {  // operator
                    setFormat(j, l, fmt[Operator]);
                } else {                            // single line comment
                    setFormat(j, text.length() - i, fmt[Comment]);
                    break;
                }
            }
        }

    if (currentBlock() == document()->lastBlock())
        qDebug() << "done at " << QTime::currentTime() << "in" << startToEnd.elapsed();
}
Beispiel #5
0
void AeHighlighter::highlightBlock(const QString & t) {
	mutex_.lock();

	const int blockNumber = currentBlock().blockNumber();
	if(blockNumber < 0) return;
	const StyleVector& v = styles_->value(blockNumber);
    (void)t;
/*
	for(int i=0, N=v.count(); i!=N; ++i) {
		const AeCodeDecoration& cd = v.at(i);
		QTextCharFormat f = cd.textCharFormat();
		AeCodeDecoration::Extents e = cd.extents();
		for(int j=0; j!=N; ++j) {
			if(j==i) continue;
			else if(e.start == v.at(j).extents().start && e.length == v.at(j).extents().length)
				f.merge(v.at(j).textCharFormat());
		}
        if(cd.extents().length == -1) {
            ae_info("extents -1 at " << t);
        }
		setFormat(cd.extents().start, cd.extents().length == -1 ? t.length() : cd.extents().length, f);
    }*/

    unsigned from=0, to;
    bool done;
    do {
        done= true;
        to = currentBlock().length();
        QTextCharFormat f;
        for(int i=0;i<v.count();++i) {
            const AeCodeDecoration&cd =v.at(i);
            AeCodeDecoration::Extents e = cd.extents();
            if(e.start+e.length > (unsigned)currentBlock().length()) continue;
            if(from < e.start) {
                done = false;
                if(to > e.start) to = e.start;
            } else if(from < e.start + e.length) {
                done = false;
                if(to > e.start + e.length) to = e.start + e.length;
                f.merge(cd.textCharFormat());
            }
        }
        setFormat(from, to - from, f);
        from = to;
    } while(!done);

	mutex_.unlock();
}
/*
 * This sets the folding indent:
 * 0 for the first line of the diff header.
 * 1 for all the following lines of the diff header and all @@ lines.
 * 2 for everything else
 */
void DiffHighlighter::highlightBlock(const QString &text)
{
    Q_D(DiffHighlighter);
    if (text.isEmpty())
        return;

    const int length = text.length();
    const Internal::DiffFormats format = d->analyzeLine(text);
    switch (format) {
    case Internal::DiffTextFormat:
        break;
    case Internal::DiffInFormat: {
            // Mark trailing whitespace.
            const int trimmedLen = trimmedLength(text);
            setFormat(0, trimmedLen, formatForCategory(format));
            if (trimmedLen != length)
                setFormat(trimmedLen, length - trimmedLen, d->m_addedTrailingWhiteSpaceFormat);
        }
        break;
    default:
        setFormat(0, length, formatForCategory(format));
        break;
    }

    // codefolding:
    TextEditor::TextBlockUserData *data =
            TextEditor::TextDocumentLayout::userData(currentBlock());
    QTC_ASSERT(data, return; );
void GitSubmitHighlighter::highlightBlock(const QString &text)
{
    // figure out current state
    State state = Other;
    const QTextBlock block = currentBlock();
    if (block.position() == 0) {
        state = Header;
    } else {
        if (text.startsWith(m_hashChar))
            state = Comment;
    }
    // Apply format.
    switch (state) {
    case Header: {
            QTextCharFormat charFormat = format(0);
            charFormat.setFontWeight(QFont::Bold);
            setFormat(0, text.size(), charFormat);
    }
        break;
    case Comment:
        setFormat(0, text.size(), m_commentFormat);
        break;
    case Other:
        // Format key words ("Task:") italic
        if (m_keywordPattern.indexIn(text, 0, QRegExp::CaretAtZero) == 0) {
            QTextCharFormat charFormat = format(0);
            charFormat.setFontItalic(true);
            setFormat(0, m_keywordPattern.matchedLength(), charFormat);
        }
        break;
    }
}
void ChangeListLevelCommand::redo()
{
    if (!m_first) {
        KoTextCommandBase::redo();
        UndoRedoFinalizer finalizer(this);
        for (int i = 0; i < m_blocks.size(); ++i) {
            m_lists.value(i)->updateStoredList(m_blocks.at(i));
            QTextBlock currentBlock(m_blocks.at(i));
            KoTextBlockData userData(currentBlock);
            userData.setCounterWidth(-1.0);
        }
    }
    else {
        for (int i = 0; i < m_blocks.size() && m_lists.value(i); ++i) {
            if (!m_lists.value(i)->style()->hasLevelProperties(m_levels.value(i))) {
                KoListLevelProperties llp = m_lists.value(i)->style()->levelProperties(m_levels.value(i));
                if (llp.alignmentMode() == false) {
                    //old list mode, see KoListLevelProperties::alignmentMode() documentation
                    llp.setIndent((m_levels.value(i)-1) * 20); //TODO make this configurable
                } else {
                    llp.setTabStopPosition(MARGIN_DEFAULT*(m_levels.value(i)+1));
                    llp.setMargin(MARGIN_DEFAULT*(m_levels.value(i)+1));
                    llp.setTextIndent(- MARGIN_DEFAULT);
                }
                llp.setDisplayLevel(llp.displayLevel() + m_coefficient);
                llp.setLevel(m_levels.value(i));

                m_lists.value(i)->style()->setLevelProperties(llp);
            }
            m_lists.value(i)->add(m_blocks.at(i), m_levels.value(i));
        }
    }
    m_first = false;
}
Beispiel #9
0
bool XLHighlighter::showSelectionInFragment(QTextFragment fragment)
// ----------------------------------------------------------------------------
//    Highlight (part of) fragment containing code related to a selected object
// ----------------------------------------------------------------------------
{
    bool matched = false;
    int spos= fragment.position();
    int epos = spos + fragment.length();
    int blockstart = currentBlock().begin().fragment().position();

    XL::stream_range frag(spos, epos);
    XL::stream_ranges::iterator r;
    for (r = selected.begin(); r != selected.end(); r++)
    {
        XL::stream_range i = intersect((*r), frag);
        if (i.first != -1)
        {
            int hstart = (int)(i.first) - blockstart;
            int hcount = (int)(i.second - i.first);
            setFormat(hstart, hcount, selectedFormat);
            matched = true;
        }
    }
    return matched;
}
int64_t CopyOnWriteIterator::countRemaining() const {
    if (m_currentBlock == NULL) {
        return 0;
    }
    TableTuple out(m_table->schema());
    uint32_t blockOffset = m_blockOffset;
    char *location = m_location;
    TupleBlock *pcurrentBlock = m_currentBlock.get();
    TBPtr currentBlock(pcurrentBlock);
    TBMapI blockIterator = m_blockIterator;
    int64_t count = 0;
    while (true) {
        if (blockOffset >= currentBlock->unusedTupleBoundary()) {
            if (blockIterator == m_end) {
                break;
            }
            location = blockIterator.key();
            currentBlock = blockIterator.data();
            assert(currentBlock->address() == location);
            blockOffset = 0;
            blockIterator++;
        }
        blockOffset++;
        out.move(location);
        location += m_tupleLength;
        if (out.isActive() && !out.isDirty()) {
            count++;
        }
    }
    return count;
}
Beispiel #11
0
bool BinIArchive::openNode(const char* name)
{
	Block block(0, 0);
	if(currentBlock().get(name, block)){
		blocks_.push_back(block);
		return true;
	}
	return false;
}
Beispiel #12
0
bool CodeGenContext::LookupBitVariable(BitVariable& outVar,const std::string& module, const std::string& name,const YYLTYPE &modLoc,const YYLTYPE &nameLoc)
{
	if ((currentBlock()!=nullptr) && (locals().find(name) != locals().end()))
	{
		outVar=locals()[name];
		outVar.refLoc = nameLoc;
	}
	else
	{
		if (globals().find(name) == globals().end())
		{
			if (m_includes.find(module)!=m_includes.end())
			{
				if (m_includes[module]->LookupBitVariable(outVar,"",name,modLoc,nameLoc))
				{
					if (outVar.pinType!=0)		// TODO: Globals Vars!
					{
						outVar.fromExternal=true;
						outVar.refLoc = CombineTokenLocations(nameLoc,modLoc);
						return true;
					}
					else
					{
						return gContext.ReportError(false, EC_InternalError, CombineTokenLocations(nameLoc, modLoc), "TODO: Globals");
					}
				}
				else
				{
					return gContext.ReportError(false, EC_ErrorAtLocation, CombineTokenLocations(nameLoc,modLoc), "undeclared variable %s%s", module.c_str(), name.c_str());
				}
			}
			else if (isRoot)
			{
				if (module == "")
				{
					return gContext.ReportError(false, EC_ErrorAtLocation, nameLoc, "undeclared variable %s", name.c_str());
				}
				else
				{
					return gContext.ReportError(false, EC_ErrorAtLocation, CombineTokenLocations(nameLoc,modLoc), "undeclared variable %s%s", module.c_str(), name.c_str());
				}
			}
			return false;
		}
		else
		{
			outVar=globals()[name];
			outVar.refLoc = nameLoc;
		}
	}

	outVar.fromExternal=false;
	return true;
}
Beispiel #13
0
// coords are offsets in file
//
void pqHighlighter::highlightBlock(const QString &text)
{
    if (status == idle)
        return;

    if (!marker.isNull() && currentBlock() == marker.block()) {
        QTextCharFormat f;
        f.setBackground(Qt::yellow);
        int s = marker.selectionStart(), e = marker.selectionEnd(), b = marker.block().position();
        setFormat(s - b, e - s, f);
        marker = QTextCursor();
        return;
    }

    if (status == completed) {
        QTextBlock b = currentBlock();
        set_sem_attrs(b.position(), b.position() + b.length(), cats);
    }
    else
        pqMiniSyntax::highlightBlock(text);
}
void ChangeListLevelCommand::undo()
{
    KoTextCommandBase::undo();
    UndoRedoFinalizer finalizer(this);
    for (int i = 0; i < m_blocks.size(); ++i) {
        if (m_blocks.at(i).textList())
            m_lists.value(i)->updateStoredList(m_blocks.at(i));

        QTextBlock currentBlock(m_blocks.at(i));
        KoTextBlockData userData(currentBlock);
        userData.setCounterWidth(-1.0);
    }
}
void ScCodeEditor::toggleCommentSingleLine(QTextCursor cursor)
{
    QTextBlock currentBlock(cursor.block());

    cursor.beginEditBlock();

    if (!isSingleLineComment(currentBlock)) {
        int blockIndentation = indentationLevel(cursor);
        addSingleLineComment(cursor, blockIndentation);
    } else
        removeSingleLineComment(cursor);

    cursor.endEditBlock();
    indent(cursor);
}
void ScCodeEditor::addSingleLineComment(QTextCursor cursor, int indentation)
{
    QTextBlock currentBlock(cursor.block());
    int blockIndentationLevel = indentationLevel(cursor);

    cursor.movePosition(QTextCursor::StartOfBlock);
    cursor.setPosition(cursor.position() + indentedStartOfLine(currentBlock), QTextCursor::KeepAnchor);

    QString commentString = makeIndentationString(indentation) + QString("// ")
                            + makeIndentationString(blockIndentationLevel - indentation);

    cursor.insertText(commentString);

    cursor.movePosition(QTextCursor::StartOfBlock);
}
Beispiel #17
0
bool BinIArchive::operator()(ContainerInterface& ser, const char* name, const char* label)
{
	if(strlen(name)){
		if(!openNode(name))
			return false;

		size_t size = currentBlock().readPackedSize();
		ser.resize(size);

		if(size > 0){
			int i = 0;
			do{
				char buffer[16];
#ifdef _MSC_VER
				_itoa(i++, buffer, 10);
#else
				sprintf(buffer, "%d", i++);
#endif
				ser(*this, buffer, "");
			}
			while(ser.next());
		}
		closeNode(name);
		return true;
	}
	else{
		size_t size = currentBlock().readPackedSize();
		ser.resize(size);
		if(size > 0){
			do
				ser(*this, "", "");
				while(ser.next());
		}
		return true;
	}
}
Beispiel #18
0
void ConditionHighlighter::highlightBlock(const QString &text)
{
    if(text.isEmpty())
        return;
    int startPosition = currentBlock().position();
    int endPosition = startPosition + text.length();

    for(QVector<Token *>::iterator iter = _tokens.begin()
        ; iter != _tokens.end(); ++iter)
    {
        Token *t = *iter;
        // Is this entire block contained in this token?
        if(t->startPos <= startPosition && t->endPos >= endPosition)
        {
            setFormat(0, text.length(), format(t->lexeme));
            return;
        }

        // Is the start position of this token in range?
        if(t->startPos >= startPosition && t->startPos < endPosition)
        {
            if(t->endPos > endPosition)
                setFormat(t->startPos - startPosition,
                          text.length() - (t->startPos - startPosition),
                          format(t->lexeme));
            else
                setFormat(t->startPos - startPosition,
                          t->endPos - t->startPos,
                          format(t->lexeme));
        }
        // If not is the end position in range?
        else if(t->endPos > startPosition && t->endPos <= endPosition)
        {
            if(t->startPos < startPosition)
                setFormat(0,
                          t->endPos - t->startPos,
                          format(t->lexeme));
            else
                setFormat(t->startPos - startPosition,
                          t->endPos - t->startPos,
                          format(t->lexeme));
        }
    }
}
void ScCodeEditor::removeSingleLineComment(QTextCursor cursor)
{
    QTextBlock currentBlock(cursor.block());
    cursor.movePosition(QTextCursor::StartOfBlock);
    const int startPosition = cursor.position();
    const int indentPosition = indentedStartOfLine(currentBlock);
    const int commentStartPosition = startPosition + indentPosition;

    cursor.setPosition(commentStartPosition);
    cursor.setPosition(commentStartPosition + 3, QTextCursor::KeepAnchor);

    if (!cursor.selectedText().endsWith(QString("// "))) {
        cursor.setPosition(commentStartPosition + 2, QTextCursor::KeepAnchor);
        if (!cursor.selectedText().endsWith(QString("//")))
            return;
    }

    cursor.insertText("");
}
SparseBlockStructure3D reparallelize(SparseBlockStructure3D const& originalStructure,
                                     plint blockLx, plint blockLy, plint blockLz)
{
    std::vector<std::pair<plint,plint> > rangesX, rangesY, rangesZ;
    Box3D boundingBox = originalStructure.getBoundingBox();
    linearBlockRepartition(boundingBox.x0, boundingBox.x1, blockLx, rangesX);
    linearBlockRepartition(boundingBox.y0, boundingBox.y1, blockLy, rangesY);
    linearBlockRepartition(boundingBox.z0, boundingBox.z1, blockLz, rangesZ);
    SparseBlockStructure3D newStructure(boundingBox);
    std::vector<plint> ids;
    std::vector<Box3D> intersections;
    for (pluint blockX=0; blockX<rangesX.size(); ++blockX) {
        for (pluint blockY=0; blockY<rangesY.size(); ++blockY) {
            for (pluint blockZ=0; blockZ<rangesZ.size(); ++blockZ) {
                Box3D currentBlock(rangesX[blockX].first, rangesX[blockX].second,
                                   rangesY[blockY].first, rangesY[blockY].second,
                                   rangesZ[blockZ].first, rangesZ[blockZ].second);
                ids.clear();
                intersections.clear();
                originalStructure.intersect(currentBlock, ids, intersections);
                // It is possible that the current block fully covers the domain of the old
                // distribution. In this case, simply add current block, in order to avoid
                // fragmentation. Note that this explicit test is really necessary, because
                // the function mergeIntersection, which is called below, is not always able
                // to reconstruct a full block from its fragments.
                if (currentBlock.nCells() == cumNcells(intersections)) {
                    plint nextId = newStructure.nextIncrementalId();
                    newStructure.addBlock(currentBlock, nextId);
                }
                else {
                    // Construct bigger blocks if possible, in order to avoid fragmentation.
                    mergeIntersections(intersections);
                    for(pluint iInters=0; iInters<intersections.size(); ++iInters) {
                        plint nextId = newStructure.nextIncrementalId();
                        newStructure.addBlock(intersections[iInters], nextId);
                    }
                }
            }
        }
    }
    return newStructure;
}
Beispiel #21
0
Json::Value toJson(std::unordered_map<h256, dev::eth::LocalisedLogEntries> const& _entriesByBlock, vector<h256> const& _order)
{
    Json::Value res(Json::arrayValue);
    for (auto const& i: _order)
    {
        auto entries = _entriesByBlock.at(i);
        Json::Value currentBlock(Json::objectValue);
        LocalisedLogEntry entry = entries[0];
        if (entry.mined)
        {

            currentBlock["blockNumber"] = entry.blockNumber;
            currentBlock["blockHash"] = toJS(entry.blockHash);
            currentBlock["type"] = "mined";
        }
        else
            currentBlock["type"] = "pending";

        currentBlock["polarity"] = entry.polarity == BlockPolarity::Live ? true : false;
        currentBlock["logs"] = Json::Value(Json::arrayValue);

        for (LocalisedLogEntry const& e: entries)
        {
            Json::Value log(Json::objectValue);
            log["logIndex"] = e.logIndex;
            log["transactionIndex"] = e.transactionIndex;
            log["transactionHash"] = toJS(e.transactionHash);
            log["address"] = toJS(e.address);
            log["data"] = toJS(e.data);
            log["topics"] = Json::Value(Json::arrayValue);
            for (auto const& t: e.topics)
                log["topics"].append(toJS(t));

            currentBlock["logs"].append(log);
        }

        res.append(currentBlock);
    }

    return res;
}
Beispiel #22
0
void Highlighter::highlightBlock( const QString &text )
{

   TheLexer.setSource( text.begin(), text.end() );

   QTextBlock previousBlock = currentBlock().previous();

   TheLexer.state( previousBlock.isValid() ? previousBlock.userData() : InitialState );

   Token Curr;

   while( !TheLexer.hasFinished() )
   {

      TheLexer.nextToken( Curr );
      setFormat( Curr.start(), Curr.length(), Formats[ Curr.type() ] );

   }

   setCurrentBlockUserData( TheLexer.state() );

}
Beispiel #23
0
/* Compile the AST into a module */
void CodeGenContext::generateCode(ast::Program& root)
{

	std::cout << "Generating code...\n";
	
	/* Create the top level interpreter function to call as entry */
	std::vector<Type*> argTypes;
	FunctionType *ftype = FunctionType::get(Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false);
	// change GlobalValue::InternalLinkage into ExternalLinkage
	mainFunction = Function::Create(ftype, GlobalValue::ExternalLinkage, "main", module);
	BasicBlock *bblock = BasicBlock::Create(getGlobalContext(), "entry", mainFunction, 0);
	
	CodeGenContext::printf = createPrintf(*this);

	/* Push a new variable/block context */
	pushBlock(bblock);
	currentFunction = mainFunction;
	for (auto label:labels){
		labelBlock[label]=BasicBlock::Create(getGlobalContext(), "label", mainFunction, 0);
	}
	root.CodeGen(*this); /* emit bytecode for the toplevel block */
	ReturnInst::Create(getGlobalContext(), currentBlock());
	popBlock();
	// popBlock();
	
	/* Print the bytecode in a human-readable format 
	   to see if our program compiled properly
	 */
	std::cout << "Code is generated.\n";
	PassManager pm;
	pm.add(createPrintModulePass(outs()));
	//pm.run(*module);

    // write IR to stderr
    std::cout<<"code is gen~~~\n";
    module->dump();
    std::cout<<"code is gen~!~\n";
}
/*
 * This sets the folding indent:
 * 0 for the first line of the diff header.
 * 1 for all the following lines of the diff header and all @@ lines.
 * 2 for everything else
 */
void DiffAndLogHighlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty())
        return;

    const int length = text.length();
    const TextEditor::TextStyle format = d->analyzeLine(text);

    if (format == TextEditor::C_ADDED_LINE) {
            // Mark trailing whitespace.
            const int trimmedLen = trimmedLength(text);
            setFormatWithSpaces(text, 0, trimmedLen, formatForCategory(format));
            if (trimmedLen != length)
                setFormat(trimmedLen, length - trimmedLen, d->m_addedTrailingWhiteSpaceFormat);
    } else if (format != TextEditor::C_TEXT) {
        setFormatWithSpaces(text, 0, length, formatForCategory(format));
    } else {
        formatSpaces(text);
    }

    // codefolding:
    TextEditor::TextBlockUserData *data =
            TextEditor::TextDocumentLayout::userData(currentBlock());
    QTC_ASSERT(data, return; );
Beispiel #25
0
void JSHighlighter::highlightBlock(const QString &text)
{
    // parsing state
    enum {
        Start = 0,
        Number = 1,
        Identifier = 2,
        String = 3,
        Comment = 4,
        Regex = 5
    };

    QList<int> bracketPositions;

    int blockState = previousBlockState();
    int bracketLevel = blockState >> 4;
    int state = blockState & 15;
    if (blockState < 0) {
        bracketLevel = 0;
        state = Start;
    }

    int start = 0;
    int i = 0;
    while (i <= text.length()) {
        QChar ch = (i < text.length()) ? text.at(i) : QChar();
        QChar next = (i < text.length() - 1) ? text.at(i + 1) : QChar();

        switch (state) {

        case Start:
            start = i;
            if (ch.isSpace()) {
                ++i;
            } else if (ch.isDigit()) {
                ++i;
                state = Number;
            } else if (ch.isLetter() || ch == '_') {
                ++i;
                state = Identifier;
            } else if (ch == '\'' || ch == '\"') {
                ++i;
                state = String;
            } else if (ch == '/' && next == '*') {
                ++i;
                ++i;
                state = Comment;
            } else if (ch == '/' && next == '/') {
                i = text.length();
                setFormat(start, text.length(), m_colors[JSEdit::Comment]);
            } else if (ch == '/' && next != '*') {
                ++i;
                state = Regex;
            } else {
                if (!QString("(){}[]").contains(ch))
                    setFormat(start, 1, m_colors[JSEdit::Operator]);
                if (ch =='{' || ch == '}') {
                    bracketPositions += i;
                    if (ch == '{')
                        bracketLevel++;
                    else
                        bracketLevel--;
                }
                ++i;
                state = Start;
            }
            break;

        case Number:
            if (ch.isSpace() || !ch.isDigit()) {
                setFormat(start, i - start, m_colors[JSEdit::Number]);
                state = Start;
            } else {
                ++i;
            }
            break;

        case Identifier:
            if (ch.isSpace() || !(ch.isDigit() || ch.isLetter() || ch == '_')) {
                QString token = text.mid(start, i - start).trimmed();
                if (m_keywords.contains(token))
                    setFormat(start, i - start, m_colors[JSEdit::Keyword]);
                else if (m_knownIds.contains(token))
                    setFormat(start, i - start, m_colors[JSEdit::BuiltIn]);
                state = Start;
            } else {
                ++i;
            }
            break;

        case String:
            if (ch == text.at(start)) {
                QChar prev = (i > 0) ? text.at(i - 1) : QChar();
                if (prev != '\\') {
                    ++i;
                    setFormat(start, i - start, m_colors[JSEdit::String]);
                    state = Start;
                } else {
                    ++i;
                }
            } else {
                ++i;
            }
            break;

        case Comment:
            if (ch == '*' && next == '/') {
                ++i;
                ++i;
                setFormat(start, i - start, m_colors[JSEdit::Comment]);
                state = Start;
            } else {
                ++i;
            }
            break;

        case Regex:
            if (ch == '/') {
                QChar prev = (i > 0) ? text.at(i - 1) : QChar();
                if (prev != '\\') {
                    ++i;
                    setFormat(start, i - start, m_colors[JSEdit::String]);
                    state = Start;
                } else {
                    ++i;
                }
            } else {
                ++i;
            }
            break;

        default:
            state = Start;
            break;
        }
    }

    if (state == Comment)
        setFormat(start, text.length(), m_colors[JSEdit::Comment]);
    else
        state = Start;

    if (!m_markString.isEmpty()) {
        int pos = 0;
        int len = m_markString.length();
        QTextCharFormat markerFormat;
        markerFormat.setBackground(m_colors[JSEdit::Marker]);
        markerFormat.setForeground(m_colors[JSEdit::Normal]);
        for (;;) {
            pos = text.indexOf(m_markString, pos, m_markCaseSensitivity);
            if (pos < 0)
                break;
            setFormat(pos, len, markerFormat);
            ++pos;
        }
    }

    if (!bracketPositions.isEmpty()) {
        JSBlockData *blockData = reinterpret_cast<JSBlockData*>(currentBlock().userData());
        if (!blockData) {
            blockData = new JSBlockData;
            currentBlock().setUserData(blockData);
        }
        blockData->bracketPositions = bracketPositions;
    }

    blockState = (state & 15) | (bracketLevel << 4);
    setCurrentBlockState(blockState);
}
Beispiel #26
0
void Highlighter::highlightBlock( const QString &ctext ){

    QString text=ctext;

    int i=0,n=text.length();
    while( i<n && text[i]<=' ' ) ++i;

    if( _editor->isMonkey() ){
        //
        // handle monkey block comments
        //
        int st=previousBlockState();
        int blkst=st;

        if( i<n && text[i]=='#' ){

            int i0=i+1;
            while( i0<n && text[i0]<=' ' ) ++i0;

            int i1=i0;
            while( i1<n && isIdent(text[i1]) ) ++i1;

            QString t=text.mid( i0,i1-i0 ).toLower();

            if( t=="rem" ){
                blkst=++st;
            }else if( t=="if" ){
                if( st>-1 ) blkst=++st;
            }else if( t=="end" || t=="endif" ){
                if( st>-1) blkst=st-1;
            }
        }

        setCurrentBlockState( blkst );

        if( st>-1 ){
            setFormat( 0,text.length(),_commentsColor );
            setCurrentBlockUserData( 0 );
            return;
        }
    }

    if( !_editor->isCode() ){
        setFormat( 0,text.length(),_defaultColor );
        setCurrentBlockUserData( 0 );
        return;
    }

    int indent=i;
    text=text.mid(i);

    int colst=0;
    QColor curcol=_defaultColor;

    QVector<QString> tokes;

    for(;;){

        QColor col=curcol;

        QString t=parseToke( text,col );
        if( t.isEmpty() ) break;

        if( t[0]>' ' ) tokes.push_back( t );

        if( col!=curcol ){
            setFormat( colst,i-colst,curcol );
            curcol=col;
            colst=i;
        }

        i+=t.length();
    }

    if( colst<n ) setFormat( colst,n-colst,curcol );

    if( _editor->isMonkey() ){
        //
        //Update user block data for code tree.
        //
        BlockData *data=0;

        QString decl=tokes.size()>0 ? tokes[0].toLower() : "";
        QString ident=tokes.size()>1 ? tokes[1] : "";

        if( (decl=="class" || decl=="interface" || decl=="method" || decl=="function") && !ident.isEmpty() ){
            QTextBlock block=currentBlock();
            data=dynamic_cast<BlockData*>( currentBlockUserData() );
            if( data && data->block()==block && data->decl()==decl && data->ident()==ident && data->indent()==indent ){
            }else{
                data=new BlockData( this,block,decl,ident,indent );
                setCurrentBlockUserData( data );
                insert( data );
            }
        }else{
            setCurrentBlockUserData( 0 );
        }
    }
}
kl::KLContext& currentKL()
{
  return currentBlock().klc(currentBlock().size()-1,true);
}
void HBQSyntaxHighlighter::highlightBlock( const QString &text )
{
   if( type == 0 )   /* PRG C C++ Sources */
   {
      if( ! initialized )
         return;

      if( editor )
      {
         int iFirstBlock = editor->firstVisibleBlockNumber();
         int iLastBlock = editor->lastVisibleBlockNumber();
         int iBlock = currentBlock().blockNumber();

         if( iBlock < iFirstBlock || iBlock > iLastBlock )
         {
            return;
         }
      }

      int index = 0;
      int length = 0;

      foreach( const HighlightingRule &rule, HighlightingRules )
      {
         index = rule.pattern.indexIn( text );
         while( index >= 0 )
         {
            length = rule.pattern.matchedLength();
            setFormat( index, length, rule.format );
            index = rule.pattern.indexIn( text, index + length );
         }
      }

      /* Defined constants */
      index = definedConstants.indexIn( text );
      while( index >= 0 )
      {
         length = definedConstants.matchedLength();
         setFormat( index, length, constantsFormat );
         index = definedConstants.indexIn( text, index + length );
      }

      /* Multi Line Comments - to ascertain if it is embedded in quotes */
      int startIndex = 0;
      int startSglLine = 0;
      if( previousBlockState() != 1 )
      {
         startIndex = commentStartExpression.indexIn( text );
         startSglLine = commentSingleLine.indexIn( text );
      }

      /* Quoted text */
      index = patternQuotation.indexIn( text );
      while( index >= 0 )
      {
         length = patternQuotation.matchedLength();
         setFormat( index, length, quotationFormat );
         if( startIndex > index && startIndex < index + length )
         {
            startIndex = -1;
         }
         if( startSglLine > index && startSglLine < index + length )
         {
            startSglLine = -1;
         }
         index = patternQuotation.indexIn( text, index + length );
      }

      /* Single Line Comments */
      if( startSglLine >= 0 )
      {
         index = commentSingleLine.indexIn( text );
         while( index >= 0 )
         {
            length = commentSingleLine.matchedLength();
            setFormat( index, length, singleLineCommentFormat );
            index = commentSingleLine.indexIn( text, index + length );
         }
      }
      /* Multi Line Comments - continued */
      setCurrentBlockState( 0 );

      while( startIndex >= 0 )
      {
         int commentLength;
         int endIndex = commentEndExpression.indexIn( text, startIndex );
         if( endIndex == -1 )
         {
            setCurrentBlockState( 1 );
            commentLength = text.length() - startIndex;
         }
         else
         {
            commentLength = endIndex - startIndex + commentEndExpression.matchedLength();
         }
         setFormat( startIndex, commentLength, multiLineCommentFormat );
         startIndex = commentStartExpression.indexIn( text, startIndex + commentLength );
      }
   }
Beispiel #29
0
void BinIArchive::closeNode(const char* name, bool check) 
{
	YASLI_ASSERT(!check || currentBlock().validToClose());
	blocks_.pop_back();
}
Beispiel #30
0
int HighlightCpp::highlight(const QString& text, int state)
{
    // highlight assembly lines
    if (m_srcWnd->isRowDisassCode(currentBlock().blockNumber()))
    {
	setFormat(0, text.length(), Qt::blue);
	return state;
    }

    if (state == -2)		// initial state
	state = 0;

    // check for preprocessor line
    if (state == 0 && text.trimmed().startsWith("#"))
    {
	setFormat(0, text.length(), QColor("darkgreen"));
	return 0;
    }

    // a font for keywords
    QTextCharFormat identFont;
    identFont.setFontWeight(QFont::Bold);

    int start = 0;
    while (start < text.length())
    {
	int end;
	switch (state) {
	case hlCommentLine:
	    end = text.length();
	    state = 0;
	    setFormat(start, end-start, QColor("gray"));
	    break;
	case hlCommentBlock:
	    end = text.indexOf("*/", start);
	    if (end >= 0)
		end += 2, state = 0;
	    else
		end = text.length();
	    setFormat(start, end-start, QColor("gray"));
	    break;
	case hlString:
	    for (end = start+1; end < int(text.length()); end++) {
		if (text[end] == '\\') {
		    if (end < int(text.length()))
			++end;
		} else if (text[end] == text[start]) {
		    ++end;
		    break;
		}
	    }
	    state = 0;
	    setFormat(start, end-start, QColor("darkred"));
	    break;
	case hlIdent:
	    for (end = start+1; end < int(text.length()); end++) {
		if (!text[end].isLetterOrNumber() && text[end] != '_')
		    break;
	    }
	    state = 0;
	    if (std::binary_search(ckw, ckw + sizeof(ckw)/sizeof(ckw[0]),
			text.mid(start, end-start)))
	    {
		setFormat(start, end-start, identFont);
	    } else {
		setFormat(start, end-start, m_srcWnd->palette().color(QPalette::WindowText));
	    }
	    break;
	default:
	    for (end = start; end < int(text.length()); end++)
	    {
		if (text[end] == '/')
		{
		    if (end+1 < int(text.length())) {
			if (text[end+1] == '/') {
			    state = hlCommentLine;
			    break;
			} else if (text[end+1] == '*') {
			    state = hlCommentBlock;
			    break;
			}
		    }
		}
		else if (text[end] == '"' || text[end] == '\'')
		{
		    state = hlString;
		    break;
		}
		else if ((text[end] >= 'A' && text[end] <= 'Z') ||
			 (text[end] >= 'a' && text[end] <= 'z') ||
			 text[end] == '_')
		{
		    state = hlIdent;
		    break;
		}
	    }
	    setFormat(start, end-start, m_srcWnd->palette().color(QPalette::WindowText));
	}
	start = end;
    }
    return state;
}