qmljssemantichighlighter.cpp 13.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "qmljssemantichighlighter.h"

#include "qmljseditor.h"

#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljsscopechain.h>
#include <qmljs/qmljsscopebuilder.h>
#include <qmljs/qmljsevaluate.h>
#include <qmljs/qmljscontext.h>
#include <qmljs/qmljsbind.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsastvisitor_p.h>
#include <texteditor/syntaxhighlighter.h>
#include <texteditor/basetextdocument.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/fontsettings.h>
#include <utils/qtcassert.h>

#include <QtCore/QThreadPool>
#include <QtCore/QFutureInterface>
#include <QtCore/QRunnable>

using namespace QmlJSEditor;
using namespace QmlJSEditor::Internal;
using namespace QmlJS;
using namespace QmlJS::AST;

namespace {

template <typename T>
class PriorityTask :
        public QFutureInterface<T>,
        public QRunnable
{
public:
    typedef QFuture<T> Future;

    Future start(QThread::Priority priority)
    {
        this->setRunnable(this);
        this->reportStarted();
        Future future = this->future();
        QThreadPool::globalInstance()->start(this, priority);
        return future;
    }
};

static bool isIdScope(const ObjectValue *scope, const QList<const QmlComponentChain *> &chain)
{
    foreach (const QmlComponentChain *c, chain) {
        if (c->idScope() == scope)
            return true;
        if (isIdScope(scope, c->instantiatingComponents()))
            return true;
    }
    return false;
}

class CollectStateNames : protected Visitor
{
    QStringList m_stateNames;
    bool m_inStateType;
    ScopeChain m_scopeChain;
    const QmlObjectValue *m_statePrototype;

public:
    CollectStateNames(const ScopeChain &scopeChain)
        : m_scopeChain(scopeChain)
    {
        m_statePrototype = scopeChain.context()->valueOwner()->cppQmlTypes().typeByCppName(QLatin1String("QDeclarativeState"));
    }

    QStringList operator()(Node *ast)
    {
        m_stateNames.clear();
        if (!m_statePrototype)
            return m_stateNames;
        m_inStateType = false;
        accept(ast);
        return m_stateNames;
    }

protected:
    void accept(Node *ast)
    {
        if (ast)
            ast->accept(this);
    }

    bool preVisit(Node *ast)
    {
        return ast->uiObjectMemberCast()
                || cast<UiProgram *>(ast)
                || cast<UiObjectInitializer *>(ast)
                || cast<UiObjectMemberList *>(ast)
                || cast<UiArrayMemberList *>(ast);
    }

    bool hasStatePrototype(Node *ast)
    {
        Bind *bind = m_scopeChain.document()->bind();
        const ObjectValue *v = bind->findQmlObject(ast);
        if (!v)
            return false;
        PrototypeIterator it(v, m_scopeChain.context());
        while (it.hasNext()) {
            const ObjectValue *proto = it.next();
            const QmlObjectValue *qmlProto = dynamic_cast<const QmlObjectValue *>(proto);
            if (!qmlProto)
                continue;
            if (qmlProto->metaObject() == m_statePrototype->metaObject())
                return true;
        }
        return false;
    }

    bool visit(UiObjectDefinition *ast)
    {
        const bool old = m_inStateType;
        m_inStateType = hasStatePrototype(ast);
        accept(ast->initializer);
        m_inStateType = old;
        return false;
    }

    bool visit(UiObjectBinding *ast)
    {
        const bool old = m_inStateType;
        m_inStateType = hasStatePrototype(ast);
        accept(ast->initializer);
        m_inStateType = old;
        return false;
    }

    bool visit(UiScriptBinding *ast)
    {
        if (!m_inStateType)
            return false;
        if (!ast->qualifiedId || ! ast->qualifiedId->name || ast->qualifiedId->next)
            return false;
        if (ast->qualifiedId->name->asString() != QLatin1String("name"))
            return false;

        ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement);
        if (!expStmt)
            return false;
        StringLiteral *strLit = cast<StringLiteral *>(expStmt->expression);
        if (!strLit || !strLit->value)
            return false;

        m_stateNames += strLit->value->asString();

        return false;
    }
};

