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 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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 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 358 359 360 361 362 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
|
/*
SPDX-FileCopyrightText: 2006 Adam Treat <treat@kde.org>
SPDX-FileCopyrightText: 2006-2008 Hamish Rodda <rodda@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "parsejob.h"
#include <QFile>
#include <QMutex>
#include <QMutexLocker>
#include <QStandardPaths>
#include <KLocalizedString>
#include <KFormat>
#include <KTextEditor/MovingInterface>
#include "backgroundparser.h"
#include <debug.h>
#include "duchain/topducontext.h"
#include "duchain/duchainlock.h"
#include "duchain/duchain.h"
#include "duchain/parsingenvironment.h"
#include "editor/documentrange.h"
#include <util/foregroundlock.h>
#include <util/kdevstringhandler.h>
#include <interfaces/icore.h>
#include <interfaces/ilanguagecontroller.h>
#include <codegen/coderepresentation.h>
#include <duchain/declaration.h>
#include <duchain/use.h>
#include <interfaces/icodehighlighting.h>
#include <duchain/problem.h>
using namespace KTextEditor;
static QMutex minimumFeaturesMutex;
static QHash<KDevelop::IndexedString, QList<KDevelop::TopDUContext::Features>> staticMinimumFeatures;
namespace KDevelop {
class ParseJobPrivate
{
public:
ParseJobPrivate(const IndexedString& url_, ILanguageSupport* languageSupport_) :
url(url_)
, languageSupport(languageSupport_)
, abortRequested(0)
, hasReadContents(false)
, aborted(false)
, features(TopDUContext::VisibleDeclarationsAndContexts)
, parsePriority(0)
, sequentialProcessingFlags(ParseJob::IgnoresSequentialProcessing)
, maximumFileSize(5 * 1024 * 1024) // 5 MB
{
}
~ParseJobPrivate()
{
}
ReferencedTopDUContext duContext;
IndexedString url;
ILanguageSupport* languageSupport;
ParseJob::Contents contents;
QAtomicInt abortRequested;
bool hasReadContents : 1;
bool aborted : 1;
TopDUContext::Features features;
QVector<QPointer<QObject>> notify;
QPointer<DocumentChangeTracker> tracker;
RevisionReference revision;
RevisionReference previousRevision;
int parsePriority;
ParseJob::SequentialProcessingFlags sequentialProcessingFlags;
qint64 maximumFileSize;
};
ParseJob::ParseJob(const IndexedString& url, KDevelop::ILanguageSupport* languageSupport)
: ThreadWeaver::Sequence()
, d_ptr(new ParseJobPrivate(url, languageSupport))
{
}
ParseJob::~ParseJob()
{
Q_D(ParseJob);
for (auto& p : qAsConst(d->notify)) {
if (p) {
QMetaObject::invokeMethod(p.data(), "updateReady", Qt::QueuedConnection,
Q_ARG(KDevelop::IndexedString, d->url),
Q_ARG(KDevelop::ReferencedTopDUContext, d->duContext));
}
}
}
ILanguageSupport* ParseJob::languageSupport() const
{
Q_D(const ParseJob);
return d->languageSupport;
}
void ParseJob::setParsePriority(int priority)
{
Q_D(ParseJob);
d->parsePriority = priority;
}
int ParseJob::parsePriority() const
{
Q_D(const ParseJob);
return d->parsePriority;
}
bool ParseJob::requiresSequentialProcessing() const
{
Q_D(const ParseJob);
return d->sequentialProcessingFlags & RequiresSequentialProcessing;
}
bool ParseJob::respectsSequentialProcessing() const
{
Q_D(const ParseJob);
return d->sequentialProcessingFlags & RespectsSequentialProcessing;
}
void ParseJob::setSequentialProcessingFlags(SequentialProcessingFlags flags)
{
Q_D(ParseJob);
d->sequentialProcessingFlags = flags;
}
qint64 ParseJob::maximumFileSize() const
{
Q_D(const ParseJob);
return d->maximumFileSize;
}
void ParseJob::setMaximumFileSize(qint64 value)
{
Q_D(ParseJob);
d->maximumFileSize = value;
}
IndexedString ParseJob::document() const
{
Q_D(const ParseJob);
return d->url;
}
bool ParseJob::success() const
{
Q_D(const ParseJob);
return !d->aborted;
}
void ParseJob::setMinimumFeatures(TopDUContext::Features features)
{
Q_D(ParseJob);
d->features = features;
}
bool ParseJob::hasStaticMinimumFeatures()
{
QMutexLocker lock(&minimumFeaturesMutex);
return !::staticMinimumFeatures.isEmpty();
}
TopDUContext::Features ParseJob::staticMinimumFeatures(const IndexedString& url)
{
QMutexLocker lock(&minimumFeaturesMutex);
TopDUContext::Features features{};
const auto featuresIt = ::staticMinimumFeatures.constFind(url);
if (featuresIt != ::staticMinimumFeatures.constEnd())
for (const TopDUContext::Features f : *featuresIt)
features |= f;
return features;
}
TopDUContext::Features ParseJob::minimumFeatures() const
{
Q_D(const ParseJob);
return d->features | staticMinimumFeatures(d->url);
}
void ParseJob::setDuChain(const ReferencedTopDUContext& duChain)
{
Q_D(ParseJob);
d->duContext = duChain;
}
ReferencedTopDUContext ParseJob::duChain() const
{
Q_D(const ParseJob);
return d->duContext;
}
bool ParseJob::abortRequested() const
{
Q_D(const ParseJob);
return d->abortRequested.loadRelaxed() != 0;
}
void ParseJob::requestAbort()
{
Q_D(ParseJob);
d->abortRequested = 1;
}
void ParseJob::abortJob()
{
Q_D(ParseJob);
d->aborted = true;
setStatus(Status_Aborted);
}
void ParseJob::setNotifyWhenReady(const QVector<QPointer<QObject>>& notify)
{
Q_D(ParseJob);
d->notify = notify;
}
void ParseJob::setStaticMinimumFeatures(const IndexedString& url, TopDUContext::Features features)
{
QMutexLocker lock(&minimumFeaturesMutex);
::staticMinimumFeatures[url].append(features);
}
void ParseJob::unsetStaticMinimumFeatures(const IndexedString& url, TopDUContext::Features features)
{
QMutexLocker lock(&minimumFeaturesMutex);
::staticMinimumFeatures[url].removeOne(features);
if (::staticMinimumFeatures[url].isEmpty())
::staticMinimumFeatures.remove(url);
}
KDevelop::ProblemPointer ParseJob::readContents()
{
Q_D(ParseJob);
Q_ASSERT(!d->hasReadContents);
d->hasReadContents = true;
QString localFile(document().toUrl().toLocalFile());
QFileInfo fileInfo(localFile);
QDateTime lastModified = fileInfo.lastModified();
d->tracker = ICore::self()->languageController()->backgroundParser()->trackerForUrl(document());
//Try using an artificial code-representation, which overrides everything else
if (artificialCodeRepresentationExists(document())) {
CodeRepresentation::Ptr repr = createCodeRepresentation(document());
d->contents.contents = repr->text().toUtf8();
qCDebug(LANGUAGE) << "took contents for " << document().str() << " from artificial code-representation";
return KDevelop::ProblemPointer();
}
bool hadTracker = false;
if (d->tracker) {
ForegroundLock lock;
if (DocumentChangeTracker* t = d->tracker.data()) {
// The file is open in an editor
d->previousRevision = t->revisionAtLastReset();
t->reset(); // Reset the tracker to the current revision
Q_ASSERT(t->revisionAtLastReset());
d->contents.contents = t->document()->text().toUtf8();
d->contents.modification =
KDevelop::ModificationRevision(lastModified, t->revisionAtLastReset()->revision());
d->revision = t->acquireRevision(d->contents.modification.revision);
hadTracker = true;
}
}
if (!hadTracker) {
// We have to load the file from disk
if (fileInfo.size() > d->maximumFileSize) {
KFormat f;
KDevelop::ProblemPointer p(new Problem());
p->setSource(IProblem::Disk);
p->setDescription(i18nc("%1: filename", "Skipped file that is too large: '%1'", localFile));
p->setExplanation(i18nc("%1: file size, %2: limit file size",
"The file is %1 and exceeds the limit of %2.",
f.formatByteSize(fileInfo.size()),
f.formatByteSize(d->maximumFileSize)));
p->setFinalLocation(DocumentRange(document(), KTextEditor::Range::invalid()));
qCWarning(LANGUAGE) << p->description() << p->explanation();
return p;
}
QFile file(localFile);
if (!file.open(QIODevice::ReadOnly)) {
KDevelop::ProblemPointer p(new Problem());
p->setSource(IProblem::Disk);
p->setDescription(i18n("Could not open file '%1'", localFile));
switch (file.error()) {
case QFile::ReadError:
p->setExplanation(i18n("File could not be read from disk."));
break;
case QFile::OpenError:
p->setExplanation(i18n("File could not be opened."));
break;
case QFile::PermissionsError:
p->setExplanation(i18n("File could not be read from disk due to permissions."));
break;
default:
break;
}
p->setFinalLocation(DocumentRange(document(), KTextEditor::Range::invalid()));
qCWarning(LANGUAGE) << "Could not open file" << document().str() << "(path" << localFile << ")";
return p;
}
d->contents.contents = file.readAll(); ///@todo Convert from local encoding to utf-8 if they don't match
// This is consistent with KTextEditor::Document::text() as used for already-open files.
normalizeLineEndings(d->contents.contents);
d->contents.modification = KDevelop::ModificationRevision(lastModified);
file.close();
}
return KDevelop::ProblemPointer();
}
const KDevelop::ParseJob::Contents& ParseJob::contents() const
{
Q_D(const ParseJob);
Q_ASSERT(d->hasReadContents);
return d->contents;
}
struct MovingRangeTranslator
: public DUChainVisitor
{
MovingRangeTranslator(qint64 _source, qint64 _target, MovingInterface* _moving) : source(_source)
, target(_target)
, moving(_moving)
{
}
void visit(DUContext* context) override
{
translateRange(context);
///@todo Also map import-positions
// Translate uses
uint usesCount = context->usesCount();
for (uint u = 0; u < usesCount; ++u) {
RangeInRevision r = context->uses()[u].m_range;
translateRange(r);
context->changeUseRange(u, r);
}
}
void visit(Declaration* declaration) override
{
translateRange(declaration);
}
void translateRange(DUChainBase* object)
{
RangeInRevision r = object->range();
translateRange(r);
object->setRange(r);
}
void translateRange(RangeInRevision& r)
{
// PHP and python use top contexts that start at (0, 0) end at INT_MAX, so make sure that doesn't overflow
// or translate the start of the top context away from (0, 0)
if (r.start.line != 0 || r.start.column != 0) {
moving->transformCursor(r.start.line, r.start.column, MovingCursor::MoveOnInsert, source, target);
}
if (r.end.line != std::numeric_limits<int>::max() || r.end.column != std::numeric_limits<int>::max()) {
moving->transformCursor(r.end.line, r.end.column, MovingCursor::StayOnInsert, source, target);
}
}
KTextEditor::Range range;
qint64 source;
qint64 target;
MovingInterface* moving;
};
void ParseJob::translateDUChainToRevision(TopDUContext* context)
{
Q_D(ParseJob);
qint64 targetRevision = d->contents.modification.revision;
if (targetRevision == -1) {
qCDebug(LANGUAGE) << "invalid target revision" << targetRevision;
return;
}
qint64 sourceRevision;
{
DUChainReadLocker duChainLock;
Q_ASSERT(context->parsingEnvironmentFile());
// Cannot map if there is no source revision
sourceRevision = context->parsingEnvironmentFile()->modificationRevision().revision;
if (sourceRevision == -1) {
qCDebug(LANGUAGE) << "invalid source revision" << sourceRevision;
return;
}
}
if (sourceRevision > targetRevision) {
qCDebug(LANGUAGE) << "for document" << document().str() <<
": source revision is higher than target revision:" << sourceRevision << " > " << targetRevision;
return;
}
ForegroundLock lock;
if (DocumentChangeTracker* t = d->tracker.data()) {
if (!d->previousRevision) {
qCDebug(LANGUAGE) << "not translating because there is no valid predecessor-revision";
return;
}
if (sourceRevision != d->previousRevision->revision() || !d->previousRevision->valid()) {
qCDebug(LANGUAGE) <<
"not translating because the document revision does not match the tracker start revision (maybe the document was cleared)";
return;
}
if (!t->holdingRevision(sourceRevision) || !t->holdingRevision(targetRevision)) {
qCDebug(LANGUAGE) << "lost one of the translation revisions, not doing the map";
return;
}
// Perform translation
MovingInterface* moving = t->documentMovingInterface();
DUChainWriteLocker wLock;
MovingRangeTranslator translator(sourceRevision, targetRevision, moving);
context->visit(translator);
const QList<ProblemPointer> problems = context->problems();
for (auto& problem : problems) {
RangeInRevision r = problem->range();
translator.translateRange(r);
problem->setRange(r);
}
// Update the modification revision in the meta-data
ModificationRevision modRev = context->parsingEnvironmentFile()->modificationRevision();
modRev.revision = targetRevision;
context->parsingEnvironmentFile()->setModificationRevision(modRev);
}
}
bool ParseJob::isUpdateRequired(const IndexedString& languageString)
{
if (abortRequested()) {
return false;
}
if (minimumFeatures() & TopDUContext::ForceUpdate) {
return true;
}
DUChainReadLocker lock;
if (abortRequested()) {
return false;
}
const auto files = DUChain::self()->allEnvironmentFiles(document());
for (const ParsingEnvironmentFilePointer& file : files) {
if (file->language() != languageString) {
continue;
}
if (!file->needsUpdate(environment()) && file->featuresSatisfied(minimumFeatures())) {
qCDebug(LANGUAGE) << "Already up to date" << document().str();
setDuChain(file->topContext());
lock.unlock();
highlightDUChain();
return false;
}
break;
}
return !abortRequested();
}
const ParsingEnvironment* ParseJob::environment() const
{
return nullptr;
}
void ParseJob::highlightDUChain()
{
Q_D(ParseJob);
ENSURE_CHAIN_NOT_LOCKED
if (!d->languageSupport->codeHighlighting() || !duChain() || abortRequested()) {
// language doesn't support highlighting
return;
}
if (!d->hasReadContents && !d->tracker) {
d->tracker = ICore::self()->languageController()->backgroundParser()->trackerForUrl(document());
}
if (d->tracker) {
d->languageSupport->codeHighlighting()->highlightDUChain(duChain());
}
}
ControlFlowGraph* ParseJob::controlFlowGraph()
{
return nullptr;
}
DataAccessRepository* ParseJob::dataAccessInformation()
{
return nullptr;
}
bool ParseJob::hasTracker() const
{
Q_D(const ParseJob);
return d->tracker;
}
}
|