aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cppeditor/quickfixes/convertnumericliteral.cpp
blob: fe50475bc9cf4b3f4ba455208e9c76bb94e796c2 (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
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "convertnumericliteral.h"

#include "../cppeditortr.h"
#include "../cpprefactoringchanges.h"
#include "cppquickfix.h"

#include <bitset>

using namespace CPlusPlus;
using namespace Utils;

namespace CppEditor::Internal {
namespace {

class ConvertNumericLiteralOp: public CppQuickFixOperation
{
public:
    ConvertNumericLiteralOp(const CppQuickFixInterface &interface, int start, int end,
                            const QString &replacement)
        : CppQuickFixOperation(interface)
        , start(start)
        , end(end)
        , replacement(replacement)
    {}

    void perform() override
    {
        currentFile()->apply(ChangeSet::makeReplace(start, end, replacement));
    }

private:
    int start, end;
    QString replacement;
};

/*!
  Base class for converting numeric literals between decimal, octal and hex.
  Does the base check for the specific ones and parses the number.

  Test cases:
    0xFA0Bu;
    0X856A;
    298.3;
    199;
    074;
    199L;
    074L;
    -199;
    -017;
    0783; // invalid octal
    0; // border case, allow only hex<->decimal

  Activates on: numeric literals
*/
class ConvertNumericLiteral : public CppQuickFixFactory
{
#ifdef WITH_TESTS
public:
    static QObject *createTest() { return new QObject; }
#endif

private:
    void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override
    {
        const QList<AST *> &path = interface.path();
        CppRefactoringFilePtr file = interface.currentFile();

        if (path.isEmpty())
            return;

        NumericLiteralAST *literal = path.last()->asNumericLiteral();

        if (!literal)
            return;

        Token token = file->tokenAt(literal->asNumericLiteral()->literal_token);
        if (!token.is(T_NUMERIC_LITERAL))
            return;
        const NumericLiteral *numeric = token.number;
        if (numeric->isDouble() || numeric->isFloat())
            return;

        // remove trailing L or U and stuff
        const char * const spell = numeric->chars();
        int numberLength = numeric->size();
        while (numberLength > 0 && !std::isxdigit(spell[numberLength - 1]))
            --numberLength;
        if (numberLength < 1)
            return;

        // convert to number
        bool valid;
        ulong value = 0;
        const QString x = QString::fromUtf8(spell).left(numberLength);
        if (x.startsWith("0b", Qt::CaseInsensitive))
            value = x.mid(2).toULong(&valid, 2);
        else
            value = x.toULong(&valid, 0);

        if (!valid)
            return;

        const int priority = path.size() - 1; // very high priority
        const int start = file->startOf(literal);
        const char * const str = numeric->chars();

        const bool isBinary = numberLength > 2 && str[0] == '0' && (str[1] == 'b' || str[1] == 'B');
        const bool isOctal = numberLength >= 2 && str[0] == '0' && str[1] >= '0' && str[1] <= '7';
        const bool isDecimal = !(isBinary || isOctal || numeric->isHex());

        if (!numeric->isHex()) {
            /*
          Convert integer literal to hex representation.
          Replace
            0b100000
            32
            040
          With
            0x20

        */
            const QString replacement = QString::asprintf("0x%lX", value);
            auto op = new ConvertNumericLiteralOp(interface, start, start + numberLength, replacement);
            op->setDescription(Tr::tr("Convert to Hexadecimal"));
            op->setPriority(priority);
            result << op;
        }

        if (!isOctal) {
            /*
          Convert integer literal to octal representation.
          Replace
            0b100000
            32
            0x20
          With
            040
        */
            const QString replacement = QString::asprintf("0%lo", value);
            auto op = new ConvertNumericLiteralOp(interface, start, start + numberLength, replacement);
            op->setDescription(Tr::tr("Convert to Octal"));
            op->setPriority(priority);
            result << op;
        }

        if (!isDecimal) {
            /*
          Convert integer literal to decimal representation.
          Replace
            0b100000
            0x20
            040
           With
            32
        */
            const QString replacement = QString::asprintf("%lu", value);
            auto op = new ConvertNumericLiteralOp(interface, start, start + numberLength, replacement);
            op->setDescription(Tr::tr("Convert to Decimal"));
            op->setPriority(priority);
            result << op;
        }

        if (!isBinary) {
            /*
          Convert integer literal to binary representation.
          Replace
            32
            0x20
            040
          With
            0b100000
        */
            QString replacement = "0b";
            if (value == 0) {
                replacement.append('0');
            } else {
                std::bitset<std::numeric_limits<decltype (value)>::digits> b(value);
                static const QRegularExpression re("^[0]*");
                replacement.append(QString::fromStdString(b.to_string()).remove(re));
            }
            auto op = new ConvertNumericLiteralOp(interface, start, start + numberLength, replacement);
            op->setDescription(Tr::tr("Convert to Binary"));
            op->setPriority(priority);
            result << op;
        }
    }
};

} // namespace

void registerConvertNumericLiteralQuickfix()
{
    CppQuickFixFactory::registerFactory<ConvertNumericLiteral>();
}

} // namespace CppEditor::Internal