aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmldom/qqmldomoutwriter.cpp
blob: 30b75e115597a565cfe8ec0c7e1aff816b16ee27 (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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// 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(
        const Path &itCanonicalPath, const DomItem &it, const 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();
}

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(const 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(MainRegion);
}

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

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

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

/*!
\internal
Helper method for writeRegion(FileLocationRegion region) that allows to use
\c{writeRegion(ColonTokenRegion);} instead of having to write out the more error-prone
\c{writeRegion(ColonTokenRegion, ":");} for tokens and keywords.
*/
OutWriter &OutWriter::writeRegion(FileLocationRegion region)
{
    QString codeForRegion;
    switch (region) {
    case ComponentKeywordRegion:
        codeForRegion = u"component"_s;
        break;
    case IdColonTokenRegion:
    case ColonTokenRegion:
        codeForRegion = u":"_s;
        break;
    case ImportTokenRegion:
        codeForRegion = u"import"_s;
        break;
    case AsTokenRegion:
        codeForRegion = u"as"_s;
        break;
    case OnTokenRegion:
        codeForRegion = u"on"_s;
        break;
    case IdTokenRegion:
        codeForRegion = u"id"_s;
        break;
    case LeftBraceRegion:
        codeForRegion = u"{"_s;
        break;
    case RightBraceRegion:
        codeForRegion = u"}"_s;
        break;
    case LeftBracketRegion:
        codeForRegion = u"["_s;
        break;
    case RightBracketRegion:
        codeForRegion = u"]"_s;
        break;
    case LeftParenthesisRegion:
        codeForRegion = u"("_s;
        break;
    case RightParenthesisRegion:
        codeForRegion = u")"_s;
        break;
    case EnumKeywordRegion:
        codeForRegion = u"enum"_s;
        break;
    case DefaultKeywordRegion:
        codeForRegion = u"default"_s;
        break;
    case RequiredKeywordRegion:
        codeForRegion = u"required"_s;
        break;
    case ReadonlyKeywordRegion:
        codeForRegion = u"readonly"_s;
        break;
    case PropertyKeywordRegion:
        codeForRegion = u"property"_s;
        break;
    case FunctionKeywordRegion:
        codeForRegion = u"function"_s;
        break;
    case SignalKeywordRegion:
        codeForRegion = u"signal"_s;
        break;
    case ReturnKeywordRegion:
        codeForRegion = u"return"_s;
        break;
    case EllipsisTokenRegion:
        codeForRegion = u"..."_s;
        break;
    case EqualTokenRegion:
        codeForRegion = u"="_s;
        break;
    case PragmaKeywordRegion:
        codeForRegion = u"pragma"_s;
        break;
    case CommaTokenRegion:
        codeForRegion = u","_s;
        break;
    case ForKeywordRegion:
        codeForRegion = u"for"_s;
        break;
    case ElseKeywordRegion:
        codeForRegion = u"else"_s;
        break;
    case DoKeywordRegion:
        codeForRegion = u"do"_s;
        break;
    case WhileKeywordRegion:
        codeForRegion = u"while"_s;
        break;
    case TryKeywordRegion:
        codeForRegion = u"try"_s;
        break;
    case CatchKeywordRegion:
        codeForRegion = u"catch"_s;
        break;
    case FinallyKeywordRegion:
        codeForRegion = u"finally"_s;
        break;
    case CaseKeywordRegion:
        codeForRegion = u"case"_s;
        break;
    case ThrowKeywordRegion:
        codeForRegion = u"throw"_s;
        break;
    case ContinueKeywordRegion:
        codeForRegion = u"continue"_s;
        break;
    case BreakKeywordRegion:
        codeForRegion = u"break"_s;
        break;
    case QuestionMarkTokenRegion:
        codeForRegion = u"?"_s;
        break;
    case SemicolonTokenRegion:
        codeForRegion = u";"_s;
        break;

    // not keywords:
    case ImportUriRegion:
    case IdNameRegion:
    case IdentifierRegion:
    case PragmaValuesRegion:
    case MainRegion:
    case OnTargetRegion:
    case TypeIdentifierRegion:
    case FirstSemicolonTokenRegion:
    case SecondSemicolonRegion:
    case InOfTokenRegion:
    case OperatorTokenRegion:
    case VersionRegion:
    case EnumValueRegion:
        Q_ASSERT_X(false, "regionToString", "Using regionToString on a value or an identifier!");
        return *this;
    }

    return writeRegion(region, codeForRegion);
}

