File: parsesession.cpp

package info (click to toggle)
kdevelop 4%3A25.04.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 73,508 kB
  • sloc: cpp: 291,803; python: 4,322; javascript: 3,518; sh: 1,316; ansic: 703; xml: 414; php: 95; lisp: 66; makefile: 31; sed: 12
file content (274 lines) | stat: -rw-r--r-- 8,637 bytes parent folder | download | duplicates (3)
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
197
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
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
/*
    SPDX-FileCopyrightText: 2012 Milian Wolff <mail@milianw.de>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "parsesession.h"
#include "debugvisitor.h"
#include "cache.h"

#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsengine_p.h>

#include <language/duchain/stringhelpers.h>
#include <language/duchain/duchain.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/declaration.h>
#include <language/backgroundparser/backgroundparser.h>
#include <language/editor/documentrange.h>
#include <interfaces/ilanguagecontroller.h>
#include <interfaces/icore.h>

using namespace KDevelop;

IndexedString ParseSession::languageString()
{
    static const IndexedString langString("QML/JS");
    return langString;
}

bool isSorted(const QList<QmlJS::AST::SourceLocation>& locations)
{
    if (locations.size() <= 1) {
        return true;
    }
    for(int i = 1; i < locations.size(); ++i) {
        if (locations.at(i).begin() <= locations.at(i-1).begin()) {
            return false;
        }
    }
    return true;
}

QmlJS::Dialect ParseSession::guessLanguageFromSuffix(const QString& path)
{
    if (path.endsWith(QLatin1String(".js"))) {
        return QmlJS::Dialect::JavaScript;
    } else if (path.endsWith(QLatin1String(".json"))) {
        return QmlJS::Dialect::Json;
    } else {
        return QmlJS::Dialect::Qml;
    }
}

ParseSession::ParseSession(const IndexedString& url, const QString& contents, int priority)
: m_url(url),
  m_ownPriority(priority),
  m_allDependenciesSatisfied(true)
{
    const QString path = m_url.str();
    m_doc = QmlJS::Document::create(path, guessLanguageFromSuffix(path));
    m_doc->setSource(contents);
    m_doc->parse();
    Q_ASSERT(isSorted(m_doc->engine()->comments()));

    // Parse the module name and the version of url (this is used only when the file
    // is a QML module, but doesn't break for JavaScript files)
    m_baseName = QString::fromUtf8(m_url.byteArray())
        .section(QLatin1Char('/'), -1, -1)                   // Base name
        .section(QLatin1Char('.'), 0, -2);                   // Without extension
}

bool ParseSession::isParsedCorrectly() const
{
    return m_doc->isParsedCorrectly();
}

QmlJS::AST::Node* ParseSession::ast() const
{
    return m_doc->ast();
}

IndexedString ParseSession::url() const
{
    return m_url;
}

QString ParseSession::moduleName() const
{
    return m_baseName;
}

void ParseSession::addProblem(QmlJS::AST::Node* node,
                              const QString& message,
                              IProblem::Severity severity)
{
    ProblemPointer p(new Problem);

    p->setDescription(message);
    p->setSeverity(severity);
    p->setSource(IProblem::SemanticAnalysis);
    p->setFinalLocation(DocumentRange(m_url, editorFindRange(node, node).castToSimpleRange()));

    m_problems << p;
}

QList<ProblemPointer> ParseSession::problems() const
{
    QList<ProblemPointer> problems = m_problems;

    const auto diagnosticMessages = m_doc->diagnosticMessages();
    problems.reserve(problems.size() + diagnosticMessages.size());
    for (const auto& msg : diagnosticMessages) {
        ProblemPointer p(new Problem);
        p->setDescription(msg.message);
        p->setSeverity(IProblem::Error);
        p->setSource(IProblem::Parser);
        p->setFinalLocation(DocumentRange(m_url, locationToRange(msg.loc).castToSimpleRange()));
        problems << p;
    }

    return problems;
}

QString ParseSession::symbolAt(const QmlJS::AST::SourceLocation& location) const
{
    return m_doc->source().mid(location.offset, location.length);
}

QmlJS::Dialect ParseSession::language() const
{
    return m_doc->language();
}

bool compareSourceLocation(const QmlJS::AST::SourceLocation& l,
                           const QmlJS::AST::SourceLocation& r)
{
    return l.begin() < r.begin();
}

QString ParseSession::commentForLocation(const QmlJS::AST::SourceLocation& location) const
{
    // find most recent comment in sorted list of comments
    const QList< QmlJS::AST::SourceLocation >& comments = m_doc->engine()->comments();
    auto it = std::lower_bound(
        comments.constBegin(),
        comments.constEnd(),
        location, compareSourceLocation
    );

    if (it == comments.constBegin()) {
        return QString();
    }

    // lower bound returns the place of insertion,
    // we want the comment before that
    it--;
    RangeInRevision input = locationToRange(location);
    RangeInRevision match = locationToRange(*it);
    if (match.end.line != input.start.line - 1 && match.end.line != input.start.line) {
        return QString();
    }

    ///TODO: merge consecutive //-style comments?
    return formatComment(symbolAt(*it));
}

RangeInRevision ParseSession::locationToRange(const QmlJS::AST::SourceLocation& location) const
{
    const int linesInLocation = m_doc->source().midRef(location.offset, location.length).count(QLatin1Char('\n'));
    return RangeInRevision(location.startLine - 1, location.startColumn - 1,
                           location.startLine - 1 + linesInLocation, location.startColumn - 1 + location.length);
}

RangeInRevision ParseSession::locationsToRange(const QmlJS::AST::SourceLocation& locationFrom,
                                               const QmlJS::AST::SourceLocation& locationTo) const
{
    return RangeInRevision(locationToRange(locationFrom).start,
                           locationToRange(locationTo).end);
}

RangeInRevision ParseSession::locationsToInnerRange(const QmlJS::AST::SourceLocation& locationFrom,
                                                    const QmlJS::AST::SourceLocation& locationTo) const
{
    return RangeInRevision(locationToRange(locationFrom).end,
                           locationToRange(locationTo).start);
}

RangeInRevision ParseSession::editorFindRange(QmlJS::AST::Node* fromNode, QmlJS::AST::Node* toNode) const
{
    return locationsToRange(fromNode->firstSourceLocation(), toNode->lastSourceLocation());
}

void ParseSession::setContextOnNode(QmlJS::AST::Node* node, DUContext* context)
{
    m_astToContext.insert(node, DUContextPointer(context));
}

DUContext* ParseSession::contextFromNode(QmlJS::AST::Node* node) const
{
    return m_astToContext.value(node, DUContextPointer()).data();
}

bool ParseSession::allDependenciesSatisfied() const
{
    return m_allDependenciesSatisfied;
}

ReferencedTopDUContext ParseSession::contextOfFile(const QString& fileName)
{
    ReferencedTopDUContext res = contextOfFile(fileName, m_url, m_ownPriority);

    if (!res) {
        // The file was not yet present in the DUChain, store this information.
        // This will prevent the second parsing pass from running (it would be
        // useless as the file will be re-parsed when res will become available)
        m_allDependenciesSatisfied = false;
    }

    return res;
}

ReferencedTopDUContext ParseSession::contextOfFile(const QString& fileName,
                                                   const KDevelop::IndexedString& url,
                                                   int ownPriority)
{
    if (fileName.isEmpty()) {
        return ReferencedTopDUContext();
    }

    // Get the top context of this module file
    DUChainReadLocker lock;
    IndexedString moduleFileString(fileName);
    ReferencedTopDUContext moduleContext = DUChain::self()->chainForDocument(moduleFileString);

    lock.unlock();
    QmlJS::Cache::instance().addDependency(url, moduleFileString);

    if (!moduleContext) {
        // Queue the file on which we depend with a lower priority than the one of this file
        scheduleForParsing(moduleFileString, ownPriority - 1);

        // Register a dependency between this file and the imported one
        return ReferencedTopDUContext();
    } else {
        return moduleContext;
    }
}

void ParseSession::reparseImporters()
{
    const auto& files = QmlJS::Cache::instance().filesThatDependOn(m_url);
    for (const KDevelop::IndexedString& file : files) {
        scheduleForParsing(file, m_ownPriority);
    }
}

void ParseSession::scheduleForParsing(const IndexedString& url, int priority)
{
    BackgroundParser* bgparser = KDevelop::ICore::self()->languageController()->backgroundParser();
    const auto features = TopDUContext::ForceUpdate | TopDUContext::AllDeclarationsContextsAndUses;

    if (bgparser->isQueued(url)) {
        bgparser->removeDocument(url);
    }

    bgparser->addDocument(url, features, priority, nullptr, ParseJob::FullSequentialProcessing);
}

void ParseSession::dumpNode(QmlJS::AST::Node* node) const
{
    DebugVisitor v(this);
    v.startVisiting(node);
}