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>
18#include <QtQmlCompiler/private/qqmljsutils_p.h>
20#include <QtCore/QBasicMutex>
21#include <QtCore/QCborArray>
22#include <QtCore/QDebug>
24#include <QtCore/QFile>
25#include <QtCore/QFileInfo>
26#include <QtCore/QRegularExpression>
27#include <QtCore/QScopeGuard>
29# include <QtCore/QThread>
36using namespace Qt::StringLiterals;
45
46
47
48
49
50
51
52
53
54
55
75
76
77
78
79
80
81
82
83
84
85
86
97 const std::shared_ptr<DomUniverse> &univ)
99 const auto next = [] {
100 Q_CONSTINIT
static std::atomic<
int> counter(0);
101 return counter.fetch_add(1, std::memory_order_relaxed) + 1;
106 return std::make_shared<DomUniverse>(
107 QLatin1String(
"universe") + QString::number(next()));
110DomItem DomUniverse::create(
const QString &universeName)
112 auto res =
std::make_shared<DomUniverse>(universeName);
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));
132 [
this](
const DomItem &) {
return qmlFilePaths(); },
133 QLatin1String(
"QmlFile")));
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));
141 [
this](
const DomItem &) {
return jsFilePaths(); }, QLatin1String(
"JsFile")));
148 QRegularExpression r(QRegularExpression::anchoredPattern(QLatin1String(R"(.*Copy([0-9]*)$)")));
149 auto m = r.match(m_name);
152 newName = QStringLiteral(u"%1Copy%2").arg(m_name).arg(m.captured(1).toInt() + 1);
154 newName = m_name + QLatin1String(
"Copy");
155 auto res =
std::make_shared<DomUniverse>(newName);
161 if (canonicalFilePath.endsWith(u".qml", Qt::CaseInsensitive)
162 || canonicalFilePath.endsWith(u".qmlannotation", Qt::CaseInsensitive)) {
164 }
else if (canonicalFilePath.endsWith(u".js", Qt::CaseInsensitive)
165 || canonicalFilePath.endsWith(u".mjs", Qt::CaseInsensitive)) {
170 .error(QCoreApplication::translate(
"Dom::fileTypeForPath",
171 "Could not detect type of file %1")
172 .arg(canonicalFilePath))
181 DomItem univ(shared_from_this());
185 const auto &preLoadResult = preload(univ, file, fileType);
191 return load(
std::get<ContentWithDate>(preLoadResult), file, fileType, creationOption);
196 .error(tr(
"Ignoring request to load file %1 of unexpected type %2, "
197 "calling callback immediately")
198 .arg(file.canonicalPath(), domTypeToString(fileType))
)
200 Q_ASSERT(
false &&
"loading non supported file type");
205DomUniverse::
LoadResult DomUniverse::load(
const ContentWithDate &codeWithDate,
209 QString canonicalPath = file.canonicalPath();
216 auto qmlFile = parseQmlFile(codeWithDate.content, file, codeWithDate.date, creationOption);
217 return insertOrUpdateExternalItem(
std::move(qmlFile));
219 auto jsFile = parseJsFile(codeWithDate.content, file, codeWithDate.date);
220 return insertOrUpdateExternalItem(
std::move(jsFile));
224 return {
std::move(oldValue),
std::move(newValue) };
228
229
230
231
232
233
234
235DomUniverse::PreloadResult DomUniverse::preload(
const DomItem &univ,
const FileToLoad &file,
238 QString canonicalPath = file.canonicalPath();
239 ContentWithDate codeWithDate;
241 if (file.content().has_value()) {
242 codeWithDate = { file.content()->data, file.content()->date };
246 const auto &curValueItem = getItemIfMostRecent(univ, fType, canonicalPath);
247 if (curValueItem.has_value()) {
248 return LoadResult{ curValueItem.value(), curValueItem.value() };
251 auto readResult = readFileContent(canonicalPath);
257 codeWithDate =
std::get<ContentWithDate>(readResult);
262 const auto &curValueItem = getItemIfHasSameCode(univ, fType, canonicalPath, codeWithDate);
263 if (curValueItem.has_value()) {
264 return LoadResult{ curValueItem.value(), curValueItem.value() };
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'/');
277 m_qmlFileWithPath.removeIf(toDelete);
278 m_jsFileWithPath.removeIf(toDelete);
281DomUniverse::ReadResult DomUniverse::readFileContent(
const QString &canonicalPath)
const
283 if (canonicalPath.isEmpty()) {
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() };
294 if (!file.open(QIODevice::ReadOnly)) {
296 tr(
"Error opening path %1: %2 %3")
297 .arg(canonicalPath, QString::number(file.error()), file.errorString())
);
299 auto content = QString::fromUtf8(file.readAll());
301 return ContentWithDate{ std::move(content), QDateTime::currentDateTimeUtc() };
304std::shared_ptr<QmlFile> DomUniverse::parseQmlFile(
const QString &code,
const FileToLoad &file,
305 const QDateTime &contentDate,
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);
316 envPtr =
std::make_shared<DomEnvironment>(QStringList(),
318 creationOption, shared_from_this());
319 envPtr->addQmlFile(qmlFile);
321 if (qmlFile->isValid()) {
327 DomItem qmlFileObj = env.copy(qmlFile);
329 errs += m.toString();
333 qCWarning(domLog).noquote().nospace()
334 <<
"Parsed invalid file " << file.canonicalPath() << errs;
339std::shared_ptr<JsFile> DomUniverse::parseJsFile(
const QString &code,
const FileToLoad &file,
340 const QDateTime &contentDate)
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);
351 envPtr =
std::make_shared<DomEnvironment>(QStringList(),
354 envPtr->addJsFile(jsFile);
356 if (!jsFile->isValid()) {
358 DomItem qmlFileObj = env.copy(jsFile);
360 errs += m.toString();
364 qCWarning(domLog).noquote().nospace()
365 <<
"Parsed invalid file " << file.canonicalPath() << errs;
371
372
373
374
376 const QString &path)
const
379 case DomType::QmlFile:
380 return m_qmlFileWithPath.value(path);
381 case DomType::JsFile:
382 return m_jsFileWithPath.value(path);
390 const QString &canonicalPath)
const
392 QFileInfo fInfo(canonicalPath);
393 bool valueItemIsMostRecent =
false;
398 QMutexLocker l(mutex());
399 value = getPathValueOrNull(fType, canonicalPath);
400 valueItemIsMostRecent = valueHasMostRecentItem(value.get(), fInfo.lastModified());
402 if (valueItemIsMostRecent) {
403 return univ.copy(value);
409 const QString &canonicalPath,
410 const ContentWithDate &codeWithDate)
const
413 bool valueItemHasSameCode =
false;
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);
425 if (valueItemHasSameCode) {
426 return univ.copy(value);
432
433
434
435
437 const QDateTime &lastModified)
442 return lastModified < value->currentItem()->lastDataUpdateAt();
446
447
448
449
455 QString curContent = value->currentItem()->code();
456 return !curContent.isNull() && curContent == content;
461 auto res =
std::make_shared<LoadInfo>(*
this);
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));
467 .warning([&self](
const Sink &sink) {
468 sink(u"Copying an in progress LoadInfo, which is most likely an error (");
473 QMutexLocker l(res->mutex());
476 res->m_inProgress.clear();
477 res->m_endCallbacks.clear();
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,
494 cont = cont && self.invokeVisitorOnValue(visitor,
Fields::nNotdone,
nNotDone());
505 QMutexLocker l(mutex());
507 case Status::NotStarted:
508 case Status::Starting:
509 case Status::InProgress:
510 case Status::CallingCallbacks:
511 m_endCallbacks.append(callback);
526 bool depValid =
false;
528 QMutexLocker l(mutex());
536 if (!m_toDo.isEmpty()) {
537 dep = m_toDo.dequeue();
538 m_inProgress.append(dep);
548 case Status::NotStarted:
549 refreshedDataAt(QDateTime::currentDateTimeUtc());
550 doAddDependencies(self);
551 refreshedDataAt(QDateTime::currentDateTimeUtc());
553 QMutexLocker l(mutex());
555 if (m_toDo.isEmpty() && m_inProgress.isEmpty())
566 refreshedDataAt(QDateTime::currentDateTimeUtc());
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()) {
573 FileToLoad::fromFileSystem(envPtr, dep.filePath),
581 Q_ASSERT(
false &&
"dependency without uri and filePath");
585 tr(
"advanceLoad called but found no work, which should never happen")
));
591 "advanceLoad called after work should have been done, which should never happen")
));
598 bool didRemove =
false;
599 bool unexpectedState =
false;
602 QMutexLocker l(mutex());
603 didRemove = m_inProgress.removeOne(d);
608 unexpectedState =
true;
613 if (m_toDo.isEmpty() && m_inProgress.isEmpty()) {
622 sink(u"LoadInfo::finishedLoadingDep did not find its dependency in those inProgress "
628 &&
"LoadInfo::finishedLoadingDep did not find its dependency in those inProgress");
630 if (unexpectedState) {
632 sink(u"LoadInfo::finishedLoadingDep found an unexpected state (");
636 Q_ASSERT(
false &&
"LoadInfo::finishedLoadingDep did find an unexpected state");
644 QList<std::function<
void(Path,
const DomItem &,
const DomItem &)>> endCallbacks;
645 bool unexpectedState =
false;
647 QMutexLocker l(mutex());
649 endCallbacks = m_endCallbacks;
650 m_endCallbacks.clear();
652 Q_ASSERT(!unexpectedState &&
"LoadInfo::execEnd found an unexpected state");
656 auto cleanup = qScopeGuard([
this, p, &el] {
657 QList<std::function<
void(Path,
const DomItem &,
const DomItem &)>> otherCallbacks;
658 bool unexpectedState2 =
false;
660 QMutexLocker l(mutex());
663 otherCallbacks = m_endCallbacks;
664 m_endCallbacks.clear();
666 Q_ASSERT(!unexpectedState2 &&
"LoadInfo::execEnd found an unexpected state");
667 for (
auto const &cb : otherCallbacks) {
672 for (
auto const &cb : endCallbacks) {
679void LoadInfo::doAddDependencies(
const DomItem &self)
692 QString currentFilePath = currentFile.canonicalFilePath();
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())
702 Dependency{ QString(), Version(),
703 canonicalPath.headName(), DomType::QmlFile });
711 tr(
"Ignoring dependencies for empty (invalid) type %1")
712 .arg(domTypeToString(el.internalKind()))
));
716 .arg(domTypeToString(el.internalKind()),
723 bool unexpectedState =
false;
725 QMutexLocker l(mutex());
729 Q_ASSERT(!unexpectedState &&
"LoadInfo::addDependency found an unexpected state");
735
736
737
738
739
740
741
742
763 cont = cont && DomTop::iterateDirectSubpaths(self, visitor);
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]() {
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));
777 [&self,
this](
const DomItem &) {
return qmlFilePaths(self); },
778 QLatin1String(
"QmlFile")));
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));
787 [
this](
const DomItem &map) {
788 DomItem mapOw = map.owner();
789 return jsFilePaths(mapOw);
791 QLatin1String(
"JsFile")));
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();
806 cont = cont && visitor(
807 Fields::loadsWithWork, [&ensureInfo, &self, &loadsWithWork]() {
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());
818 [loadsWithWork](
const DomItem &) {
819 return index_type(loadsWithWork.size());
821 nullptr, QLatin1String(
"Path")));
823 cont = cont && visitor(
Fields::inProgress, [&self, &ensureInfo, &inProgress]() {
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());
834 [inProgress](
const DomItem &) {
return index_type(inProgress.size()); },
835 nullptr, QLatin1String(
"Path")));
837 cont = cont && visitor(
Fields::loadInfo, [&self,
this]() {
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())
848 return map.copy(*it);
850 [infos](
const DomItem &) {
851 return QSet<QString>(infos.keyBegin(), infos.keyEnd());
853 QLatin1String(
"LoadInfo")));
855 cont = cont && self.invokeVisitorOnField(visitor,
Fields::imports, m_implicitImports);
856 cont = cont && self.invokeVisitorOnLazyField(visitor,
Fields::nAllLoadedCallbacks,
857 [&nAllLoadedCallbacks, &ensureInfo]() {
859 return nAllLoadedCallbacks;
871 return std::static_pointer_cast<DomEnvironment>(
doCopy(self));
876 shared_ptr<DomEnvironment> res;
878 res =
std::make_shared<DomEnvironment>(m_base, m_loadPaths, m_options, m_domCreationOption);
880 res =
std::make_shared<DomEnvironment>(m_loadPaths, m_options, m_domCreationOption,
885bool DomEnvironment::
hasFile(
const QString &filePath)
const
887 return m_qmlFileWithPath.contains(filePath);
892 if (options() & DomEnvironment::Option::NoDependencies)
893 loadFile(file, callback, DomTop::Callback(), fileType, h);
898 loadFile(file, DomTop::Callback(), callback, fileType, h);
903
904
905
906
907
908
909
910
911
912
913
919 DomItem self(shared_from_this());
921 (
bool(fileType) ? (*fileType) : fileTypeForPath(self, _file.logicalPath()));
928 file.setCanonicalPath(QQmlJSUtils::qmlSourcePathFromBuildPath(
929 semanticAnalysis().m_mapper.get(), file.canonicalPath()));
930 file.setLogicalPath(file.logicalPath());
934 if (file.canonicalPath().isEmpty()) {
935 if (!file.content() || file.content()->data.isNull()) {
938 .error(tr(
"Non existing path to load: '%1'").arg(file.logicalPath())
)
944 endCallback(Path(), DomItem::empty, DomItem::empty);
949 file.canonicalPath() = file.logicalPath();
956 const auto &fetchResult = fetchFileFromEnvs<QmlFile>(file);
957 oldValue = fetchResult.first;
958 newValue = fetchResult.second;
960 const auto &loadRes = universe()->loadFile(file, fType, m_domCreationOption);
961 addExternalItemInfo<QmlFile>(loadRes.currentItem, loadCallback, endCallback);
966 const auto &loadRes = universe()->loadFile(file, fType, m_domCreationOption);
967 addExternalItemInfo<JsFile>(loadRes.currentItem, loadCallback, endCallback);
971 myErrors().error(tr(
"Unexpected file to load: '%1'").arg(file.canonicalPath())
).handle(h);
979 Path p = self.copy(newValue).canonicalPath();
980 std::shared_ptr<LoadInfo> lInfo = loadInfo(p);
983 DomItem oldValueObj = self.copy(oldValue);
984 DomItem newValueObj = self.copy(newValue);
985 loadCallback(p, oldValueObj, newValueObj);
994 const Path &,
const DomItem &,
const DomItem &env) {
995 DomItem el = env.path(p);
996 endCallback(p, el, el);
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'/');
1007 m_qmlFileWithPath.removeIf(toDelete);
1008 m_jsFileWithPath.removeIf(toDelete);
1011shared_ptr<DomUniverse> DomEnvironment::
universe()
const {
1015 return m_base->universe();
1045std::shared_ptr<ExternalItemInfo<QmlFile>>
1048 return lookup<QmlFile>(path, options);
1053 return getStrings<std::shared_ptr<ExternalItemInfo<QmlFile>>>(
1055 DomItem baseObj(m_base);
1056 return m_base->qmlFilePaths(baseObj, EnvLookup::Normal);
1058 m_qmlFileWithPath, lookup);
1061std::shared_ptr<ExternalItemInfo<JsFile>>
1064 return lookup<JsFile>(path, options);
1069 return getStrings<std::shared_ptr<ExternalItemInfo<JsFile>>>(
1071 DomItem baseObj(m_base);
1072 return m_base->jsFilePaths(baseObj, EnvLookup::Normal);
1074 m_jsFileWithPath, lookup);
1078
1079
1080
1083 if (options() & Option::NoDependencies) {
1087 const auto loadInfo =
std::make_shared<LoadInfo>(path);
1092
1093
1094
1095
1100 Path p = loadInfo->elementCanonicalPath();
1101 bool addWork = loadInfo->status() != LoadInfo::Status::Done;
1102 std::shared_ptr<LoadInfo> oldVal;
1104 QMutexLocker l(mutex());
1105 oldVal = m_loadInfos.value(p);
1106 m_loadInfos.insert(p, loadInfo);
1108 m_loadsWithWork.enqueue(p);
1112 .error(tr(
"addLoadinfo replaces unfinished load info for %1")
1120 QMutexLocker l(mutex());
1121 return m_loadInfos.value(path);
1126 QMutexLocker l(mutex());
1132 auto lInfos = loadInfos();
1133 return lInfos.keys();
1136DomEnvironment::
DomEnvironment(
const QStringList &loadPaths, Options options,
1138 const shared_ptr<DomUniverse> &universe)
1143 m_domCreationOption(domCreationOption)
1149
1150
1151
1152
1155 QMutexLocker l(mutex());
1156 return semanticAnalysisUnlocked();
1159DomEnvironment::SemanticAnalysis DomEnvironment::prepareSemanticAnalysisForFileLoading()
1161 QMutexLocker guard(mutex());
1162 auto result = semanticAnalysisUnlocked();
1163 result.updateLoadPaths(m_loadPaths);
1164 result.setResourceFiles(m_resourcePaths);
1168DomEnvironment::SemanticAnalysis DomEnvironment::semanticAnalysisUnlocked()
1173 return m_base->semanticAnalysis();
1175 if (m_semanticAnalysis)
1176 return *m_semanticAnalysis;
1179 m_semanticAnalysis = SemanticAnalysis(m_loadPaths);
1180 return *m_semanticAnalysis;
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))
1194
1195
1196
1197
1198
1199
1200
1201void DomEnvironment::SemanticAnalysis::updateLoadPaths(
const QStringList &loadPaths)
1203 if (loadPaths == m_importer->importPaths())
1206 m_importer->setImportPaths(loadPaths);
1209void DomEnvironment::SemanticAnalysis::setResourceFiles(
const QStringList &qrcFiles)
1211 if (qrcFiles == m_resourceFiles)
1213 m_resourceFiles = qrcFiles;
1214 *m_mapper = QQmlJSResourceFileMapper(qrcFiles);
1217std::shared_ptr<DomEnvironment> DomEnvironment::create(
const QStringList &loadPaths,
1222 std::shared_ptr<DomUniverse> universePtr = universe.ownerAs<DomUniverse>();
1223 return std::make_shared<DomEnvironment>(loadPaths, options, domCreationOption, universePtr);
1226DomEnvironment::
DomEnvironment(
const shared_ptr<DomEnvironment> &parent,
1227 const QStringList &loadPaths, Options options,
1233 m_domCreationOption(domCreationOption)
1239 addExternalItem(file, file->canonicalFilePath(), options);
1241 QQmlJSScope::Ptr handle =
1245 file->setHandleForPopulation(handle);
1247 TypeReader{ weak_from_this(), m_loadPaths });
1254 addExternalItem(file, file->canonicalFilePath(), options);
1257void DomEnvironment::TypeReader::operator()(QQmlJSImporter *importer,
const QString &filePath,
1258 const QSharedPointer<QQmlJSScope> &scopeToPopulate)
1261 Q_UNUSED(scopeToPopulate);
1263 std::shared_ptr<DomEnvironment> envPtr = m_env.lock();
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?";
1273 const DomItem qmlFile = it.value()->currentItem(
DomItem(envPtr));
1277 const QStringList oldImportPaths = envPtr->loadPaths();
1278 envPtr->setLoadPaths(m_importPaths);
1280 envPtr->setLoadPaths(oldImportPaths);
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;
1292 QMutexLocker l(mutex());
1293 my_qmlFileWithPath = m_qmlFileWithPath;
1294 my_jsFileWithPath = m_jsFileWithPath;
1295 my_loadInfos = m_loadInfos;
1296 my_semanticAnalysis = semanticAnalysisUnlocked();
1299 QMutexLocker lBase(base()->mutex());
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);
1306 m_lastValidBase = validEnvPtr;
1307 if (m_lastValidBase) {
1308 QMutexLocker lValid(
1309 m_lastValidBase->mutex());
1310 m_lastValidBase->m_semanticAnalysis = std::move(my_semanticAnalysis);
1311 for (
auto it = my_qmlFileWithPath.cbegin(), end = my_qmlFileWithPath.cend(); it != end;
1313 if (it.value() && it.value()->current && it.value()->current->isValid())
1314 m_lastValidBase->m_qmlFileWithPath.insert(it.key(), it.value());
1316 for (
auto it = my_jsFileWithPath.cbegin(), end = my_jsFileWithPath.cend(); it != end;
1318 if (it.value() && it.value()->current && it.value()->current->isValid())
1319 m_lastValidBase->m_jsFileWithPath.insert(it.key(), it.value());
1321 m_lastValidBase->m_loadInfos.insert(my_loadInfos);
1324 auto newBaseForPopulation =
1325 m_lastValidBase ? m_lastValidBase->weak_from_this() : m_base->weak_from_this();
1328 for (
const auto &qmlFile : my_qmlFileWithPath) {
1329 if (!qmlFile || !qmlFile->current)
1331 QQmlJSScope::ConstPtr handle = qmlFile->current->handleForPopulation();
1334 auto oldFactory = handle.factory();
1338 resetFactory(handle, oldFactory->importer(),
1339 TypeReader{ newBaseForPopulation, m_loadPaths });
1346 DomItem self(shared_from_this());
1349 std::shared_ptr<LoadInfo> loadInfo;
1351 QMutexLocker l(mutex());
1352 if (m_loadsWithWork.isEmpty())
1354 elToDo = m_loadsWithWork.dequeue();
1355 m_inProgress.append(elToDo);
1356 loadInfo = m_loadInfos.value(elToDo);
1359 auto cleanup = qScopeGuard([
this, &elToDo, &self] {
1360 QList<Callback> endCallbacks;
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();
1369 for (
const Callback &cb : std::as_const(endCallbacks))
1370 cb(self.canonicalPath(), self, self);
1372 DomItem loadInfoObj = self.copy(loadInfo);
1373 loadInfo->advanceLoad(loadInfoObj);
1376 u"find loadInfo listed in m_loadsWithWork"_sv)
);
1378 QMutexLocker l(mutex());
1379 m_inProgress.removeOne(elToDo);
1382 &&
"DomEnvironment::loadPendingDependencies could not find loadInfo listed in "
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;
1400 hasPendingLoads =
true;
1402 if (!hasPendingLoads)
1404 auto missing = QDateTime::currentDateTimeUtc().msecsTo(endTime);
1409#if QT_FEATURE_thread
1410 QThread::msleep(missing);
1413 return !hasPendingLoads;
1418 QMutexLocker l(mutex());
1419 m_loadsWithWork.enqueue(elementCanonicalPath);
1427std::shared_ptr<DomEnvironment> DomEnvironment::
base()
const
1434 QMutexLocker l(mutex());
1440 QMutexLocker l(mutex());
1441 m_resourcePaths = v;
1446 QMutexLocker l(mutex());
1450QList<Import> DomEnvironment::defaultImplicitImports()
1452 return QList<
Import>({ Import::fromUriString(u"QML"_s, Version(1, 0)),
1453 Import(QmlUri::fromUriString(u"QtQml"_s), Version(6, 0)) });
1458 return m_implicitImports;
1464 bool immediate =
false;
1466 QMutexLocker l(mutex());
1467 if (m_loadsWithWork.isEmpty() && m_inProgress.isEmpty())
1470 m_allLoadedCallback.append(c);
1479 m_referenceCache.clear();
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);
1490 auto setupFile = [&qmlFilePtr, &qmlFile,
this](
auto &&visitor) {
1493 AST::Node::accept(qmlFilePtr->ast(), visitor);
1503 SemanticAnalysis analysis = prepareSemanticAnalysisForFileLoading();
1505 analysis.m_importer.get());
1506 v->enableLoadFileLazily(
true);
1507 v->enableScriptExpressions(
true);
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) });
1517 auto v =
std::make_unique<QQmlDomAstCreator>(qmlFile);
1524 qCWarning(domLog) <<
"populateQmlFile called on non qmlFile";
1531 shared_ptr<ExternalOwningItem> current = currentItem();
1533 return current->canonicalFilePath(currentObj);
1538 if (!self.invokeVisitorOnLazyField(visitor,
Fields::currentRevision,
1541 if (!self.invokeVisitorOnLazyField(visitor,
Fields::lastRevision,
1544 if (!self.invokeVisitorOnLazyField(visitor,
Fields::lastValidRevision,
1547 if (!visitor(
Fields::currentItem,
1550 if (!self.invokeVisitorOnLazyField(visitor,
Fields::currentExposedAt,
1551 [
this]() {
return currentExposedAt(); }))
1558 return currentItem()->revision();
1563 Path p = currentItem()->canonicalPath();
1570 Path p = currentItem()->canonicalPath();
1577 shared_ptr<ExternalOwningItem> current = currentItem();
1578 return current->canonicalFilePath();
1583 shared_ptr<ExternalOwningItem> current = currentItem();
1584 return current->canonicalPath().dropTail();
1589 if (!self.invokeVisitorOnLazyField(visitor,
Fields::currentIsValid,
1594 if (!visitor(
Fields::currentItem,
1597 if (!self.invokeVisitorOnValue(visitor,
Fields::validExposedAt, validExposedAt))
1599 if (!self.invokeVisitorOnValue(visitor,
Fields::currentExposedAt,
1600 currentExposedAt)) {
1614 std::shared_ptr<DomEnvironment> envPtr = env.ownerAs<DomEnvironment>();
1617 QMutexLocker l(envPtr->mutex());
1618 cached = envPtr->m_referenceCache.value(canonicalPath, {});
1620 qCWarning(domLog) <<
"No Env for reference" << canonicalPath <<
"from"
1631 std::shared_ptr<DomEnvironment> envPtr = env.ownerAs<DomEnvironment>();
1632 bool didSet =
false;
1634 QMutexLocker l(envPtr->mutex());
1635 RefCacheEntry &cached = envPtr->m_referenceCache[canonicalPath];
1636 switch (cached.cached) {
1637 case RefCacheEntry::Cached::None:
1641 case RefCacheEntry::Cached::First:
1642 if (addOption == AddOption::Overwrite || entry.cached == RefCacheEntry::Cached::All) {
1647 case RefCacheEntry::Cached::All:
1648 if (addOption == AddOption::Overwrite || entry.cached == RefCacheEntry::Cached::All) {
1653 if (cached.cached == RefCacheEntry::Cached::First && cached.canonicalPaths.isEmpty())
1654 cached.cached = RefCacheEntry::Cached::All;
1666#include "moc_qqmldomtop_p.cpp"
virtual DomItem field(const DomItem &self, FieldName name) const
SemanticAnalysis semanticAnalysis()
void clearReferenceCache()
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
void loadPendingDependencies()
A value type that references any element of the Dom.
DomItem path(const Path &p, const ErrorHandler &h=&defaultErrorHandler) 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 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
bool currentIsValid() const
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)
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)