class CollectionTask :
        public PriorityTask<SemanticHighlighter::Use>,
        protected Visitor
{
public:
    CollectionTask(const ScopeChain &scopeChain)
        : m_scopeChain(scopeChain)
        , m_scopeBuilder(&m_scopeChain)
197
        , m_lineOfLastUse(0)
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    {}

protected:
    void accept(Node *ast)
    {
        if (ast)
            ast->accept(this);
    }

    void scopedAccept(Node *ast, Node *child)
    {
        m_scopeBuilder.push(ast);
        accept(child);
        m_scopeBuilder.pop();
    }

    void processName(NameId *name, SourceLocation location)
    {
        if (!name)
            return;

        const QString nameStr = name->asString();
        const ObjectValue *scope = 0;
        const Value *value = m_scopeChain.lookup(nameStr, &scope);
        if (!value || !scope)
            return;

225
        SemanticHighlighter::UseType type = SemanticHighlighter::UnknownType;
226
        if (m_scopeChain.qmlTypes() == scope) {
227
            type = SemanticHighlighter::QmlTypeType;
228
        } else if (m_scopeChain.qmlScopeObjects().contains(scope)) {
229
            type = SemanticHighlighter::ScopeObjectPropertyType;
230
        } else if (m_scopeChain.jsScopes().contains(scope)) {
231
            type = SemanticHighlighter::JsScopeType;
232
        } else if (m_scopeChain.jsImports() == scope) {
233
            type = SemanticHighlighter::JsImportType;
234
        } else if (m_scopeChain.globalScope() == scope) {
235 236 237 238 239 240 241 242 243 244 245
            type = SemanticHighlighter::JsGlobalType;
        } else if (QSharedPointer<const QmlComponentChain> chain = m_scopeChain.qmlComponentChain()) {
            if (scope == chain->idScope()) {
                type = SemanticHighlighter::LocalIdType;
            } else if (isIdScope(scope, chain->instantiatingComponents())) {
                type = SemanticHighlighter::ExternalIdType;
            } else if (scope == chain->rootObjectScope()) {
                type = SemanticHighlighter::RootObjectPropertyType;
            }
        } else { // check for this?
            type = SemanticHighlighter::ExternalObjectPropertyType;
246 247
        }

248
        addUse(location, type);
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    }

    bool visit(UiObjectDefinition *ast)
    {
        scopedAccept(ast, ast->initializer);
        return false;
    }

    bool visit(UiObjectBinding *ast)
    {
        scopedAccept(ast, ast->initializer);
        return false;
    }

    bool visit(UiScriptBinding *ast)
    {
        scopedAccept(ast, ast->statement);
        return false;
    }

    bool visit(UiPublicMember *ast)
    {
        scopedAccept(ast, ast->statement);
        return false;
    }

    bool visit(FunctionExpression *ast)
    {
        processName(ast->name, ast->identifierToken);
        scopedAccept(ast, ast->body);
        return false;
    }

    bool visit(FunctionDeclaration *ast)
    {
        return visit(static_cast<FunctionExpression *>(ast));
    }

    bool visit(VariableDeclaration *ast)
    {
        processName(ast->name, ast->identifierToken);
        return true;
    }

    bool visit(IdentifierExpression *ast)
    {
        processName(ast->name, ast->identifierToken);
        return false;
    }

    bool visit(StringLiteral *ast)
    {
        if (!ast->value)
            return false;

        const QString value = ast->value->asString();
        if (m_stateNames.contains(value)) {
306
            addUse(ast->literalToken, SemanticHighlighter::LocalStateNameType);
307 308 309 310 311 312 313 314 315 316 317
        }

        return false;
    }

private:
    void run()
    {
        Node *root = m_scopeChain.document()->ast();
        m_stateNames = CollectStateNames(m_scopeChain)(root);
        accept(root);
318
        flush();
319 320 321
        reportFinished();
    }

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    void addUse(const SourceLocation &location, SemanticHighlighter::UseType type)
    {
        addUse(SemanticHighlighter::Use(location.startLine, location.startColumn, location.length, type));
    }

    static const int chunkSize = 50;

    void addUse(const SemanticHighlighter::Use &use)
    {
        if (m_uses.size() >= chunkSize) {
            if (use.line > m_lineOfLastUse)
                flush();
        }

        m_lineOfLastUse = qMax(m_lineOfLastUse, use.line);
        m_uses.append(use);
    }

    static bool sortByLinePredicate(const SemanticHighlighter::Use &lhs, const SemanticHighlighter::Use &rhs)
    {
        return lhs.line < rhs.line;
    }

    void flush()
    {
        m_lineOfLastUse = 0;

        if (m_uses.isEmpty())
            return;

        qSort(m_uses.begin(), m_uses.end(), sortByLinePredicate);
        reportResults(m_uses);
        m_uses.clear();
        m_uses.reserve(chunkSize);
    }

358 359 360
    ScopeChain m_scopeChain;
    ScopeBuilder m_scopeBuilder;
    QStringList m_stateNames;
361 362
    QVector<SemanticHighlighter::Use> m_uses;
    unsigned m_lineOfLastUse;
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
};

} // anonymous namespace

