aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmldom/qqmldomcodeformatter_p.h
blob: 084272401e4cb7c558241b1a17d5585cd9d39f56 (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
// Copyright (C) 2022 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

#ifndef QQMLDOMCODEFORMATTER_P_H
#define QQMLDOMCODEFORMATTER_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "qqmldom_global.h"
#include "qqmldomfunctionref_p.h"
#include "qqmldomscanner_p.h"
#include "qqmldomlinewriter_p.h"

#include <QtCore/QStack>
#include <QtCore/QList>
#include <QtCore/QSet>
#include <QtCore/QVector>
#include <QtCore/QMetaObject>

QT_BEGIN_NAMESPACE

namespace QQmlJS {
namespace Dom {

class QMLDOM_EXPORT FormatTextStatus
{
    Q_GADGET
public:
    enum class StateType : quint8 {
        Invalid = 0,

        TopmostIntro, // The first line in a "topmost" definition.

        TopQml, // root state for qml
        TopJs, // root for js
        ObjectdefinitionOrJs, // file starts with identifier

        MultilineCommentStart,
        MultilineCommentCont,

        ImportStart, // after 'import'
        ImportMaybeDotOrVersionOrAs, // after string or identifier
        ImportDot, // after .
        ImportMaybeAs, // after version
        ImportAs,

        PropertyStart, // after 'property'
        PropertyModifiers, // after 'default' or readonly
        RequiredProperty, // after required
        PropertyListOpen, // after 'list' as a type
        PropertyName, // after the type
        PropertyMaybeInitializer, // after the identifier
        ComponentStart, // after component
        ComponentName, // after component Name

        TypeAnnotation, // after a : starting a type annotation
        TypeParameter, // after a < in a type annotation (starting type parameters)

        EnumStart, // after 'enum'

        SignalStart, // after 'signal'
        SignalMaybeArglist, // after identifier
        SignalArglistOpen, // after '('

        FunctionStart, // after 'function'
        FunctionArglistOpen, // after '(' starting function argument list
        FunctionArglistClosed, // after ')' in argument list, expecting '{'

        BindingOrObjectdefinition, // after an identifier

        BindingAssignment, // after : in a binding
        ObjectdefinitionOpen, // after {

        Expression,
        ExpressionContinuation, // at the end of the line, when the next line definitely is a
                                // continuation
        ExpressionMaybeContinuation, // at the end of the line, when the next line may be an
                                     // expression
        ExpressionOrObjectdefinition, // after a binding starting with an identifier ("x: foo")
        ExpressionOrLabel, // when expecting a statement and getting an identifier

        ParenOpen, // opening ( in expression
        BracketOpen, // opening [ in expression
        ObjectliteralOpen, // opening { in expression

        ObjectliteralAssignment, // after : in object literal

        BracketElementStart, // after starting bracket_open or after ',' in bracket_open
        BracketElementMaybeObjectdefinition, // after an identifier in bracket_element_start

        TernaryOp, // The ? : operator
        TernaryOpAfterColon, // after the : in a ternary

        JsblockOpen,

        EmptyStatement, // for a ';', will be popped directly
        BreakcontinueStatement, // for continue/break, may be followed by identifier

        IfStatement, // After 'if'
        MaybeElse, // after the first substatement in an if
        ElseClause, // The else line of an if-else construct.

        ConditionOpen, // Start of a condition in 'if', 'while', entered after opening paren

        Substatement, // The first line after a conditional or loop construct.
        SubstatementOpen, // The brace that opens a substatement block.

        LabelledStatement, // after a label

        ReturnStatement, // After 'return'
        ThrowStatement, // After 'throw'

        StatementWithCondition, // After the 'for', 'while', ... token
        StatementWithConditionParenOpen, // While inside the (...)

        TryStatement, // after 'try'
        CatchStatement, // after 'catch', nested in try_statement
        FinallyStatement, // after 'finally', nested in try_statement
        MaybeCatchOrFinally, // after ther closing '}' of try_statement and catch_statement,
                             // nested in try_statement

        DoStatement, // after 'do'
        DoStatementWhileParenOpen, // after '(' in while clause

        SwitchStatement, // After 'switch' token
        CaseStart, // after a 'case' or 'default' token
        CaseCont // after the colon in a case/default
    };
    Q_ENUM(StateType)

    static QString stateToString(StateType type);

    class State
    {
    public:
        quint16 savedIndentDepth = 0;
        StateType type = StateType::Invalid;
        bool operator==(const State &other) const
        {
            return type == other.type && savedIndentDepth == other.savedIndentDepth;
        }
        QString typeStr() const { return FormatTextStatus::stateToString(type); }
    };

    static bool isBracelessState(StateType type)
    {
        return type == StateType::IfStatement || type == StateType::ElseClause
                || type == StateType::Substatement || type == StateType::BindingAssignment
                || type == StateType::BindingOrObjectdefinition;
    }

    static bool isExpressionEndState(StateType type)
    {
        return type == StateType::TopmostIntro || type == StateType::TopJs
                || type == StateType::ObjectdefinitionOpen || type == StateType::DoStatement
                || type == StateType::JsblockOpen || type == StateType::SubstatementOpen
                || type == StateType::BracketOpen || type == StateType::ParenOpen
                || type == StateType::CaseCont || type == StateType::ObjectliteralOpen;
    }

    static FormatTextStatus initialStatus(int baseIndent = 0)
    {
        return FormatTextStatus {
            Scanner::State {},
            QVector<State>({ State { quint16(baseIndent), StateType::TopmostIntro } }), baseIndent
        };
    }

    size_t size() const { return states.size(); }

    State state(int belowTop = 0) const;

    void pushState(StateType type, quint16 savedIndentDepth)
    {
        states.append(State { savedIndentDepth, type });
    }

    State popState()
    {
        if (states.isEmpty()) {
            Q_ASSERT(false);
            return State();
        }
        State res = states.last();
        states.removeLast();
        return res;
    }

    Scanner::State lexerState = {};
    QVector<State> states;
    int finalIndent = 0;
};

class QMLDOM_EXPORT FormatPartialStatus
{
    Q_GADGET
public:

    using OnEnterCallback =
            function_ref<void(FormatTextStatus::StateType newState, int *indentDepth,
                              int *savedIndentDepth, const FormatPartialStatus &fStatus)>;

    // to determine whether a line was joined, Tokenizer needs a
    // newline character at the end, lease ensure that line contains it
    FormatPartialStatus() = default;
    FormatPartialStatus(const FormatPartialStatus &o) = default;
    FormatPartialStatus &operator=(const FormatPartialStatus &o) = default;
    FormatPartialStatus(QStringView line, const FormatOptions &options,
                        const FormatTextStatus &initialStatus)
        : line(line),
          options(options),
          initialStatus(initialStatus),
          currentStatus(initialStatus),
          currentIndent(0),
          tokenIndex(0)
    {
        Scanner::State startState = initialStatus.lexerState;
        currentIndent = initialStatus.finalIndent;
        Scanner tokenize;
        lineTokens = tokenize(line, startState);
        currentStatus.lexerState = tokenize.state();
    }

    void enterState(FormatTextStatus::StateType newState);
    void leaveState(bool statementDone);
    void turnIntoState(FormatTextStatus::StateType newState);

    const Token &tokenAt(int idx) const;
    int tokenCount() const { return lineTokens.size(); }
    int column(int index) const;
    QStringView tokenText(const Token &token) const;
    void handleTokens();

    bool tryInsideExpression(bool alsoExpression);
    bool tryStatement();

    void defaultOnEnter(FormatTextStatus::StateType newState, int *indentDepth,
                        int *savedIndentDepth) const;

    int indentLine();
    int indentForNewLineAfter() const;
    void recalculateWithIndent(int indent);

    void dump() const;

    QStringView line;
    FormatOptions options;
    FormatTextStatus initialStatus;
    FormatTextStatus currentStatus;
    int indentOffset = 0;
    int currentIndent = 0;
    QList<Token> lineTokens;
    int tokenIndex = 0;
};

QMLDOM_EXPORT int indentForLineStartingWithToken(const FormatTextStatus &oldStatus,
                                                 const FormatOptions &options,
                                                 int token = QQmlJSGrammar::T_ERROR);

QMLDOM_EXPORT FormatPartialStatus formatCodeLine(QStringView line, const FormatOptions &options,
                                                 const FormatTextStatus &initialStatus);

} // namespace Dom
} // namespace QQmlJs
QT_END_NAMESPACE
#endif // QQMLDOMCODEFORMATTER_P_H