aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmldom/qqmldomoutwriter.cpp
blob: 7bdbf505e2f9573de313181162808e5dc6800cbf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qqmldomoutwriter_p.h"
#include "qqmldomattachedinfo_p.h"
#include "qqmldomlinewriter_p.h"
#include "qqmldomitem_p.h"
#include "qqmldomcomments_p.h"
#include "qqmldomexternalitems_p.h"
#include "qqmldomtop_p.h"

#include <QtCore/QLoggingCategory>

QT_BEGIN_NAMESPACE
namespace QQmlJS {
namespace Dom {

OutWriterState::OutWriterState(Path itCanonicalPath, DomItem &it, FileLocations::Tree fLoc)
    : itemCanonicalPath(itCanonicalPath), item(it), currentMap(fLoc)
{
    DomItem cRegions = it.field(Fields::comments);
    if (const RegionComments *cRegionsPtr = cRegions.as<RegionComments>()) {
        pendingComments = cRegionsPtr->regionComments;
        fLoc->info().ensureCommentLocations(pendingComments.keys());
    }
}

void OutWriterState::closeState(OutWriter &w)
{
    if (w.lineWriter.options().updateOptions & LineWriterOptions::Update::Locations)
        w.lineWriter.endSourceLocation(fullRegionId);
    if (!pendingRegions.isEmpty()) {
        qCWarning(writeOutLog) << "PendingRegions non empty when closing item"
                               << pendingRegions.keys();
        auto iend = pendingRegions.end();
        auto it = pendingRegions.begin();
        while (it == iend) {
            w.lineWriter.endSourceLocation(it.value());
            ++it;
        }
    }
    if (!w.skipComments && !pendingComments.isEmpty())
        qCWarning(writeOutLog) << "PendingComments when closing item "
                               << item.canonicalPath().toString() << "for regions"
                               << pendingComments.keys();
}

OutWriterState &OutWriter::state(int i)
{
    return states[states.size() - 1 - i];
}

void OutWriter::itemStart(DomItem &it)
{
    if (!topLocation->path())
        topLocation->setPath(it.canonicalPath());
    bool updateLocs = lineWriter.options().updateOptions & LineWriterOptions::Update::Locations;
    FileLocations::Tree newFLoc = topLocation;
    Path itP = it.canonicalPath();
    if (updateLocs) {
        if (!states.isEmpty()
            && states.last().itemCanonicalPath
                    == itP.mid(0, states.last().itemCanonicalPath.length())) {
            int oldL = states.last().itemCanonicalPath.length();
            newFLoc = FileLocations::ensure(states.last().currentMap,
                                            itP.mid(oldL, itP.length() - oldL),
                                            AttachedInfo::PathType::Relative);

        } else {
            newFLoc = FileLocations::ensure(topLocation, itP, AttachedInfo::PathType::Canonical);
        }
    }
    states.append(OutWriterState(itP, it, newFLoc));
    if (updateLocs)
        state().fullRegionId = lineWriter.startSourceLocation(
                [newFLoc](SourceLocation l) { FileLocations::updateFullLocation(newFLoc, l); });
    regionStart(QString());
}

void OutWriter::itemEnd(DomItem &it)
{
    Q_ASSERT(states.size() > 0);
    Q_ASSERT(state().item == it);
    regionEnd(QString());
    state().closeState(*this);
    states.removeLast();
}

void OutWriter::regionStart(QString rName)
{
    Q_ASSERT(!state().pendingRegions.contains(rName));
    FileLocations::Tree fMap = state().currentMap;
    if (!skipComments && state().pendingComments.contains(rName)) {
        bool updateLocs = lineWriter.options().updateOptions & LineWriterOptions::Update::Locations;
        QList<SourceLocation> *cLocs =
                (updateLocs ? &(fMap->info().preCommentLocations[rName]) : nullptr);
        state().pendingComments[rName].writePre(*this, cLocs);
    }
    state().pendingRegions[rName] = lineWriter.startSourceLocation(
            [rName, fMap](SourceLocation l) { FileLocations::addRegion(fMap, rName, l); });
}

void OutWriter::regionEnd(QString rName)
{
    Q_ASSERT(state().pendingRegions.contains(rName));
    FileLocations::Tree fMap = state().currentMap;
    lineWriter.endSourceLocation(state().pendingRegions.value(rName));
    state().pendingRegions.remove(rName);
    if (state().pendingComments.contains(rName)) {
        if (!skipComments) {
            bool updateLocs =
                    lineWriter.options().updateOptions & LineWriterOptions::Update::Locations;
            QList<SourceLocation> *cLocs =
                    (updateLocs ? &(fMap->info().postCommentLocations[rName]) : nullptr);
            state().pendingComments[rName].writePost(*this, cLocs);
        }
        state().pendingComments.remove(rName);
    }
}

OutWriter &OutWriter::writeRegion(QString rName, QStringView toWrite)
{
    regionStart(rName);
    lineWriter.write(toWrite);
    regionEnd(rName);
    return *this;
}

DomItem OutWriter::updatedFile(DomItem &qmlFile)
{
    Q_ASSERT(qmlFile.internalKind() == DomType::QmlFile);
    if (std::shared_ptr<QmlFile> qmlFilePtr = qmlFile.ownerAs<QmlFile>()) {
        std::shared_ptr<QmlFile> copyPtr = qmlFilePtr->makeCopy(qmlFile);
        DomItem env = qmlFile.environment();
        std::shared_ptr<DomEnvironment> envPtr = env.ownerAs<DomEnvironment>();
        Q_ASSERT(envPtr);
        auto newEnvPtr = std::make_shared<DomEnvironment>(
                envPtr, envPtr->loadPaths(), envPtr->options());
        newEnvPtr->addQmlFile(copyPtr);
        MutableDomItem copy = MutableDomItem(DomItem(newEnvPtr).copy(copyPtr));
        FileLocations::Tree newLoc = topLocation;
        Path qmlFilePath = qmlFile.canonicalPath();
        if (newLoc->path() != qmlFilePath) {
            if (newLoc->path()) {
                if (newLoc->path().length() > qmlFilePath.length()
                    && newLoc->path().mid(0, qmlFilePath.length()) == qmlFilePath) {
                    newLoc = FileLocations::createTree(qmlFilePath);
                    FileLocations::Tree loc =
                            FileLocations::ensure(newLoc, newLoc->path().mid(qmlFilePath.length()),
                                                  AttachedInfo::PathType::Relative);
                    loc->setSubItems(topLocation->subItems());
                } else {
                    qCWarning(writeOutLog)
                            << "failed to base fileLocations in OutWriter (" << newLoc->path()
                            << ") to current file (" << qmlFilePath << ")";
                }
            } else {
                newLoc = FileLocations::createTree(qmlFilePath);
                Q_ASSERT(newLoc->subItems().isEmpty() && newLoc->info().regions.isEmpty());
            }
        }
        copyPtr->setFileLocationsTree(newLoc);
        UpdatedScriptExpression::visitTree(
                reformattedScriptExpressions,
                [&copy, qmlFilePath](Path p, UpdatedScriptExpression::Tree t) {
                    if (std::shared_ptr<ScriptExpression> exprPtr = t->info().expr) {
                        Q_ASSERT(p.mid(0, qmlFilePath.length()) == qmlFilePath);
                        MutableDomItem targetExpr = copy.path(p.mid(qmlFilePath.length()));
                        if (!targetExpr)
                            qCWarning(writeOutLog) << "failed to get" << p.mid(qmlFilePath.length())
                                                   << "from" << copy.canonicalPath();
                        else if (exprPtr->ast()
                                 || (!targetExpr.as<ScriptExpression>()
                                     || !targetExpr.as<ScriptExpression>()->ast()))
                            targetExpr.setScript(exprPtr);
                        else {
                            qCWarning(writeOutLog).noquote()
                                    << "Skipped update of reformatted ScriptExpression with "
                                       "code:\n---------------\n"
                                    << exprPtr->code() << "\n---------------\n preCode:" <<
                                    [exprPtr](Sink s) { sinkEscaped(s, exprPtr->preCode()); }
                                    << "\n postCode: " <<
                                    [exprPtr](Sink s) { sinkEscaped(s, exprPtr->postCode()); }
                                    << "\n as it failed standalone reparse with errors:" <<
                                    [&targetExpr, exprPtr](Sink s) {
                                        targetExpr.item()
                                                .copy(exprPtr, targetExpr.canonicalPath())
                                                .iterateErrors(
                                                        [s](DomItem, ErrorMessage msg) {
                                                            s(u"\n  ");
                                                            msg.dump(s);
                                                            return true;
                                                        },
                                                        true);
                                    }
                                    << "\n";
                        }
                    }
                    return true;
                });
        return copy.item();
    }
    return DomItem();
}

} // namespace Dom
} // namespace QQmlJS
QT_END_NAMESPACE