SemanticHighlighter::SemanticHighlighter(QmlJSTextEditorWidget *editor)
    : QObject(editor)
    , m_editor(editor)
    , m_startRevision(0)
{
    connect(&m_watcher, SIGNAL(resultsReadyAt(int,int)),
            this, SLOT(applyResults(int,int)));
    connect(&m_watcher, SIGNAL(finished()),
            this, SLOT(finished()));
}

void SemanticHighlighter::rerun(const ScopeChain &scopeChain)
{
    m_watcher.cancel();

    // this does not simply use QtConcurrentRun because we want a low-priority future
    // the thread pool deletes the task when it is done
    CollectionTask::Future f = (new CollectionTask(scopeChain))->start(QThread::LowestPriority);
    m_startRevision = m_editor->editorRevision();
    m_watcher.setFuture(f);
}

void SemanticHighlighter::applyResults(int from, int to)
{
    if (m_watcher.isCanceled())
        return;
    if (m_startRevision != m_editor->editorRevision())
        return;

    TextEditor::BaseTextDocument *baseTextDocument = m_editor->baseTextDocument();
    QTC_ASSERT(baseTextDocument, return);
    TextEditor::SyntaxHighlighter *highlighter = qobject_cast<TextEditor::SyntaxHighlighter *>(baseTextDocument->syntaxHighlighter());
    QTC_ASSERT(highlighter, return);

    TextEditor::SemanticHighlighter::incrementalApplyExtraAdditionalFormats(
                highlighter, m_watcher.future(), from, to, m_formats);
}

void SemanticHighlighter::finished()
{
    if (m_watcher.isCanceled())
        return;
    if (m_startRevision != m_editor->editorRevision())
        return;

    TextEditor::BaseTextDocument *baseTextDocument = m_editor->baseTextDocument();
    QTC_ASSERT(baseTextDocument, return);
    TextEditor::SyntaxHighlighter *highlighter = qobject_cast<TextEditor::SyntaxHighlighter *>(baseTextDocument->syntaxHighlighter());
    QTC_ASSERT(highlighter, return);

    TextEditor::SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd(
                highlighter, m_watcher.future());
}

void SemanticHighlighter::updateFontSettings(const TextEditor::FontSettings &fontSettings)
{
    m_formats[LocalIdType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_QML_LOCAL_ID));
    m_formats[ExternalIdType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_QML_EXTERNAL_ID));
    m_formats[QmlTypeType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_QML_TYPE_ID));
    m_formats[RootObjectPropertyType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_QML_ROOT_OBJECT_PROPERTY));
    m_formats[ScopeObjectPropertyType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_QML_SCOPE_OBJECT_PROPERTY));
    m_formats[ExternalObjectPropertyType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_QML_EXTERNAL_OBJECT_PROPERTY));
    m_formats[JsScopeType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_JS_SCOPE_VAR));
    m_formats[JsImportType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_JS_IMPORT_VAR));
    m_formats[JsGlobalType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_JS_GLOBAL_VAR));
    m_formats[LocalStateNameType] = fontSettings.toTextCharFormat(QLatin1String(TextEditor::Constants::C_QML_STATE_NAME));
}