aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmldom/qqmldomoutwriter.cpp
blob: 722315702e191e7b249ea77ef615a82096205e53 (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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// 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 "qqmldomformatdirectivescanner_p.h"
#include "qqmldomoutwriter_p.h"
#include "qqmldomlinewriter_p.h"
#include "qqmldomindentinglinewriter_p.h"
#include "qqmldomitem_p.h"
#include "qqmldomcomments_p.h"

#include <QtCore/QLoggingCategory>

QT_BEGIN_NAMESPACE
namespace QQmlJS {
namespace Dom {

using DisabledRegionIt = OutWriter::OffsetToDisabledRegionMap::const_iterator;

static inline OutWriter::RegionToCommentMap extractComments(const DomItem &it)
{
    OutWriter::RegionToCommentMap comments;
    if (const RegionComments *cRegionsPtr = it.field(Fields::comments).as<RegionComments>()) {
        comments = cRegionsPtr->regionComments();
    }
    return comments;
}

/*
\internal
\brief Utility function to determine if two source locations overlap
*/
static inline bool overlaps(const SourceLocation &a, const SourceLocation &b)
{
    return a.isValid() && b.isValid() && (a.begin() < b.end() && b.begin() < a.end());
}

/*
\internal
\brief Utility function to determine the indent after skipping to format a piece of code
*/
static inline int indentAfterPartialFormatting(int initialIndent, QStringView code,
                                               LineWriterOptions options)
{
    FormatTextStatus initialState = FormatTextStatus::initialStatus(initialIndent);
    FormatPartialStatus partialStatus({}, options.formatOptions, initialState);
    IndentingLineWriter indentingLineWriter([](QStringView line) { Q_UNUSED(line) }, QString(),
                                            options, partialStatus.currentStatus);
    OutWriter indentTracker(indentingLineWriter);
    const auto commentLines = code.split(u'\n');
    for (const auto &line : commentLines) {
        if (!line.isEmpty()) {
            partialStatus =
                    formatCodeLine(line, options.formatOptions, partialStatus.currentStatus);
            indentTracker.write(line);
        }
    }

    return indentTracker.indent;
}

/*
\internal
\brief Utility function to determine if a given location overlapping disabled region, returns an
iterator to the region if found, or end() if not found
*/
static inline DisabledRegionIt
findOverlappingRegion(const SourceLocation &loc,
                      const OutWriter::OffsetToDisabledRegionMap &formatDisabledRegions)
{
    if (!loc.isValid())
        return formatDisabledRegions.cend();

    return std::find_if(formatDisabledRegions.cbegin(), formatDisabledRegions.cend(),
                        [&loc](const auto &it) { return it.isValid() && overlaps(loc, it); });
}

QStringView OutWriter::attachedDisableCode(quint32 offset) const
{
    if (formatDisabledRegions.contains(offset)) {
        const auto &loc = formatDisabledRegions.value(offset);
        return code.mid(loc.offset, loc.length);
    }
    return {};
}

// This function examines the provided SourceLocation to determine if it overlaps with any regions
// where formatting is disabled. If such a region is found and the formatter is currently enabled,
// it writes the disabled region and disables the formatter. If no overlapping region is found,
// the formatter is enabled.
void OutWriter::maybeWriteDisabledRegion(const SourceLocation &loc)
{
    if (!loc.isValid())
        return;
    if (formatDisabledRegions.isEmpty())
        return;
    if (const auto foundRegionIt = findOverlappingRegion(loc, formatDisabledRegions);
        foundRegionIt != formatDisabledRegions.end()) {
        if (isFormatterEnabled) {
            writeDisabledRegion(loc);
            isFormatterEnabled = false;
        }
    } else {
        isFormatterEnabled = true;
    }
}

// Decides whether the given region should be formatted or not, based on the
// disabled regions found in the file and updates and returns the formatting enabled state.
bool OutWriter::shouldFormat(const FileLocations::Tree &fLoc, FileLocationRegion region)
{
    if (!fLoc || formatDisabledRegions.isEmpty())
        return isFormatterEnabled;

    if (const auto regions = fLoc->info().regions; regions.contains(region)) {
        isFormatterEnabled = findOverlappingRegion(regions.value(region), formatDisabledRegions)
                == formatDisabledRegions.end();
    }
    return isFormatterEnabled;
}

void OutWriter::scanFormatDirectives(QStringView code, const QList<SourceLocation> &comments)
{
    // Disabled regions cannot be effective if the line writer options
    // are set to normalize or sort imports.
    const auto shouldScanDirectives = lineWriter.options().attributesSequence
                    != LineWriterOptions::AttributesSequence::Normalize
            && !lineWriter.options().sortImports;
    if (!shouldScanDirectives)
        return;

    formatDisabledRegions = QmlFormat::identifyDisabledRegions(code, comments);
}

bool OutWriter::formatterEnabled() const
{
    return isFormatterEnabled;
}

void OutWriter::writeDisabledRegion(const SourceLocation &loc)
{
    const auto disabledCode = attachedDisableCode(loc.offset);
    int newIndent = indentAfterPartialFormatting(indent, disabledCode, lineWriter.options());
    lineWriter.ensureNewline();
    lineWriter.setLineIndent(0);
    indentNextlines = false;
    lineWriter.write(disabledCode);
    lineWriter.setLineIndent(newIndent);
    indentNextlines = true;
}

void OutWriter::maybeWriteComment(const Comment &comment)
{
    maybeWriteDisabledRegion(comment.sourceLocation());

    if (!skipComments && formatterEnabled()) {
        comment.write(*this);
    }

    // if disabled, maybe reenabled with this comment
    if (!formatterEnabled()) {
        auto directive = QmlFormat::directiveFromComment(comment.rawComment());
        if (directive == QmlFormat::Directive::On)
            isFormatterEnabled = true;
    }
}

void OutWriter::itemStart(const DomItem &it)
{
    if (skipComments)
        return;

    pendingComments.push(extractComments(it));
    writePreComment(MainRegion);
}

void OutWriter::itemEnd()
{
    if (skipComments)
        return;

    Q_ASSERT(!pendingComments.isEmpty());
    writePostComment(MainRegion);
    pendingComments.pop();
}

void OutWriter::writePreComment(FileLocationRegion region)
{
    if (skipComments)
        return;

    const auto &comments = pendingComments.top();
    if (comments.contains(region)) {
        const auto attachedComments = comments[region];
        for (const auto &comment : attachedComments.preComments())
            maybeWriteComment(comment);
    }
}

void OutWriter::writePostComment(FileLocationRegion region)
{
    if (skipComments)
        return;

    auto &comments = pendingComments.top();
    if (comments.contains(region)) {
        const auto attachedComments = comments[region];
        for (const auto &comment : attachedComments.postComments())
            maybeWriteComment(comment);
        comments.remove(region);
    }
}

static bool regionIncreasesIndentation(FileLocationRegion region)
{
    switch (region) {
    case LeftBraceRegion:
        return true;
    case LeftBracketRegion:
        return true;
    default:
        return false;
    }
    Q_UNREACHABLE_RETURN(false);
}

static bool regionDecreasesIndentation(FileLocationRegion region)
{
    switch (region) {
    case RightBraceRegion:
        return true;
    case RightBracketRegion:
        return true;
    default:
        return false;
    }
    Q_UNREACHABLE_RETURN(false);
}

/*!
\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(const FileLocations::Tree &fLoc, FileLocationRegion region)
{
    using namespace Qt::Literals::StringLiterals;
    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;
    case IfKeywordRegion:
        codeForRegion = u"if"_s;
        break;
    case SwitchKeywordRegion:
        codeForRegion = u"switch"_s;
        break;
    case YieldKeywordRegion:
        codeForRegion = u"yield"_s;
        break;
    case NewKeywordRegion:
        codeForRegion = u"new"_s;
        break;
    case ThisKeywordRegion:
        codeForRegion = u"this"_s;
        break;
    case SuperKeywordRegion:
        codeForRegion = u"super"_s;
        break;
    case StarTokenRegion:
        codeForRegion = u"*"_s;
        break;
    case DollarLeftBraceTokenRegion:
        codeForRegion = u"${"_s;
        break;
    case LeftBacktickTokenRegion:
    case RightBacktickTokenRegion:
        codeForRegion = u"`"_s;
        break;
    case FinalKeywordRegion:
        codeForRegion = u"final"_s;
        break;
    // not keywords:
    case ImportUriRegion:
    case IdNameRegion:
    case IdentifierRegion:
    case PragmaValuesRegion:
    case MainRegion:
    case OnTargetRegion:
    case TypeIdentifierRegion:
    case TypeModifierRegion:
    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(fLoc, region, codeForRegion);
}

OutWriter &OutWriter::writeRegion(const FileLocations::Tree &fLoc, FileLocationRegion region,
                                  QStringView toWrite)
{
    writePreComment(region);
    if (regionDecreasesIndentation(region))
        decreaseIndent(1);
    if (shouldFormat(fLoc, region))
        lineWriter.write(toWrite);
    if (regionIncreasesIndentation(region))
        increaseIndent(1);
    writePostComment(region);
    return *this;
}

} // namespace Dom
} // namespace QQmlJS
QT_END_NAMESPACE