Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmldomtop.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
6#include "qqmldomtop_p.h"
11
12#include <QtQml/private/qqmljslexer_p.h>
13#include <QtQml/private/qqmljsparser_p.h>
14#include <QtQml/private/qqmljsengine_p.h>
15#include <QtQml/private/qqmljsastvisitor_p.h>
16#include <QtQml/private/qqmljsast_p.h>
17
18#include <QtQmlCompiler/private/qqmljsutils_p.h>
19
20#include <QtCore/QBasicMutex>
21#include <QtCore/QCborArray>
22#include <QtCore/QDebug>
23#include <QtCore/QDir>
24#include <QtCore/QFile>
25#include <QtCore/QFileInfo>
26#include <QtCore/QRegularExpression>
27#include <QtCore/QScopeGuard>
28#if QT_FEATURE_thread
29# include <QtCore/QThread>
30#endif
31
32#include <memory>
33
35
36using namespace Qt::StringLiterals;
37
38namespace QQmlJS {
39namespace Dom {
40
41using std::shared_ptr;
42
43
44/*!
45 \internal
46 \brief QQml::Dom::DomTop::loadFile
47 \param filePath
48 the file path to load
49 \param logicalPath
50 the path from the
51 \param callback
52 a callback called with an canonical path, the old value, and the current value.
53 \param loadOptions are
54 if force is true the file is always read
55 */
56
58{
59 return canonicalPath();
60}
61
63{
64 return DomItem();
65}
66
67bool DomTop::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
68{
69 Q_UNUSED(self);
70 Q_UNUSED(visitor);
71 return true;
72}
73
74/*!
75\class QQmlJS::Dom::DomUniverse
76
77\brief Represents a set of parsed/loaded modules libraries and a plugins
78
79This can be used to share parsing and updates between several Dom models, and kickstart a model
80without reparsing everything.
81
82The universe is peculiar, because stepping into it from an environment looses the connection with
83the environment.
84
85This implementation is a placeholder, a later patch will introduce it.
86 */
87
88ErrorGroups DomUniverse::myErrors()
89{
90 static ErrorGroups groups = {{ DomItem::domErrorGroup, NewErrorGroup("Universe") }};
91 return groups;
92}
93
94DomUniverse::DomUniverse(const QString &universeName) : m_name(universeName) { }
95
96std::shared_ptr<DomUniverse> DomUniverse::guaranteeUniverse(
97 const std::shared_ptr<DomUniverse> &univ)
98{
99 const auto next = [] {
100 Q_CONSTINIT static std::atomic<int> counter(0);
101 return counter.fetch_add(1, std::memory_order_relaxed) + 1;
102 };
103 if (univ)
104 return univ;
105
106 return std::make_shared<DomUniverse>(
107 QLatin1String("universe") + QString::number(next()));
108}
109
110DomItem DomUniverse::create(const QString &universeName)
111{
112 auto res = std::make_shared<DomUniverse>(universeName);
113 return DomItem(res);
114}
115
116Path DomUniverse::canonicalPath() const
117{
119}
120
121bool DomUniverse::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
122{
123 bool cont = true;
124 cont = cont && DomTop::iterateDirectSubpaths(self, visitor);
125 cont = cont && self.invokeVisitorOnValue(visitor, Fields::name, name());
126 cont = cont && visitor(Fields::qmlFileWithPath, [this, &self]() {
127 return self.subMapItem(Map(
128 Path::fromField(Fields::qmlFileWithPath),
129 [this](const DomItem &map, const QString &key) {
130 return map.copy(qmlFileWithPath(key));
131 },
132 [this](const DomItem &) { return qmlFilePaths(); },
133 QLatin1String("QmlFile")));
134 });
135 cont = cont && visitor(Fields::jsFileWithPath, [this, &self]() {
136 return self.subMapItem(Map(
137 Path::fromField(Fields::jsFileWithPath),
138 [this](const DomItem &map, const QString &key) {
139 return map.copy(jsFileWithPath(key));
140 },
141 [this](const DomItem &) { return jsFilePaths(); }, QLatin1String("JsFile")));
142 });
143 return cont;
145
146std::shared_ptr<OwningItem> DomUniverse::doCopy(const DomItem &) const
147{
148 QRegularExpression r(QRegularExpression::anchoredPattern(QLatin1String(R"(.*Copy([0-9]*)$)")));
149 auto m = r.match(m_name);
150 QString newName;
151 if (m.hasMatch())
152 newName = QStringLiteral(u"%1Copy%2").arg(m_name).arg(m.captured(1).toInt() + 1);
153 else
154 newName = m_name + QLatin1String("Copy");
155 auto res = std::make_shared<DomUniverse>(newName);
156 return res;
157}
158
159static DomType fileTypeForPath(const DomItem &self, const QString &canonicalFilePath)
160{
161 if (canonicalFilePath.endsWith(u".qml", Qt::CaseInsensitive)
162 || canonicalFilePath.endsWith(u".qmlannotation", Qt::CaseInsensitive)) {
163 return DomType::QmlFile;
164 } else if (canonicalFilePath.endsWith(u".js", Qt::CaseInsensitive)
165 || canonicalFilePath.endsWith(u".mjs", Qt::CaseInsensitive)) {
166 return DomType::JsFile;
167 }
168 else {
169 self.addError(DomUniverse::myErrors()
170 .error(QCoreApplication::translate("Dom::fileTypeForPath",
171 "Could not detect type of file %1")
172 .arg(canonicalFilePath))
173 .handle());
174 }
175 return DomType::Empty;
176}
177
178DomUniverse::LoadResult DomUniverse::loadFile(const FileToLoad &file, DomType fileType,
179 DomCreationOption creationOption)
180{
181 DomItem univ(shared_from_this());
182 switch (fileType) {
183 case DomType::QmlFile:
184 case DomType::JsFile: {
185 const auto &preLoadResult = preload(univ, file, fileType);
186 if (std::holds_alternative<LoadResult>(preLoadResult)) {
187 // universe already has the most recent version of the file
188 return std::get<LoadResult>(preLoadResult);
189 } else {
190 // content of the file needs to be parsed and value inside Universe needs to be updated
191 return load(std::get<ContentWithDate>(preLoadResult), file, fileType, creationOption);
192 }
193 }
194 default:
196 .error(tr("Ignoring request to load file %1 of unexpected type %2, "
197 "calling callback immediately")
198 .arg(file.canonicalPath(), domTypeToString(fileType)))
199 .handle());
200 Q_ASSERT(false && "loading non supported file type");
201 return {};
202 }
203}
204
205DomUniverse::LoadResult DomUniverse::load(const ContentWithDate &codeWithDate,
206 const FileToLoad &file, DomType fType,
207 DomCreationOption creationOption)
208{
209 QString canonicalPath = file.canonicalPath();
210
211 DomItem oldValue; // old ExternalItemPair (might be empty, or equal to newValue)
212 DomItem newValue; // current ExternalItemPair
213 DomItem univ = DomItem(shared_from_this());
214
215 if (fType == DomType::QmlFile) {
216 auto qmlFile = parseQmlFile(codeWithDate.content, file, codeWithDate.date, creationOption);
217 return insertOrUpdateExternalItem(std::move(qmlFile));
218 } else if (fType == DomType::JsFile) {
219 auto jsFile = parseJsFile(codeWithDate.content, file, codeWithDate.date);
220 return insertOrUpdateExternalItem(std::move(jsFile));
221 } else {
222 Q_ASSERT(false);
223 }
224 return { std::move(oldValue), std::move(newValue) };
225}
226
227/*!
228 \internal
229 This function is somewhat coupled and does the following:
230 1. If a content of the file is provided it checks whether the item with the same content
231 already exists inside the Universe. If so, returns it as a result of the load
232 2. If a content is not provided, it first tries to check whether Universe has the most
233 recent item. If yes, it returns it as a result of the load. Otherwise does step 1.
234 */
235DomUniverse::PreloadResult DomUniverse::preload(const DomItem &univ, const FileToLoad &file,
236 DomType fType) const
237{
238 QString canonicalPath = file.canonicalPath();
239 ContentWithDate codeWithDate;
240
241 if (file.content().has_value()) {
242 codeWithDate = { file.content()->data, file.content()->date };
243 } else {
244 // When content is empty, Universe attempts to read it from the File.
245 // However if it already has the most recent version of that File it just returns it
246 const auto &curValueItem = getItemIfMostRecent(univ, fType, canonicalPath);
247 if (curValueItem.has_value()) {
248 return LoadResult{ curValueItem.value(), curValueItem.value() };
249 }
250 // otherwise tries to read the content from the path
251 auto readResult = readFileContent(canonicalPath);
252 if (std::holds_alternative<ErrorMessage>(readResult)) {
253 DomItem newValue;
254 newValue.addError(std::move(std::get<ErrorMessage>(readResult)));
255 return LoadResult{ DomItem(), std::move(newValue) }; // read failed, nothing to parse
256 } else {
257 codeWithDate = std::get<ContentWithDate>(readResult);
258 }
259 }
260
261 // Once the code is provided Universe verifies if it already has an up-to-date code
262 const auto &curValueItem = getItemIfHasSameCode(univ, fType, canonicalPath, codeWithDate);
263 if (curValueItem.has_value()) {
264 return LoadResult{ curValueItem.value(), curValueItem.value() };
265 }
266 // otherwise code needs to be parsed
267 return codeWithDate;
268}
269
270void DomUniverse::removePath(const QString &path)
271{
272 QMutexLocker l(mutex());
273 const auto toDelete = [path](const auto &it) {
274 QString p = it.key();
275 return p.startsWith(path) && (p.size() == path.size() || p.at(path.size()) == u'/');
276 };
277 m_qmlFileWithPath.removeIf(toDelete);
278 m_jsFileWithPath.removeIf(toDelete);
279}
280
281DomUniverse::ReadResult DomUniverse::readFileContent(const QString &canonicalPath) const
282{
283 if (canonicalPath.isEmpty()) {
284 return myErrors().error(tr("Non existing path %1").arg(canonicalPath));
285 }
286 QFile file(canonicalPath);
287 QFileInfo fileInfo(canonicalPath);
288 if (fileInfo.isDir()) {
289 return ContentWithDate{ QDir(canonicalPath)
290 .entryList(QDir::NoDotAndDotDot | QDir::Files, QDir::Name)
291 .join(QLatin1Char('\n')),
292 QDateTime::currentDateTimeUtc() };
293 }
294 if (!file.open(QIODevice::ReadOnly)) {
295 return myErrors().error(
296 tr("Error opening path %1: %2 %3")
297 .arg(canonicalPath, QString::number(file.error()), file.errorString()));
298 }
299 auto content = QString::fromUtf8(file.readAll());
300 file.close();
301 return ContentWithDate{ std::move(content), QDateTime::currentDateTimeUtc() };
302}
303
304std::shared_ptr<QmlFile> DomUniverse::parseQmlFile(const QString &code, const FileToLoad &file,
305 const QDateTime &contentDate,
306 DomCreationOption creationOption)
307{
308 auto qmlFile =
309 std::make_shared<QmlFile>(file.canonicalPath(), code, contentDate, 0,
310 creationOption == Extended ? QmlFile::EnableParserRecovery
311 : QmlFile::DisableParserRecovery);
312 std::shared_ptr<DomEnvironment> envPtr;
313 if (auto ptr = file.environment())
314 envPtr = std::move(ptr);
315 else
316 envPtr = std::make_shared<DomEnvironment>(QStringList(),
317 DomEnvironment::Option::NoDependencies,
318 creationOption, shared_from_this());
319 envPtr->addQmlFile(qmlFile);
320 DomItem env(envPtr);
321 if (qmlFile->isValid()) {
322 // do not call populateQmlFile twice on lazy qml files if the importer already does it!
323 if (creationOption != DomCreationOption::Extended)
324 envPtr->populateFromQmlFile(MutableDomItem(env.copy(qmlFile)));
325 } else {
326 QString errs;
327 DomItem qmlFileObj = env.copy(qmlFile);
328 qmlFile->iterateErrors(qmlFileObj, [&errs](const DomItem &, const ErrorMessage &m) {
329 errs += m.toString();
330 errs += u"\n";
331 return true;
332 });
333 qCWarning(domLog).noquote().nospace()
334 << "Parsed invalid file " << file.canonicalPath() << errs;
335 }
336 return qmlFile;
337}
338
339std::shared_ptr<JsFile> DomUniverse::parseJsFile(const QString &code, const FileToLoad &file,
340 const QDateTime &contentDate)
341{
342 // WATCH OUT!
343 // DOM construction for plain JS files is not yet supported
344 // Only parsing of the file
345 // and adding ExternalItem to the Environment will happen here
346 auto jsFile = std::make_shared<JsFile>(file.canonicalPath(), code, contentDate);
347 std::shared_ptr<DomEnvironment> envPtr;
348 if (auto ptr = file.environment())
349 envPtr = std::move(ptr);
350 else
351 envPtr = std::make_shared<DomEnvironment>(QStringList(),
352 DomEnvironment::Option::NoDependencies,
353 DomCreationOption::Default, shared_from_this());
354 envPtr->addJsFile(jsFile);
355 DomItem env(envPtr);
356 if (!jsFile->isValid()) {
357 QString errs;
358 DomItem qmlFileObj = env.copy(jsFile);
359 jsFile->iterateErrors(qmlFileObj, [&errs](const DomItem &, const ErrorMessage &m) {
360 errs += m.toString();
361 errs += u"\n";
362 return true;
363 });
364 qCWarning(domLog).noquote().nospace()
365 << "Parsed invalid file " << file.canonicalPath() << errs;
366 }
367 return jsFile;
368}
369
370/*!
371 \internal
372 Queries the corresponding path map attempting to get the value
373 *WARNING* Usage of this function should be protected by the read lock
374 */
375std::shared_ptr<ExternalItemPairBase> DomUniverse::getPathValueOrNull(DomType fType,
376 const QString &path) const
377{
378 switch (fType) {
379 case DomType::QmlFile:
380 return m_qmlFileWithPath.value(path);
381 case DomType::JsFile:
382 return m_jsFileWithPath.value(path);
383 default:
384 Q_ASSERT(false);
385 }
386 return nullptr;
387}
388
389std::optional<DomItem> DomUniverse::getItemIfMostRecent(const DomItem &univ, DomType fType,
390 const QString &canonicalPath) const
391{
392 QFileInfo fInfo(canonicalPath);
393 bool valueItemIsMostRecent = false;
394 std::shared_ptr<ExternalItemPairBase> value = nullptr;
395 {
396 // Mutex is to sync access to the Value and Value->CurrentItem, which can be modified
397 // through updateEnty method and currentItem->refreshedDataAt
398 QMutexLocker l(mutex());
399 value = getPathValueOrNull(fType, canonicalPath);
400 valueItemIsMostRecent = valueHasMostRecentItem(value.get(), fInfo.lastModified());
401 }
402 if (valueItemIsMostRecent) {
403 return univ.copy(value);
404 }
405 return std::nullopt;
406}
407
408std::optional<DomItem> DomUniverse::getItemIfHasSameCode(const DomItem &univ, DomType fType,
409 const QString &canonicalPath,
410 const ContentWithDate &codeWithDate) const
411{
412 std::shared_ptr<ExternalItemPairBase> value = nullptr;
413 bool valueItemHasSameCode = false;
414 {
415 // Mutex is to sync access to the Value and Value->CurrentItem, which can be modified
416 // through updateEnty method and currentItem->refreshedDataAt
417 QMutexLocker l(mutex());
418 value = getPathValueOrNull(fType, canonicalPath);
419 if (valueHasSameContent(value.get(), codeWithDate.content)) {
420 valueItemHasSameCode = true;
421 if (value->currentItem()->lastDataUpdateAt() < codeWithDate.date)
422 value->currentItem()->refreshedDataAt(codeWithDate.date);
423 }
424 }
425 if (valueItemHasSameCode) {
426 return univ.copy(value);
427 }
428 return std::nullopt;
429}
430
431/*!
432 \internal
433 Checks if value has current Item and if it was not modified since last seen
434 *WARNING* Usage of this function should be protected by the read lock
435 */
436bool DomUniverse::valueHasMostRecentItem(const ExternalItemPairBase *value,
437 const QDateTime &lastModified)
438{
439 if (!value || !value->currentItem()) {
440 return false;
441 }
442 return lastModified < value->currentItem()->lastDataUpdateAt();
443}
444
445/*!
446 \internal
447 Checks if value has current Item and if it has same content
448 *WARNING* Usage of this function should be protected by the read lock
449 */
450bool DomUniverse::valueHasSameContent(const ExternalItemPairBase *value, const QString &content)
451{
452 if (!value || !value->currentItem()) {
453 return false;
454 }
455 QString curContent = value->currentItem()->code();
456 return !curContent.isNull() && curContent == content;
457}
458
459std::shared_ptr<OwningItem> LoadInfo::doCopy(const DomItem &self) const
460{
461 auto res = std::make_shared<LoadInfo>(*this);
462 if (res->status() != Status::Done) {
463 res->addErrorLocal(DomEnvironment::myErrors().warning(
464 u"This is a copy of a LoadInfo still in progress, artificially ending it, if you "
465 u"use this you will *not* resume loading"_sv));
466 DomEnvironment::myErrors()
467 .warning([&self](const Sink &sink) {
468 sink(u"Copying an in progress LoadInfo, which is most likely an error (");
469 self.dump(sink);
470 sink(u")");
471 })
472 .handle();
473 QMutexLocker l(res->mutex());
474 res->m_status = Status::Done;
475 res->m_toDo.clear();
476 res->m_inProgress.clear();
477 res->m_endCallbacks.clear();
478 }
479 return res;
480}
481
482Path LoadInfo::canonicalPath(const DomItem &) const
483{
485}
486
487bool LoadInfo::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
488{
489 bool cont = OwningItem::iterateDirectSubpaths(self, visitor);
490 cont = cont && self.invokeVisitorOnValue(visitor, Fields::status, int(status()));
491 cont = cont && self.invokeVisitorOnValue(visitor, Fields::nLoaded, nLoaded());
492 cont = cont && self.invokeVisitorOnValue(visitor, Fields::elementCanonicalPath,
493 elementCanonicalPath().toString());
494 cont = cont && self.invokeVisitorOnValue(visitor, Fields::nNotdone, nNotDone());
495 cont = cont && self.invokeVisitorOnValue(visitor, Fields::nCallbacks, nCallbacks());
496 return cont;
497}
498
499void LoadInfo::addEndCallback(const DomItem &self,
500 std::function<void(Path, const DomItem &, const DomItem &)> callback)
501{
502 if (!callback)
503 return;
504 {
505 QMutexLocker l(mutex());
506 switch (m_status) {
507 case Status::NotStarted:
508 case Status::Starting:
509 case Status::InProgress:
510 case Status::CallingCallbacks:
511 m_endCallbacks.append(callback);
512 return;
513 case Status::Done:
514 break;
515 }
516 }
518 DomItem el = self.path(p);
519 callback(p, el, el);
520}
521
522void LoadInfo::advanceLoad(const DomItem &self)
523{
524 Status myStatus;
525 Dependency dep;
526 bool depValid = false;
527 {
528 QMutexLocker l(mutex());
529 myStatus = m_status;
530 switch (myStatus) {
532 m_status = Status::Starting;
533 break;
534 case Status::Starting:
536 if (!m_toDo.isEmpty()) {
537 dep = m_toDo.dequeue();
538 m_inProgress.append(dep);
539 depValid = true;
540 }
541 break;
543 case Status::Done:
544 break;
545 }
546 }
547 switch (myStatus) {
548 case Status::NotStarted:
549 refreshedDataAt(QDateTime::currentDateTimeUtc());
550 doAddDependencies(self);
551 refreshedDataAt(QDateTime::currentDateTimeUtc());
552 {
553 QMutexLocker l(mutex());
554 Q_ASSERT(m_status == Status::Starting);
555 if (m_toDo.isEmpty() && m_inProgress.isEmpty())
556 myStatus = m_status = Status::CallingCallbacks;
557 else
558 myStatus = m_status = Status::InProgress;
559 }
560 if (myStatus == Status::CallingCallbacks)
561 execEnd(self);
562 break;
563 case Status::Starting:
565 if (depValid) {
566 refreshedDataAt(QDateTime::currentDateTimeUtc());
567 auto envPtr = self.environment().ownerAs<DomEnvironment>();
568 Q_ASSERT(envPtr && "missing environment");
569 if (!dep.uri.isEmpty()) {
570 Q_ASSERT(dep.filePath.isEmpty() && "dependency with both uri and file");
571 } else if (!dep.filePath.isEmpty()) {
572 envPtr->loadFile(
573 FileToLoad::fromFileSystem(envPtr, dep.filePath),
574 [this, copiedSelf = self, dep](Path, const DomItem &, const DomItem &) {
575 // Need to explicitly copy self here since we might store this and
576 // call it later.
577 finishedLoadingDep(copiedSelf, dep);
578 },
579 dep.fileType, self.errorHandler());
580 } else {
581 Q_ASSERT(false && "dependency without uri and filePath");
582 }
583 } else {
585 tr("advanceLoad called but found no work, which should never happen")));
586 }
587 break;
589 case Status::Done:
590 addErrorLocal(DomEnvironment::myErrors().error(tr(
591 "advanceLoad called after work should have been done, which should never happen")));
592 break;
593 }
594}
595
596void LoadInfo::finishedLoadingDep(const DomItem &self, const Dependency &d)
597{
598 bool didRemove = false;
599 bool unexpectedState = false;
600 bool doEnd = false;
601 {
602 QMutexLocker l(mutex());
603 didRemove = m_inProgress.removeOne(d);
604 switch (m_status) {
607 case Status::Done:
608 unexpectedState = true;
609 break;
610 case Status::Starting:
611 break;
613 if (m_toDo.isEmpty() && m_inProgress.isEmpty()) {
614 m_status = Status::CallingCallbacks;
615 doEnd = true;
616 }
617 break;
618 }
619 }
620 if (!didRemove) {
621 addErrorLocal(DomEnvironment::myErrors().error([&self](const Sink &sink) {
622 sink(u"LoadInfo::finishedLoadingDep did not find its dependency in those inProgress "
623 u"()");
624 self.dump(sink);
625 sink(u")");
626 }));
627 Q_ASSERT(false
628 && "LoadInfo::finishedLoadingDep did not find its dependency in those inProgress");
629 }
630 if (unexpectedState) {
631 addErrorLocal(DomEnvironment::myErrors().error([&self](const Sink &sink) {
632 sink(u"LoadInfo::finishedLoadingDep found an unexpected state (");
633 self.dump(sink);
634 sink(u")");
635 }));
636 Q_ASSERT(false && "LoadInfo::finishedLoadingDep did find an unexpected state");
637 }
638 if (doEnd)
639 execEnd(self);
640}
641
642void LoadInfo::execEnd(const DomItem &self)
643{
644 QList<std::function<void(Path, const DomItem &, const DomItem &)>> endCallbacks;
645 bool unexpectedState = false;
646 {
647 QMutexLocker l(mutex());
648 unexpectedState = m_status != Status::CallingCallbacks;
649 endCallbacks = m_endCallbacks;
650 m_endCallbacks.clear();
651 }
652 Q_ASSERT(!unexpectedState && "LoadInfo::execEnd found an unexpected state");
654 DomItem el = self.path(p);
655 {
656 auto cleanup = qScopeGuard([this, p, &el] {
657 QList<std::function<void(Path, const DomItem &, const DomItem &)>> otherCallbacks;
658 bool unexpectedState2 = false;
659 {
660 QMutexLocker l(mutex());
661 unexpectedState2 = m_status != Status::CallingCallbacks;
662 m_status = Status::Done;
663 otherCallbacks = m_endCallbacks;
664 m_endCallbacks.clear();
665 }
666 Q_ASSERT(!unexpectedState2 && "LoadInfo::execEnd found an unexpected state");
667 for (auto const &cb : otherCallbacks) {
668 if (cb)
669 cb(p, el, el);
670 }
671 });
672 for (auto const &cb : endCallbacks) {
673 if (cb)
674 cb(p, el, el);
675 }
676 }
677}
678
679void LoadInfo::doAddDependencies(const DomItem &self)
680{
682 DomEnvironment::myErrors()
683 .error(tr("Uninitialized LoadInfo %1").arg(self.canonicalPath().toString()))
684 .handle(nullptr);
685 Q_ASSERT(false);
686 return;
687 }
688 // sychronous add of all dependencies
691 DomItem currentFile = el.field(Fields::currentItem);
692 QString currentFilePath = currentFile.canonicalFilePath();
693 // do not mess with QmlFile's lazy-loading
694 if (currentFile.internalKind() != DomType::QmlFile) {
695 DomItem currentQmlFiles = currentFile.field(Fields::qmlFiles);
696 currentQmlFiles.visitKeys([this, &self](const QString &, const DomItem &els) {
697 return els.visitIndexes([this, &self](const DomItem &el) {
698 if (const Reference *ref = el.as<Reference>()) {
699 Path canonicalPath = ref->referredObjectPath[2];
700 if (canonicalPath && !canonicalPath.headName().isEmpty())
701 addDependency(self,
702 Dependency{ QString(), Version(),
703 canonicalPath.headName(), DomType::QmlFile });
704 }
705 return true;
706 });
707 });
708 }
709 } else if (!el) {
710 self.addError(DomEnvironment::myErrors().error(
711 tr("Ignoring dependencies for empty (invalid) type %1")
712 .arg(domTypeToString(el.internalKind()))));
713 } else {
714 self.addError(
715 DomEnvironment::myErrors().error(tr("dependencies of %1 (%2) not yet implemented")
716 .arg(domTypeToString(el.internalKind()),
717 elementCanonicalPath().toString())));
718 }
719}
720
721void LoadInfo::addDependency(const DomItem &self, const Dependency &dep)
722{
723 bool unexpectedState = false;
724 {
725 QMutexLocker l(mutex());
726 unexpectedState = m_status != Status::Starting;
727 m_toDo.enqueue(dep);
728 }
729 Q_ASSERT(!unexpectedState && "LoadInfo::addDependency found an unexpected state");
730 DomItem env = self.environment();
731 env.ownerAs<DomEnvironment>()->addWorkForLoadInfo(elementCanonicalPath());
732}
733
734/*!
735\class QQmlJS::Dom::DomEnvironment
736
737\brief Represents a consistent set of types organized in modules, it is the top level of the DOM
738
739The DomEnvironment keeps a pointer m_lastValidBase to the last used valid DomEnvironment in the
740commitToBase() method. This allows the qqmldomastcreator to commit lazily loaded dependencies to the
741valid environment used by qmlls.
742 */
743
744ErrorGroups DomEnvironment::myErrors()
745{
746 static ErrorGroups res = {{NewErrorGroup("Dom")}};
747 return res;
748}
749
750DomType DomEnvironment::kind() const
751{
752 return kindValue;
753}
754
755Path DomEnvironment::canonicalPath() const
756{
758}
759
760bool DomEnvironment::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
761{
762 bool cont = true;
763 cont = cont && DomTop::iterateDirectSubpaths(self, visitor);
764 DomItem univ = universe();
765 cont = cont && visitor(Fields::universe, [this]() { return universe(); });
766 cont = cont && self.invokeVisitorOnValue(visitor, Fields::options, int(options()));
767 cont = cont && visitor(Fields::base, [this]() { return base(); });
768 cont = cont && self.invokeVisitorOnLazyField(visitor, Fields::loadPaths, [this]() {
769 return loadPaths();
770 });
771 cont = cont && visitor(Fields::qmlFileWithPath, [this, &self]() {
772 return self.subMapItem(Map(
773 Path::fromField(Fields::qmlFileWithPath),
774 [&self, this](const DomItem &map, const QString &key) {
775 return map.copy(qmlFileWithPath(self, key));
776 },
777 [&self, this](const DomItem &) { return qmlFilePaths(self); },
778 QLatin1String("QmlFile")));
779 });
780 cont = cont && visitor(Fields::jsFileWithPath, [this, &self]() {
781 return self.subMapItem(Map(
782 Path::fromField(Fields::jsFileWithPath),
783 [this](const DomItem &map, const QString &key) {
784 DomItem mapOw(map.owner());
785 return map.copy(jsFileWithPath(mapOw, key));
786 },
787 [this](const DomItem &map) {
788 DomItem mapOw = map.owner();
789 return jsFilePaths(mapOw);
790 },
791 QLatin1String("JsFile")));
792 });
793 bool loadedLoadInfo = false;
794 QQueue<Path> loadsWithWork;
795 QQueue<Path> inProgress;
796 int nAllLoadedCallbacks;
797 auto ensureInfo = [&]() {
798 if (!loadedLoadInfo) {
799 QMutexLocker l(mutex());
800 loadedLoadInfo = true;
801 loadsWithWork = m_loadsWithWork;
802 inProgress = m_inProgress;
803 nAllLoadedCallbacks = m_allLoadedCallback.size();
804 }
805 };
806 cont = cont && visitor(
807 Fields::loadsWithWork, [&ensureInfo, &self, &loadsWithWork]() {
808 ensureInfo();
809 return self.subListItem(List(
810 Path::fromField(Fields::loadsWithWork),
811 [loadsWithWork](const DomItem &list, index_type i) {
812 if (i >= 0 && i < loadsWithWork.size())
813 return list.subDataItem(PathEls::Index(i),
814 loadsWithWork.at(i).toString());
815 else
816 return DomItem();
817 },
818 [loadsWithWork](const DomItem &) {
819 return index_type(loadsWithWork.size());
820 },
821 nullptr, QLatin1String("Path")));
822 });
823 cont = cont && visitor(Fields::inProgress, [&self, &ensureInfo, &inProgress]() {
824 ensureInfo();
825 return self.subListItem(List(
826 Path::fromField(Fields::inProgress),
827 [inProgress](const DomItem &list, index_type i) {
828 if (i >= 0 && i < inProgress.size())
829 return list.subDataItem(PathEls::Index(i),
830 inProgress.at(i).toString());
831 else
832 return DomItem();
833 },
834 [inProgress](const DomItem &) { return index_type(inProgress.size()); },
835 nullptr, QLatin1String("Path")));
836 });
837 cont = cont && visitor(Fields::loadInfo, [&self, this]() {
838 // keyed by Path::toString() to avoid reparsing the path in Map::key()
839 QMap<QString, std::shared_ptr<LoadInfo>> infos;
840 for (const Path &p : loadInfoPaths())
841 infos.insert(p.toString(), loadInfo(p));
842 return self.subMapItem(Map(
843 Path::fromField(Fields::loadInfo),
844 [infos](const DomItem &map, const QString &name) {
845 auto it = infos.find(name);
846 if (it == infos.end())
847 return DomItem();
848 return map.copy(*it);
849 },
850 [infos](const DomItem &) {
851 return QSet<QString>(infos.keyBegin(), infos.keyEnd());
852 },
853 QLatin1String("LoadInfo")));
854 });
855 cont = cont && self.invokeVisitorOnField(visitor, Fields::imports, m_implicitImports);
856 cont = cont && self.invokeVisitorOnLazyField(visitor, Fields::nAllLoadedCallbacks,
857 [&nAllLoadedCallbacks, &ensureInfo]() {
858 ensureInfo();
859 return nAllLoadedCallbacks;
860 });
861 return cont;
862}
863
864DomItem DomEnvironment::field(const DomItem &self, FieldName name) const
865{
866 return DomTop::field(self, name);
867}
868
869std::shared_ptr<DomEnvironment> DomEnvironment::makeCopy(const DomItem &self) const
870{
871 return std::static_pointer_cast<DomEnvironment>(doCopy(self));
872}
873
874std::shared_ptr<OwningItem> DomEnvironment::doCopy(const DomItem &) const
875{
876 shared_ptr<DomEnvironment> res;
877 if (m_base)
878 res = std::make_shared<DomEnvironment>(m_base, m_loadPaths, m_options, m_domCreationOption);
879 else
880 res = std::make_shared<DomEnvironment>(m_loadPaths, m_options, m_domCreationOption,
881 m_universe);
882 return res;
883}
884
885bool DomEnvironment::hasFile(const QString &filePath) const
886{
887 return m_qmlFileWithPath.contains(filePath);
888}
889void DomEnvironment::loadFile(const FileToLoad &file, const Callback &callback,
890 std::optional<DomType> fileType, const ErrorHandler &h)
891{
892 if (options() & DomEnvironment::Option::NoDependencies)
893 loadFile(file, callback, DomTop::Callback(), fileType, h);
894 else {
895 // When the file is required to be loaded with dependencies, those dependencies
896 // will be added to the "pending" queue through envCallbackForFile
897 // then those should not be forgotten to be loaded.
898 loadFile(file, DomTop::Callback(), callback, fileType, h);
899 }
900}
901
902/*!
903 \internal
904 Depending on the options, the function will be called either with loadCallback OR endCallback
905
906 Before loading the file, envCallbackForFile will be created and passed as an argument to
907 universe().loadFile(...).
908 This is a callback which will be called after the load of the file is finished. More
909 specifically when File is required to be loaded without Dependencies only loadCallback is being
910 used. Otherwise, the callback is passed as endCallback. What endCallback means is that this
911 callback will be called only at the very end, once all necessary dependencies are being loaded.
912 Management and handing of this is happening through the m_loadsWithWork.
913*/
914// TODO(QTBUG-119550) refactor this
915void DomEnvironment::loadFile(const FileToLoad &_file, const Callback &loadCallback,
916 const Callback &endCallback, std::optional<DomType> fileType,
917 const ErrorHandler &h)
918{
919 DomItem self(shared_from_this());
920 const DomType fType =
921 (bool(fileType) ? (*fileType) : fileTypeForPath(self, _file.logicalPath()));
922
923 FileToLoad file {_file};
924
926 // use source folders when loading qml files and build folders otherwise
927 if (fType == DomType::QmlFile) {
928 file.setCanonicalPath(QQmlJSUtils::qmlSourcePathFromBuildPath(
929 semanticAnalysis().m_mapper.get(), file.canonicalPath()));
930 file.setLogicalPath(file.logicalPath());
931 }
932 }
933
934 if (file.canonicalPath().isEmpty()) {
935 if (!file.content() || file.content()->data.isNull()) {
936 // file's content inavailable and no path to retrieve it
938 .error(tr("Non existing path to load: '%1'").arg(file.logicalPath()))
939 .handle(h);
940 if (loadCallback)
941 loadCallback(Path(), DomItem::empty, DomItem::empty);
942 if (endCallback)
943 addAllLoadedCallback(self, [endCallback](Path, const DomItem &, const DomItem &) {
944 endCallback(Path(), DomItem::empty, DomItem::empty);
945 });
946 return;
947 } else {
948 // fallback: path invalid but file's content is already available.
949 file.canonicalPath() = file.logicalPath();
950 }
951 }
952
953 shared_ptr<ExternalItemInfoBase> oldValue, newValue;
954 switch (fType) {
955 case DomType::QmlFile: {
956 const auto &fetchResult = fetchFileFromEnvs<QmlFile>(file);
957 oldValue = fetchResult.first;
958 newValue = fetchResult.second;
959 if (!newValue) {
960 const auto &loadRes = universe()->loadFile(file, fType, m_domCreationOption);
961 addExternalItemInfo<QmlFile>(loadRes.currentItem, loadCallback, endCallback);
962 return;
963 }
964 } break;
965 case DomType::JsFile: {
966 const auto &loadRes = universe()->loadFile(file, fType, m_domCreationOption);
967 addExternalItemInfo<JsFile>(loadRes.currentItem, loadCallback, endCallback);
968 return;
969 } break;
970 default: {
971 myErrors().error(tr("Unexpected file to load: '%1'").arg(file.canonicalPath())).handle(h);
972 if (loadCallback)
974 if (endCallback)
976 return;
977 } break;
978 }
979 Path p = self.copy(newValue).canonicalPath();
980 std::shared_ptr<LoadInfo> lInfo = loadInfo(p);
981 if (lInfo) {
982 if (loadCallback) {
983 DomItem oldValueObj = self.copy(oldValue);
984 DomItem newValueObj = self.copy(newValue);
985 loadCallback(p, oldValueObj, newValueObj);
986 }
987 } else {
988 self.addError(myErrors().error(tr("missing load info in ")));
989 if (loadCallback)
991 }
992 if (endCallback)
993 addAllLoadedCallback(self, [p = std::move(p), endCallback](
994 const Path &, const DomItem &, const DomItem &env) {
995 DomItem el = env.path(p);
996 endCallback(p, el, el);
997 });
998}
999
1000void DomEnvironment::removePath(const QString &path)
1001{
1002 QMutexLocker l(mutex());
1003 auto toDelete = [path](auto it) {
1004 QString p = it.key();
1005 return p.startsWith(path) && (p.size() == path.size() || p.at(path.size()) == u'/');
1006 };
1007 m_qmlFileWithPath.removeIf(toDelete);
1008 m_jsFileWithPath.removeIf(toDelete);
1009}
1010
1011shared_ptr<DomUniverse> DomEnvironment::universe() const {
1012 if (m_universe)
1013 return m_universe;
1014 else if (m_base)
1015 return m_base->universe();
1016 else
1017 return {};
1018}
1019
1020template<typename T>
1021QSet<QString> DomEnvironment::getStrings(function_ref<QSet<QString>()> getBase,
1022 const QMap<QString, T> &selfMap, EnvLookup options) const
1023{
1024 QSet<QString> res;
1025 if (options != EnvLookup::NoBase && m_base) {
1026 if (m_base)
1027 res = getBase();
1028 }
1029 if (options != EnvLookup::BaseOnly) {
1030 QMap<QString, T> map;
1031 {
1032 QMutexLocker l(mutex());
1033 map = selfMap;
1034 }
1035 auto it = map.keyBegin();
1036 auto end = map.keyEnd();
1037 while (it != end) {
1038 res += *it;
1039 ++it;
1040 }
1041 }
1042 return res;
1043}
1044
1045std::shared_ptr<ExternalItemInfo<QmlFile>>
1046DomEnvironment::qmlFileWithPath(const DomItem &, const QString &path, EnvLookup options) const
1047{
1048 return lookup<QmlFile>(path, options);
1049}
1050
1051QSet<QString> DomEnvironment::qmlFilePaths(const DomItem &, EnvLookup lookup) const
1052{
1053 return getStrings<std::shared_ptr<ExternalItemInfo<QmlFile>>>(
1054 [this] {
1055 DomItem baseObj(m_base);
1056 return m_base->qmlFilePaths(baseObj, EnvLookup::Normal);
1057 },
1058 m_qmlFileWithPath, lookup);
1059}
1060
1061std::shared_ptr<ExternalItemInfo<JsFile>>
1062DomEnvironment::jsFileWithPath(const DomItem &, const QString &path, EnvLookup options) const
1063{
1064 return lookup<JsFile>(path, options);
1065}
1066
1067QSet<QString> DomEnvironment::jsFilePaths(const DomItem &, EnvLookup lookup) const
1068{
1069 return getStrings<std::shared_ptr<ExternalItemInfo<JsFile>>>(
1070 [this] {
1071 DomItem baseObj(m_base);
1072 return m_base->jsFilePaths(baseObj, EnvLookup::Normal);
1073 },
1074 m_jsFileWithPath, lookup);
1075}
1076
1077/*!
1078 \internal
1079 Depending on the creation options, this function adds LoadInfo of the provided path
1080*/
1081void DomEnvironment::addDependenciesToLoad(const Path &path)
1082{
1083 if (options() & Option::NoDependencies) {
1084 return;
1085 }
1086 Q_ASSERT(path);
1087 const auto loadInfo = std::make_shared<LoadInfo>(path);
1088 return addLoadInfo(DomItem(shared_from_this()), loadInfo);
1089}
1090
1091/*!
1092 \internal
1093 Enqueues path to the m_loadsWithWork (queue of the pending "load" jobs).
1094 In simpler words, schedule the load of the dependencies of the path from loadInfo.
1095*/
1096void DomEnvironment::addLoadInfo(const DomItem &self, const std::shared_ptr<LoadInfo> &loadInfo)
1097{
1098 if (!loadInfo)
1099 return;
1100 Path p = loadInfo->elementCanonicalPath();
1101 bool addWork = loadInfo->status() != LoadInfo::Status::Done;
1102 std::shared_ptr<LoadInfo> oldVal;
1103 {
1104 QMutexLocker l(mutex());
1105 oldVal = m_loadInfos.value(p);
1106 m_loadInfos.insert(p, loadInfo);
1107 if (addWork)
1108 m_loadsWithWork.enqueue(p);
1109 }
1110 if (oldVal && oldVal->status() != LoadInfo::Status::Done) {
1112 .error(tr("addLoadinfo replaces unfinished load info for %1")
1113 .arg(p.toString()))
1114 .handle());
1115 }
1116}
1117
1118std::shared_ptr<LoadInfo> DomEnvironment::loadInfo(const Path &path) const
1119{
1120 QMutexLocker l(mutex());
1121 return m_loadInfos.value(path);
1122}
1123
1124QHash<Path, std::shared_ptr<LoadInfo>> DomEnvironment::loadInfos() const
1125{
1126 QMutexLocker l(mutex());
1127 return m_loadInfos;
1128}
1129
1130QList<Path> DomEnvironment::loadInfoPaths() const
1131{
1132 auto lInfos = loadInfos();
1133 return lInfos.keys();
1134}
1135
1136DomEnvironment::DomEnvironment(const QStringList &loadPaths, Options options,
1137 DomCreationOption domCreationOption,
1138 const shared_ptr<DomUniverse> &universe)
1139 : m_options(options),
1143 m_domCreationOption(domCreationOption)
1144
1145{
1146}
1147
1148/*!
1149\internal
1150Do not call this method inside of DomEnvironment's constructor! It requires weak_from_this() that
1151only works after the constructor call finished.
1152*/
1153DomEnvironment::SemanticAnalysis DomEnvironment::semanticAnalysis()
1154{
1155 QMutexLocker l(mutex());
1156 return semanticAnalysisUnlocked();
1157}
1158
1159DomEnvironment::SemanticAnalysis DomEnvironment::prepareSemanticAnalysisForFileLoading()
1160{
1161 QMutexLocker guard(mutex());
1162 auto result = semanticAnalysisUnlocked();
1163 result.updateLoadPaths(m_loadPaths);
1164 result.setResourceFiles(m_resourcePaths);
1165 return result;
1166}
1167
1168DomEnvironment::SemanticAnalysis DomEnvironment::semanticAnalysisUnlocked()
1169{
1170 // QTBUG-124799: do not create a SemanticAnalysis in a temporary DomEnvironment, and use the one
1171 // from the base environment instead.
1172 if (m_base)
1173 return m_base->semanticAnalysis();
1174
1175 if (m_semanticAnalysis)
1176 return *m_semanticAnalysis;
1177
1179 m_semanticAnalysis = SemanticAnalysis(m_loadPaths);
1180 return *m_semanticAnalysis;
1181}
1182
1183DomEnvironment::SemanticAnalysis::SemanticAnalysis(const QStringList &loadPaths)
1184 : m_mapper(std::make_shared<QQmlJSResourceFileMapper>(
1185 QQmlJSUtils::resourceFilesFromBuildFolders(loadPaths))),
1186 m_importer(std::make_shared<QQmlJSImporter>(loadPaths, m_mapper.get(),
1187 QQmlJSImporterFlags{} | UseOptionalImports
1188 | TolerateFileSelectors
1189 | PreferQmlFilesFromSourceFolder))
1190{
1191}
1192
1193/*!
1194\internal
1195
1196Sets the new load paths in the importer.
1197
1198This affects all copies of SemanticAnalysis that use the same QQmlJSImporter and QQmlJSMapper
1199pointers.
1200*/
1201void DomEnvironment::SemanticAnalysis::updateLoadPaths(const QStringList &loadPaths)
1202{
1203 if (loadPaths == m_importer->importPaths())
1204 return;
1205
1206 m_importer->setImportPaths(loadPaths);
1207}
1208
1209void DomEnvironment::SemanticAnalysis::setResourceFiles(const QStringList &qrcFiles)
1210{
1211 if (qrcFiles == m_resourceFiles)
1212 return;
1213 m_resourceFiles = qrcFiles;
1214 *m_mapper = QQmlJSResourceFileMapper(qrcFiles);
1215}
1216
1217std::shared_ptr<DomEnvironment> DomEnvironment::create(const QStringList &loadPaths,
1218 Options options,
1219 DomCreationOption domCreationOption,
1220 const DomItem &universe)
1221{
1222 std::shared_ptr<DomUniverse> universePtr = universe.ownerAs<DomUniverse>();
1223 return std::make_shared<DomEnvironment>(loadPaths, options, domCreationOption, universePtr);
1224}
1225
1226DomEnvironment::DomEnvironment(const shared_ptr<DomEnvironment> &parent,
1227 const QStringList &loadPaths, Options options,
1228 DomCreationOption domCreationOption)
1229 : m_options(options),
1230 m_base(parent),
1233 m_domCreationOption(domCreationOption)
1234{
1235}
1236
1237void DomEnvironment::addQmlFile(const std::shared_ptr<QmlFile> &file, AddOption options)
1238{
1239 addExternalItem(file, file->canonicalFilePath(), options);
1241 QQmlJSScope::Ptr handle =
1242 semanticAnalysis().m_importer->importFile(file->canonicalFilePath());
1243
1244 // force reset the outdated qqmljsscope in case it was already populated
1245 file->setHandleForPopulation(handle);
1246 resetFactory(handle, semanticAnalysis().m_importer.get(),
1247 TypeReader{ weak_from_this(), m_loadPaths });
1248 }
1249}
1250
1251
1252void DomEnvironment::addJsFile(const std::shared_ptr<JsFile> &file, AddOption options)
1253{
1254 addExternalItem(file, file->canonicalFilePath(), options);
1255}
1256
1257void DomEnvironment::TypeReader::operator()(QQmlJSImporter *importer, const QString &filePath,
1258 const QSharedPointer<QQmlJSScope> &scopeToPopulate)
1259{
1260 Q_UNUSED(importer);
1261 Q_UNUSED(scopeToPopulate);
1262
1263 std::shared_ptr<DomEnvironment> envPtr = m_env.lock();
1264 // populate QML File if from implicit import directory
1265 // use the version in DomEnvironment and do *not* load from disk.
1266 auto it = envPtr->m_qmlFileWithPath.constFind(filePath);
1267 if (it == envPtr->m_qmlFileWithPath.constEnd()) {
1268 qCDebug(domLog) << "Import visitor tried to lazily load file \"" << filePath
1269 << "\", but that file was not found in the DomEnvironment. Was this "
1270 "file not discovered by the Dom's dependency loading mechanism?";
1271 return;
1272 }
1273 const DomItem qmlFile = it.value()->currentItem(DomItem(envPtr));
1274
1275 // workaround for QTBUG-137705 while waiting for qmlls to use separate DomEnvironments for files
1276 // requiring different importpaths (QTBUG-134308).
1277 const QStringList oldImportPaths = envPtr->loadPaths();
1278 envPtr->setLoadPaths(m_importPaths);
1279 envPtr->populateFromQmlFile(MutableDomItem(qmlFile));
1280 envPtr->setLoadPaths(oldImportPaths);
1281}
1282
1283bool DomEnvironment::commitToBase(const DomItem &, const shared_ptr<DomEnvironment> &validEnvPtr)
1284{
1285 if (!base())
1286 return false;
1287 QMap<QString, std::shared_ptr<ExternalItemInfo<QmlFile>>> my_qmlFileWithPath;
1288 QMap<QString, std::shared_ptr<ExternalItemInfo<JsFile>>> my_jsFileWithPath;
1289 QHash<Path, std::shared_ptr<LoadInfo>> my_loadInfos;
1290 std::optional<SemanticAnalysis> my_semanticAnalysis;
1291 {
1292 QMutexLocker l(mutex());
1293 my_qmlFileWithPath = m_qmlFileWithPath;
1294 my_jsFileWithPath = m_jsFileWithPath;
1295 my_loadInfos = m_loadInfos;
1296 my_semanticAnalysis = semanticAnalysisUnlocked();
1297 }
1298 {
1299 QMutexLocker lBase(base()->mutex()); // be more careful about makeCopy calls with lock?
1300 m_base->m_semanticAnalysis = my_semanticAnalysis;
1301 m_base->m_qmlFileWithPath.insert(my_qmlFileWithPath);
1302 m_base->m_jsFileWithPath.insert(my_jsFileWithPath);
1303 m_base->m_loadInfos.insert(my_loadInfos);
1304 }
1305 if (validEnvPtr)
1306 m_lastValidBase = validEnvPtr;
1307 if (m_lastValidBase) {
1308 QMutexLocker lValid(
1309 m_lastValidBase->mutex()); // be more careful about makeCopy calls with lock?
1310 m_lastValidBase->m_semanticAnalysis = std::move(my_semanticAnalysis);
1311 for (auto it = my_qmlFileWithPath.cbegin(), end = my_qmlFileWithPath.cend(); it != end;
1312 ++it) {
1313 if (it.value() && it.value()->current && it.value()->current->isValid())
1314 m_lastValidBase->m_qmlFileWithPath.insert(it.key(), it.value());
1315 }
1316 for (auto it = my_jsFileWithPath.cbegin(), end = my_jsFileWithPath.cend(); it != end;
1317 ++it) {
1318 if (it.value() && it.value()->current && it.value()->current->isValid())
1319 m_lastValidBase->m_jsFileWithPath.insert(it.key(), it.value());
1320 }
1321 m_lastValidBase->m_loadInfos.insert(my_loadInfos);
1322 }
1323
1324 auto newBaseForPopulation =
1325 m_lastValidBase ? m_lastValidBase->weak_from_this() : m_base->weak_from_this();
1326 // adapt the factory to the use the base or valid environment for unpopulated files, instead of
1327 // the current environment which will very probably be destroyed anytime soon
1328 for (const auto &qmlFile : my_qmlFileWithPath) {
1329 if (!qmlFile || !qmlFile->current)
1330 continue;
1331 QQmlJSScope::ConstPtr handle = qmlFile->current->handleForPopulation();
1332 if (!handle)
1333 continue;
1334 auto oldFactory = handle.factory();
1335 if (!oldFactory)
1336 continue;
1337
1338 resetFactory(handle, oldFactory->importer(),
1339 TypeReader{ newBaseForPopulation, m_loadPaths });
1340 }
1341 return true;
1342}
1343
1344void DomEnvironment::loadPendingDependencies()
1345{
1346 DomItem self(shared_from_this());
1347 while (true) {
1348 Path elToDo;
1349 std::shared_ptr<LoadInfo> loadInfo;
1350 {
1351 QMutexLocker l(mutex());
1352 if (m_loadsWithWork.isEmpty())
1353 break;
1354 elToDo = m_loadsWithWork.dequeue();
1355 m_inProgress.append(elToDo);
1356 loadInfo = m_loadInfos.value(elToDo);
1357 }
1358 if (loadInfo) {
1359 auto cleanup = qScopeGuard([this, &elToDo, &self] {
1360 QList<Callback> endCallbacks;
1361 {
1362 QMutexLocker l(mutex());
1363 m_inProgress.removeOne(elToDo);
1364 if (m_inProgress.isEmpty() && m_loadsWithWork.isEmpty()) {
1365 endCallbacks = m_allLoadedCallback;
1366 m_allLoadedCallback.clear();
1367 }
1368 }
1369 for (const Callback &cb : std::as_const(endCallbacks))
1370 cb(self.canonicalPath(), self, self);
1371 });
1372 DomItem loadInfoObj = self.copy(loadInfo);
1373 loadInfo->advanceLoad(loadInfoObj);
1374 } else {
1375 self.addError(myErrors().error(u"DomEnvironment::loadPendingDependencies could not "
1376 u"find loadInfo listed in m_loadsWithWork"_sv));
1377 {
1378 QMutexLocker l(mutex());
1379 m_inProgress.removeOne(elToDo);
1380 }
1381 Q_ASSERT(false
1382 && "DomEnvironment::loadPendingDependencies could not find loadInfo listed in "
1383 "m_loadsWithWork");
1384 }
1385 }
1386}
1387
1388bool DomEnvironment::finishLoadingDependencies(int waitMSec)
1389{
1390 bool hasPendingLoads = true;
1391 QDateTime endTime = QDateTime::currentDateTimeUtc().addMSecs(waitMSec);
1392 for (int i = 0; i < waitMSec / 10 + 2; ++i) {
1394 auto lInfos = loadInfos();
1395 auto it = lInfos.cbegin();
1396 auto end = lInfos.cend();
1397 hasPendingLoads = false;
1398 while (it != end) {
1399 if (*it && (*it)->status() != LoadInfo::Status::Done)
1400 hasPendingLoads = true;
1401 }
1402 if (!hasPendingLoads)
1403 break;
1404 auto missing = QDateTime::currentDateTimeUtc().msecsTo(endTime);
1405 if (missing < 0)
1406 break;
1407 if (missing > 100)
1408 missing = 100;
1409#if QT_FEATURE_thread
1410 QThread::msleep(missing);
1411#endif
1412 }
1413 return !hasPendingLoads;
1414}
1415
1416void DomEnvironment::addWorkForLoadInfo(const Path &elementCanonicalPath)
1417{
1418 QMutexLocker l(mutex());
1419 m_loadsWithWork.enqueue(elementCanonicalPath);
1420}
1421
1422DomEnvironment::Options DomEnvironment::options() const
1423{
1424 return m_options;
1425}
1426
1427std::shared_ptr<DomEnvironment> DomEnvironment::base() const
1428{
1429 return m_base;
1430}
1431
1432void DomEnvironment::setLoadPaths(const QStringList &v)
1433{
1434 QMutexLocker l(mutex());
1435 m_loadPaths = v;
1436}
1437
1438void DomEnvironment::setResourceFiles(const QStringList &v)
1439{
1440 QMutexLocker l(mutex());
1441 m_resourcePaths = v;
1442}
1443
1444QStringList DomEnvironment::loadPaths() const
1445{
1446 QMutexLocker l(mutex());
1447 return m_loadPaths;
1448}
1449
1450QList<Import> DomEnvironment::defaultImplicitImports()
1451{
1452 return QList<Import>({ Import::fromUriString(u"QML"_s, Version(1, 0)),
1453 Import(QmlUri::fromUriString(u"QtQml"_s), Version(6, 0)) });
1454}
1455
1456QList<Import> DomEnvironment::implicitImports() const
1457{
1458 return m_implicitImports;
1459}
1460
1461void DomEnvironment::addAllLoadedCallback(const DomItem &self, DomTop::Callback c)
1462{
1463 if (c) {
1464 bool immediate = false;
1465 {
1466 QMutexLocker l(mutex());
1467 if (m_loadsWithWork.isEmpty() && m_inProgress.isEmpty())
1468 immediate = true;
1469 else
1470 m_allLoadedCallback.append(c);
1471 }
1472 if (immediate)
1473 c(Path(), self, self);
1474 }
1475}
1476
1477void DomEnvironment::clearReferenceCache()
1478{
1479 m_referenceCache.clear();
1480}
1481
1482void DomEnvironment::populateFromQmlFile(MutableDomItem &&qmlFile)
1483{
1484 if (std::shared_ptr<QmlFile> qmlFilePtr = qmlFile.ownerAs<QmlFile>()) {
1485 auto logger = std::make_shared<QQmlJSLogger>();
1486 logger->setFilePath(qmlFile.canonicalFilePath());
1487 logger->setCode(qmlFilePtr->code());
1488 logger->setSilent(true);
1489
1490 auto setupFile = [&qmlFilePtr, &qmlFile, this](auto &&visitor) {
1491 Q_UNUSED(this); // note: integrity requires "this" to be in the capture list, while
1492 // other compilers complain about "this" being unused in the lambda
1493 AST::Node::accept(qmlFilePtr->ast(), visitor);
1494
1495 if (m_domCreationOption == DomCreationOption::Minimal)
1496 return;
1497
1498 CommentCollector collector(qmlFile);
1499 collector.collectComments();
1500 };
1501
1502 if (m_domCreationOption == DomCreationOption::Extended) {
1503 SemanticAnalysis analysis = prepareSemanticAnalysisForFileLoading();
1504 auto v = std::make_unique<QQmlDomAstCreatorWithQQmlJSScope>(qmlFile, logger.get(),
1505 analysis.m_importer.get());
1506 v->enableLoadFileLazily(true);
1507 v->enableScriptExpressions(true);
1508
1509 setupFile(v.get());
1510
1511 auto typeResolver =
1512 std::make_shared<QQmlJSTypeResolver>(analysis.m_importer.get());
1513 typeResolver->init(&v->scopeCreator(), nullptr);
1514 qmlFilePtr->setTypeResolverWithDependencies(
1515 typeResolver, { analysis.m_importer, analysis.m_mapper, std::move(logger) });
1516 } else {
1517 auto v = std::make_unique<QQmlDomAstCreator>(qmlFile);
1518 // we need file locations of script expressions in qmlformat for the "// qmlformat off"
1519 // functionality
1520 v->enableScriptExpressions(m_domCreationOption == DomCreationOption::Default);
1521 setupFile(v.get());
1522 }
1523 } else {
1524 qCWarning(domLog) << "populateQmlFile called on non qmlFile";
1525 return;
1526 }
1527}
1528
1530{
1531 shared_ptr<ExternalOwningItem> current = currentItem();
1532 DomItem currentObj = currentItem(self);
1533 return current->canonicalFilePath(currentObj);
1534}
1535
1536bool ExternalItemInfoBase::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
1537{
1538 if (!self.invokeVisitorOnLazyField(visitor, Fields::currentRevision,
1539 [this, &self]() { return currentRevision(self); }))
1540 return false;
1541 if (!self.invokeVisitorOnLazyField(visitor, Fields::lastRevision,
1542 [this, &self]() { return lastRevision(self); }))
1543 return false;
1544 if (!self.invokeVisitorOnLazyField(visitor, Fields::lastValidRevision,
1545 [this, &self]() { return lastValidRevision(self); }))
1546 return false;
1547 if (!visitor(Fields::currentItem,
1548 [&self, this]() { return currentItem(self); }))
1549 return false;
1550 if (!self.invokeVisitorOnLazyField(visitor, Fields::currentExposedAt,
1551 [this]() { return currentExposedAt(); }))
1552 return false;
1553 return true;
1554}
1555
1557{
1558 return currentItem()->revision();
1559}
1560
1562{
1563 Path p = currentItem()->canonicalPath();
1564 DomItem lastValue = self.universe()[p.mid(1, p.length() - 1)];
1565 return lastValue.revision();
1566}
1567
1569{
1570 Path p = currentItem()->canonicalPath();
1571 DomItem lastValidValue = self.universe()[p.mid(1, p.length() - 2)].field(Fields::validItem);
1572 return lastValidValue.revision();
1573}
1574
1576{
1577 shared_ptr<ExternalOwningItem> current = currentItem();
1578 return current->canonicalFilePath();
1579}
1580
1582{
1583 shared_ptr<ExternalOwningItem> current = currentItem();
1584 return current->canonicalPath().dropTail();
1585}
1586
1587bool ExternalItemPairBase::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
1588{
1589 if (!self.invokeVisitorOnLazyField(visitor, Fields::currentIsValid,
1590 [this]() { return currentIsValid(); }))
1591 return false;
1592 if (!visitor(Fields::validItem, [this, &self]() { return validItem(self); }))
1593 return false;
1594 if (!visitor(Fields::currentItem,
1595 [this, &self]() { return currentItem(self); }))
1596 return false;
1597 if (!self.invokeVisitorOnValue(visitor, Fields::validExposedAt, validExposedAt))
1598 return false;
1599 if (!self.invokeVisitorOnValue(visitor, Fields::currentExposedAt,
1600 currentExposedAt)) {
1601 return false;
1602 }
1603 return true;
1604}
1605
1607{
1608 return currentItem() == validItem();
1609}
1610
1611RefCacheEntry RefCacheEntry::forPath(const DomItem &el, const Path &canonicalPath)
1612{
1613 DomItem env = el.environment();
1614 std::shared_ptr<DomEnvironment> envPtr = env.ownerAs<DomEnvironment>();
1615 RefCacheEntry cached;
1616 if (envPtr) {
1617 QMutexLocker l(envPtr->mutex());
1618 cached = envPtr->m_referenceCache.value(canonicalPath, {});
1619 } else {
1620 qCWarning(domLog) << "No Env for reference" << canonicalPath << "from"
1621 << el.internalKindStr() << el.canonicalPath();
1622 Q_ASSERT(false);
1623 }
1624 return cached;
1625}
1626
1627bool RefCacheEntry::addForPath(const DomItem &el, const Path &canonicalPath, const RefCacheEntry &entry,
1628 AddOption addOption)
1629{
1630 DomItem env = el.environment();
1631 std::shared_ptr<DomEnvironment> envPtr = env.ownerAs<DomEnvironment>();
1632 bool didSet = false;
1633 if (envPtr) {
1634 QMutexLocker l(envPtr->mutex());
1635 RefCacheEntry &cached = envPtr->m_referenceCache[canonicalPath];
1636 switch (cached.cached) {
1637 case RefCacheEntry::Cached::None:
1638 cached = entry;
1639 didSet = true;
1640 break;
1641 case RefCacheEntry::Cached::First:
1642 if (addOption == AddOption::Overwrite || entry.cached == RefCacheEntry::Cached::All) {
1643 cached = entry;
1644 didSet = true;
1645 }
1646 break;
1647 case RefCacheEntry::Cached::All:
1648 if (addOption == AddOption::Overwrite || entry.cached == RefCacheEntry::Cached::All) {
1649 cached = entry;
1650 didSet = true;
1651 }
1652 }
1653 if (cached.cached == RefCacheEntry::Cached::First && cached.canonicalPaths.isEmpty())
1654 cached.cached = RefCacheEntry::Cached::All;
1655 } else {
1656 Q_ASSERT(false);
1657 }
1658 return didSet;
1659}
1660
1661} // end namespace Dom
1662} // end namespace QQmlJS
1663
1664QT_END_NAMESPACE
1665
1666#include "moc_qqmldomtop_p.cpp"
CommentCollector(MutableDomItem item)
virtual DomItem field(const DomItem &self, FieldName name) const
SemanticAnalysis semanticAnalysis()
void addQmlFile(const std::shared_ptr< QmlFile > &file, AddOption option=AddOption::KeepExisting)
bool finishLoadingDependencies(int waitMSec=30000)
std::shared_ptr< ExternalItemInfo< QmlFile > > qmlFileWithPath(const DomItem &self, const QString &path, EnvLookup options=EnvLookup::Normal) const
void populateFromQmlFile(MutableDomItem &&qmlFile)
std::shared_ptr< LoadInfo > loadInfo(const Path &path) const
void addDependenciesToLoad(const Path &path)
void setResourceFiles(const QStringList &v)
bool hasFile(const QString &filePath) const
Path canonicalPath() const override
void addJsFile(const std::shared_ptr< JsFile > &file, AddOption option=AddOption::KeepExisting)
void removePath(const QString &path)
bool commitToBase(const DomItem &self, const std::shared_ptr< DomEnvironment > &validEnv=nullptr)
QSet< QString > qmlFilePaths(const DomItem &self, EnvLookup lookup=EnvLookup::Normal) const
DomEnvironment(const std::shared_ptr< DomEnvironment > &parent, const QStringList &loadPaths, Options options=Option::SingleThreaded, DomCreationOption domCreationOption=Default)
DomItem field(const DomItem &self, FieldName name) const final override
static ErrorGroups myErrors()
void setLoadPaths(const QStringList &v)
std::shared_ptr< DomEnvironment > base() const
std::shared_ptr< DomEnvironment > makeCopy(const DomItem &self) const
QList< Path > loadInfoPaths() const
std::shared_ptr< ExternalItemInfo< JsFile > > jsFileWithPath(const DomItem &self, const QString &path, EnvLookup options=EnvLookup::Normal) const
void addWorkForLoadInfo(const Path &elementCanonicalPath)
std::shared_ptr< OwningItem > doCopy(const DomItem &self) const override
static constexpr DomType kindValue
void addLoadInfo(const DomItem &self, const std::shared_ptr< LoadInfo > &loadInfo)
DomEnvironment(const QStringList &loadPaths, Options options=Option::SingleThreaded, DomCreationOption domCreationOption=Default, const std::shared_ptr< DomUniverse > &universe=nullptr)
void loadFile(const FileToLoad &file, const Callback &callback, std::optional< DomType > fileType=std::optional< DomType >(), const ErrorHandler &h=nullptr)
std::shared_ptr< DomUniverse > universe() const
DomCreationOption domCreationOption() const
QList< Import > implicitImports() const
QHash< Path, std::shared_ptr< LoadInfo > > loadInfos() const
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
DomType kind() const override
void addAllLoadedCallback(const DomItem &self, Callback c)
QStringList loadPaths() const
QSet< QString > jsFilePaths(const DomItem &self, EnvLookup lookup=EnvLookup::Normal) const
A value type that references any element of the Dom.
DomItem path(const Path &p, const ErrorHandler &h=&defaultErrorHandler) const
DomItem universe() const
DomItem field(FieldName name) const
DomItem environment() const
Path canonicalPath() const
void addError(ErrorMessage &&msg) const
InternalKind internalKind() const
ErrorHandler errorHandler() const
DomItem operator[](const Path &path) const
static DomItem empty
static ErrorGroup domErrorGroup
Path canonicalPath(const DomItem &) const override
QQml::Dom::DomTop::loadFile.
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
virtual Path canonicalPath() const =0
DomItem::Callback Callback
DomItem containingObject(const DomItem &) const override
static ErrorGroups myErrors()
std::shared_ptr< OwningItem > doCopy(const DomItem &self) const override
static std::shared_ptr< DomUniverse > guaranteeUniverse(const std::shared_ptr< DomUniverse > &univ)
void removePath(const QString &dir)
DomUniverse(const QString &universeName)
LoadResult loadFile(const FileToLoad &file, DomType fileType, DomCreationOption creationOption={})
Path canonicalPath() const override
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
Represents a set of tags grouping a set of related error messages.
ErrorMessage warning(const Dumper &message) const
ErrorMessage error(const Dumper &message) const
Represents an error message connected to the dom.
ErrorMessage handle(const ErrorHandler &errorHandler=nullptr)
QString canonicalFilePath(const DomItem &) const final override
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const final override
int lastValidRevision(const DomItem &self) const
int lastRevision(const DomItem &self) const
int currentRevision(const DomItem &self) const
virtual DomItem currentItem(const DomItem &) const =0
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const final override
QString canonicalFilePath(const DomItem &) const final override
Path canonicalPath(const DomItem &self) const final override
virtual DomItem validItem(const DomItem &self) const =0
virtual std::shared_ptr< ExternalOwningItem > currentItem() const =0
virtual std::shared_ptr< ExternalOwningItem > validItem() const =0
virtual DomItem currentItem(const DomItem &self) const =0
void addEndCallback(const DomItem &self, std::function< void(Path, const DomItem &, const DomItem &)> callback)
void finishedLoadingDep(const DomItem &self, const Dependency &d)
Status status() const
void execEnd(const DomItem &self)
void advanceLoad(const DomItem &self)
std::shared_ptr< OwningItem > doCopy(const DomItem &self) const override
Path canonicalPath(const DomItem &self) const override
Path elementCanonicalPath() const
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
MutableDomItem(const DomItem &item)
A DomItem that owns other DomItems and is managed through a shared pointer.
void addErrorLocal(ErrorMessage &&msg)
Represents an immutable JsonPath like path in the Qml code model (from a DomItem to another DomItem).
static Path fromRoot(PathRoot r)
Path withField(FieldName name) const
Path mid(int offset, int length) const
static bool addForPath(const DomItem &el, const Path &canonicalPath, const RefCacheEntry &entry, AddOption addOption=AddOption::KeepExisting)
static RefCacheEntry forPath(const DomItem &el, const Path &canonicalPath)
static DomType fileTypeForPath(const DomItem &self, const QString &canonicalFilePath)
std::function< void(const ErrorMessage &)> ErrorHandler
Combined button and popup list for selecting options.
#define NewErrorGroup(name)