OutWriter &OutWriter::writeRegion(FileLocationRegion region, QStringView toWrite)
{
    regionStart(region);
    lineWriter.write(toWrite);
    regionEnd(region);
    return *this;
}
/*!
   \internal
    Restores written out FileItem using intermediate information saved during DOM traversal.
    It enables verifying DOM consistency of the written item later.

    At the moment of writing, intermediate information consisting only of UpdatedScriptExpression,
    however this is subject for change. The process of restoration is the following:
    1. Creating copy of the initial fileItem
    2. Updating relevant data/subitems modified during the WriteOut
    3. Returning an item containing updates.
 */
DomItem OutWriter::restoreWrittenFileItem(const DomItem &fileItem)
{
    switch (fileItem.internalKind()) {
    case DomType::QmlFile:
        return writtenQmlFileItem(fileItem, fileItem.canonicalPath());
    case DomType::JsFile:
        return writtenJsFileItem(fileItem, fileItem.canonicalPath());
    default:
        qCWarning(writeOutLog) << fileItem.internalKind() << " is not supported";
        return DomItem{};
    }
}

DomItem OutWriter::writtenQmlFileItem(const DomItem &fileItem, const Path &filePath)
{
    Q_ASSERT(fileItem.internalKind() == DomType::QmlFile);
    auto mutableFile = fileItem.makeCopy(DomItem::CopyOption::EnvDisconnected);
    // QmlFile specific visitor for reformattedScriptExpressions tree
    // lambda function responsible for the update of the initial expression by the formatted one
    auto exprUpdater = [&mutableFile, filePath](
                               const Path &p, const UpdatedScriptExpression::Tree &t) {
        if (std::shared_ptr<ScriptExpression> formattedExpr = t->info().expr) {
            Q_ASSERT(p.mid(0, filePath.length()) == filePath);
            MutableDomItem originalExprItem = mutableFile.path(p.mid(filePath.length()));
            if (!originalExprItem)
                qCWarning(writeOutLog) << "failed to get" << p.mid(filePath.length()) << "from"
                                       << mutableFile.canonicalPath();
            // Verifying originalExprItem.as<ScriptExpression>() == false is handy
            // because we can't call setScript on the ScriptExpression itself and it needs to
            // be called on the container / parent item. See setScript for details
            else if (formattedExpr->ast()
                     || (!originalExprItem.as<ScriptExpression>()
                         || !originalExprItem.as<ScriptExpression>()->ast()))
                originalExprItem.setScript(formattedExpr);
            else {
                logScriptExprUpdateSkipped(originalExprItem.item(),
                                           originalExprItem.canonicalPath(), formattedExpr);
            }
        }
        return true;
    };
    // update relevant formatted expressions
    UpdatedScriptExpression::visitTree(reformattedScriptExpressions, exprUpdater);
    return mutableFile.item();
}

DomItem OutWriter::writtenJsFileItem(const DomItem &fileItem, const Path &filePath)
{
    Q_ASSERT(fileItem.internalKind() == DomType::JsFile);
    auto mutableFile = fileItem.makeCopy(DomItem::CopyOption::EnvDisconnected);
    UpdatedScriptExpression::visitTree(
            reformattedScriptExpressions,
            [&mutableFile, filePath](const Path &p, const UpdatedScriptExpression::Tree &t) {
                if (std::shared_ptr<ScriptExpression> formattedExpr = t->info().expr) {
                    Q_ASSERT(p.mid(0, filePath.length()) == filePath);
                    mutableFile.mutableAs<JsFile>()->setExpression(formattedExpr);
                }
                return true;
            });
    return mutableFile.item();
}

void OutWriter::logScriptExprUpdateSkipped(
        const DomItem &exprItem, const Path &exprPath,
        const std::shared_ptr<ScriptExpression> &formattedExpr)
{
    qCWarning(writeOutLog).noquote() << "Skipped update of reformatted ScriptExpression with "
                                        "code:\n---------------\n"
                                     << formattedExpr->code() << "\n---------------\n preCode:" <<
            [&formattedExpr](Sink s) { sinkEscaped(s, formattedExpr->preCode()); }
                                     << "\n postCode: " <<
            [&formattedExpr](Sink s) { sinkEscaped(s, formattedExpr->postCode()); }
                                     << "\n as it failed standalone reparse with errors:" <<
            [&exprItem, &exprPath, &formattedExpr](Sink s) {
                exprItem.copy(formattedExpr, exprPath)
                        .iterateErrors(
                                [s](const DomItem &, const ErrorMessage &msg) {
                                    s(u"\n  ");
                                    msg.dump(s);
                                    return true;
                                },
                                true);
            } << "\n";
}
} // namespace Dom
} // namespace QQmlJS
QT_END_NAMESPACE