aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cppeditor/quickfixes/extractliteralasparameter.cpp
blob: a1f0760dfbc13ab73e18454cc134b8ab6a5e4e80 (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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// 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 "extractliteralasparameter.h"

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

#include <cplusplus/ASTPath.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>

#ifdef WITH_TESTS
#include "cppquickfix_test.h"
#include <QtTest>
#endif

using namespace CPlusPlus;
using namespace Utils;

namespace CppEditor::Internal {
namespace {

struct ReplaceLiteralsResult
{
    Token token;
    QString literalText;
};

template <class T>
class ReplaceLiterals : private ASTVisitor
{
public:
    ReplaceLiterals(const CppRefactoringFilePtr &file, ChangeSet *changes, T *literal)
        : ASTVisitor(file->cppDocument()->translationUnit()), m_file(file), m_changes(changes),
        m_literal(literal)
    {
        m_result.token = m_file->tokenAt(literal->firstToken());
        m_literalTokenText = m_result.token.spell();
        m_result.literalText = QLatin1String(m_literalTokenText);
        if (m_result.token.isCharLiteral()) {
            m_result.literalText.prepend(QLatin1Char('\''));
            m_result.literalText.append(QLatin1Char('\''));
            if (m_result.token.kind() == T_WIDE_CHAR_LITERAL)
                m_result.literalText.prepend(QLatin1Char('L'));
            else if (m_result.token.kind() == T_UTF16_CHAR_LITERAL)
                m_result.literalText.prepend(QLatin1Char('u'));
            else if (m_result.token.kind() == T_UTF32_CHAR_LITERAL)
                m_result.literalText.prepend(QLatin1Char('U'));
        } else if (m_result.token.isStringLiteral()) {
            m_result.literalText.prepend(QLatin1Char('"'));
            m_result.literalText.append(QLatin1Char('"'));
            if (m_result.token.kind() == T_WIDE_STRING_LITERAL)
                m_result.literalText.prepend(QLatin1Char('L'));
            else if (m_result.token.kind() == T_UTF16_STRING_LITERAL)
                m_result.literalText.prepend(QLatin1Char('u'));
            else if (m_result.token.kind() == T_UTF32_STRING_LITERAL)
                m_result.literalText.prepend(QLatin1Char('U'));
        }
    }

    ReplaceLiteralsResult apply(AST *ast)
    {
        ast->accept(this);
        return m_result;
    }

private:
    bool visit(T *ast) override
    {
        if (ast != m_literal
            && strcmp(m_file->tokenAt(ast->firstToken()).spell(), m_literalTokenText) != 0) {
            return true;
        }
        int start, end;
        m_file->startAndEndOf(ast->firstToken(), &start, &end);
        m_changes->replace(start, end, QLatin1String("newParameter"));
        return true;
    }

    const CppRefactoringFilePtr &m_file;
    ChangeSet *m_changes;
    T *m_literal;
    const char *m_literalTokenText;
    ReplaceLiteralsResult m_result;
};

class ExtractLiteralAsParameterOp : public CppQuickFixOperation
{
public:
    ExtractLiteralAsParameterOp(const CppQuickFixInterface &interface, int priority,
                                ExpressionAST *literal, FunctionDefinitionAST *function)
        : CppQuickFixOperation(interface, priority),
        m_literal(literal),
        m_functionDefinition(function)
    {
        setDescription(Tr::tr("Extract Constant as Function Parameter"));
    }

    struct FoundDeclaration
    {
        FunctionDeclaratorAST *ast = nullptr;
        CppRefactoringFilePtr file;
    };

    FoundDeclaration findDeclaration(const CppRefactoringChanges &refactoring,
                                     FunctionDefinitionAST *ast)
    {
        FoundDeclaration result;
        Function *func = ast->symbol;
        if (Class *matchingClass = isMemberFunction(context(), func)) {
            // Dealing with member functions
            const QualifiedNameId *qName = func->name()->asQualifiedNameId();
            for (Symbol *s = matchingClass->find(qName->identifier()); s; s = s->next()) {
                if (!s->name()
                    || !qName->identifier()->match(s->identifier())
                    || !s->type()->asFunctionType()
                    || !s->type().match(func->type())
                    || s->asFunction()) {
                    continue;
                }

                const FilePath declFilePath = matchingClass->filePath();
                result.file = refactoring.cppFile(declFilePath);
                ASTPath astPath(result.file->cppDocument());
                const QList<AST *> path = astPath(s->line(), s->column());
                SimpleDeclarationAST *simpleDecl = nullptr;
                for (AST *node : path) {
                    simpleDecl = node->asSimpleDeclaration();
                    if (simpleDecl) {
                        if (simpleDecl->symbols && !simpleDecl->symbols->next) {
                            result.ast = functionDeclarator(simpleDecl);
                            return result;
                        }
                    }
                }

                if (simpleDecl)
                    break;
            }
        } else if (Namespace *matchingNamespace = isNamespaceFunction(context(), func)) {
            // Dealing with free functions and inline member functions.
            bool isHeaderFile;
            FilePath declFilePath = correspondingHeaderOrSource(filePath(), &isHeaderFile);
            if (!declFilePath.exists())
                return FoundDeclaration();
            result.file = refactoring.cppFile(declFilePath);
            if (!result.file)
                return FoundDeclaration();
            const LookupContext lc(result.file->cppDocument(), snapshot());
            const QList<LookupItem> candidates = lc.lookup(func->name(), matchingNamespace);
            for (const LookupItem &candidate : candidates) {
                if (Symbol *s = candidate.declaration()) {
                    if (s->asDeclaration()) {
                        ASTPath astPath(result.file->cppDocument());
                        const QList<AST *> path = astPath(s->line(), s->column());
                        for (AST *node : path) {
                            SimpleDeclarationAST *simpleDecl = node->asSimpleDeclaration();
                            if (simpleDecl) {
                                result.ast = functionDeclarator(simpleDecl);
                                return result;
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    void perform() override
    {
        FunctionDeclaratorAST *functionDeclaratorOfDefinition
            = functionDeclarator(m_functionDefinition);
        const CppRefactoringChanges refactoring(snapshot());
        const CppRefactoringFilePtr currentFile = refactoring.cppFile(filePath());
        deduceTypeNameOfLiteral(currentFile->cppDocument());

        ChangeSet changes;
        if (NumericLiteralAST *concreteLiteral = m_literal->asNumericLiteral()) {
            m_literalInfo = ReplaceLiterals<NumericLiteralAST>(currentFile, &changes,
                                                               concreteLiteral)
                                .apply(m_functionDefinition->function_body);
        } else if (StringLiteralAST *concreteLiteral = m_literal->asStringLiteral()) {
            m_literalInfo = ReplaceLiterals<StringLiteralAST>(currentFile, &changes,
                                                              concreteLiteral)
                                .apply(m_functionDefinition->function_body);
        } else if (BoolLiteralAST *concreteLiteral = m_literal->asBoolLiteral()) {
            m_literalInfo = ReplaceLiterals<BoolLiteralAST>(currentFile, &changes,
                                                            concreteLiteral)
                                .apply(m_functionDefinition->function_body);
        }
        const FoundDeclaration functionDeclaration
            = findDeclaration(refactoring, m_functionDefinition);
        appendFunctionParameter(functionDeclaratorOfDefinition, currentFile, &changes,
                                !functionDeclaration.ast);
        if (functionDeclaration.ast) {
            if (currentFile->filePath() != functionDeclaration.file->filePath()) {
                ChangeSet declChanges;
                appendFunctionParameter(functionDeclaration.ast, functionDeclaration.file, &declChanges,
                                        true);
                functionDeclaration.file->setChangeSet(declChanges);
                functionDeclaration.file->apply();
            } else {
                appendFunctionParameter(functionDeclaration.ast, currentFile, &changes,
                                        true);
            }
        }
        currentFile->setChangeSet(changes);
        currentFile->apply();
        QTextCursor c = currentFile->cursor();
        c.setPosition(c.position() - parameterName().length());
        editor()->setTextCursor(c);
        editor()->renameSymbolUnderCursor();
    }

private:
    bool hasParameters(FunctionDeclaratorAST *ast) const
    {
        return ast->parameter_declaration_clause
               && ast->parameter_declaration_clause->parameter_declaration_list
               && ast->parameter_declaration_clause->parameter_declaration_list->value;
    }

    void deduceTypeNameOfLiteral(const Document::Ptr &document)
    {
        TypeOfExpression typeOfExpression;
        typeOfExpression.init(document, snapshot());
        Overview overview;
        Scope *scope = m_functionDefinition->symbol->enclosingScope();
        const QList<LookupItem> items = typeOfExpression(m_literal, document, scope);
        if (!items.isEmpty())
            m_typeName = overview.prettyType(items.first().type());
    }

    static QString parameterName() { return QLatin1String("newParameter"); }

    QString parameterDeclarationTextToInsert(FunctionDeclaratorAST *ast) const
    {
        QString str;
        if (hasParameters(ast))
            str = QLatin1String(", ");
        str += m_typeName;
        if (!m_typeName.endsWith(QLatin1Char('*')))
            str += QLatin1Char(' ');
        str += parameterName();
        return str;
    }

    FunctionDeclaratorAST *functionDeclarator(SimpleDeclarationAST *ast) const
    {
        for (DeclaratorListAST *decls = ast->declarator_list; decls; decls = decls->next) {
            FunctionDeclaratorAST * const functionDeclaratorAST = functionDeclarator(decls->value);
            if (functionDeclaratorAST)
                return functionDeclaratorAST;
        }
        return nullptr;
    }

    FunctionDeclaratorAST *functionDeclarator(DeclaratorAST *ast) const
    {
        for (PostfixDeclaratorListAST *pds = ast->postfix_declarator_list; pds; pds = pds->next) {
            FunctionDeclaratorAST *funcdecl = pds->value->asFunctionDeclarator();
            if (funcdecl)
                return funcdecl;
        }
        return nullptr;
    }

    FunctionDeclaratorAST *functionDeclarator(FunctionDefinitionAST *ast) const
    {
        return functionDeclarator(ast->declarator);
    }

    void appendFunctionParameter(FunctionDeclaratorAST *ast, const CppRefactoringFileConstPtr &file,
                                 ChangeSet *changes, bool addDefaultValue)
    {
        if (!ast)
            return;
        if (m_declarationInsertionString.isEmpty())
            m_declarationInsertionString = parameterDeclarationTextToInsert(ast);
        QString insertion = m_declarationInsertionString;
        if (addDefaultValue)
            insertion += QLatin1String(" = ") + m_literalInfo.literalText;
        changes->insert(file->startOf(ast->rparen_token), insertion);
    }

    ExpressionAST *m_literal;
    FunctionDefinitionAST *m_functionDefinition;
    QString m_typeName;
    QString m_declarationInsertionString;
    ReplaceLiteralsResult m_literalInfo;
};

/*!
  Extracts the selected constant and converts it to a parameter of the current function.
  Activates on numeric, bool, character, or string literal in the function body.
 */
class ExtractLiteralAsParameter : public CppQuickFixFactory
{
#ifdef WITH_TESTS
public:
    static QObject *createTest();
#endif

private:
    void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override
    {
        const QList<AST *> &path = interface.path();
        if (path.count() < 2)
            return;

        AST * const lastAst = path.last();
        ExpressionAST *literal;
        if (!((literal = lastAst->asNumericLiteral())
              || (literal = lastAst->asStringLiteral())
              || (literal = lastAst->asBoolLiteral()))) {
            return;
        }

        FunctionDefinitionAST *function;
        int i = path.count() - 2;
        while (!(function = path.at(i)->asFunctionDefinition())) {
            // Ignore literals in lambda expressions for now.
            if (path.at(i)->asLambdaExpression())
                return;
            if (--i < 0)
                return;
        }

        PostfixDeclaratorListAST * const declaratorList = function->declarator->postfix_declarator_list;
        if (!declaratorList)
            return;
        if (FunctionDeclaratorAST *declarator = declaratorList->value->asFunctionDeclarator()) {
            if (declarator->parameter_declaration_clause
                && declarator->parameter_declaration_clause->dot_dot_dot_token) {
                // Do not handle functions with ellipsis parameter.
                return;
            }
        }

        const int priority = path.size() - 1;
        result << new ExtractLiteralAsParameterOp(interface, priority, literal, function);
    }
};

#ifdef WITH_TESTS
using namespace Tests;

class ExtractLiteralAsParameterTest : public QObject
{
    Q_OBJECT

private slots:
    void testTypeDeduction_data()
    {
        QTest::addColumn<QByteArray>("typeString");
        QTest::addColumn<QByteArray>("literal");
        QTest::newRow("int")
            << QByteArray("int ") << QByteArray("156");
        QTest::newRow("unsigned int")
            << QByteArray("unsigned int ") << QByteArray("156u");
        QTest::newRow("long")
            << QByteArray("long ") << QByteArray("156l");
        QTest::newRow("unsigned long")
            << QByteArray("unsigned long ") << QByteArray("156ul");
        QTest::newRow("long long")
            << QByteArray("long long ") << QByteArray("156ll");
        QTest::newRow("unsigned long long")
            << QByteArray("unsigned long long ") << QByteArray("156ull");
        QTest::newRow("float")
            << QByteArray("float ") << QByteArray("3.14159f");
        QTest::newRow("double")
            << QByteArray("double ") << QByteArray("3.14159");
        QTest::newRow("long double")
            << QByteArray("long double ") << QByteArray("3.14159L");
        QTest::newRow("bool")
            << QByteArray("bool ") << QByteArray("true");
        QTest::newRow("bool")
            << QByteArray("bool ") << QByteArray("false");
        QTest::newRow("char")
            << QByteArray("char ") << QByteArray("'X'");
        QTest::newRow("wchar_t")
            << QByteArray("wchar_t ") << QByteArray("L'X'");
        QTest::newRow("char16_t")
            << QByteArray("char16_t ") << QByteArray("u'X'");
        QTest::newRow("char32_t")
            << QByteArray("char32_t ") << QByteArray("U'X'");
        QTest::newRow("const char *")
            << QByteArray("const char *") << QByteArray("\"narf\"");
        QTest::newRow("const wchar_t *")
            << QByteArray("const wchar_t *") << QByteArray("L\"narf\"");
        QTest::newRow("const char16_t *")
            << QByteArray("const char16_t *") << QByteArray("u\"narf\"");
        QTest::newRow("const char32_t *")
            << QByteArray("const char32_t *") << QByteArray("U\"narf\"");
    }

    void testTypeDeduction()
    {
        QFETCH(QByteArray, typeString);
        QFETCH(QByteArray, literal);
        const QByteArray original = QByteArray("void foo() {return @") + literal + QByteArray(";}\n");
        const QByteArray expected = QByteArray("void foo(") + typeString + QByteArray("newParameter = ")
                                    + literal + QByteArray(") {return newParameter;}\n");

        if (literal == "3.14159") {
            qWarning("Literal 3.14159 is wrongly reported as int. Skipping.");
            return;
        } else if (literal == "3.14159L") {
            qWarning("Literal 3.14159L is wrongly reported as long. Skipping.");
            return;
        }

        ExtractLiteralAsParameter factory;
        QuickFixOperationTest(singleDocument(original, expected), &factory);
    }

    void testFreeFunctionSeparateFiles()
    {
        QList<TestDocumentPtr> testDocuments;
        QByteArray original;
        QByteArray expected;

        // Header File
        original =
            "void foo(const char *a, long b = 1);\n";
        expected =
            "void foo(const char *a, long b = 1, int newParameter = 156);\n";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        // Source File
        original =
            "void foo(const char *a, long b)\n"
            "{return 1@56 + 123 + 156;}\n";
        expected =
            "void foo(const char *a, long b, int newParameter)\n"
            "{return newParameter + 123 + newParameter;}\n";
        testDocuments << CppTestDocument::create("file.cpp", original, expected);

        ExtractLiteralAsParameter factory;
        QuickFixOperationTest(testDocuments, &factory);
    }

    void testMemberFunctionSeparateFiles()
    {
        QList<TestDocumentPtr> testDocuments;
        QByteArray original;
        QByteArray expected;

        // Header File
        original =
            "class Narf {\n"
            "public:\n"
            "    int zort();\n"
            "};\n";
        expected =
            "class Narf {\n"
            "public:\n"
            "    int zort(int newParameter = 155);\n"
            "};\n";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        // Source File
        original =
            "#include \"file.h\"\n\n"
            "int Narf::zort()\n"
            "{ return 15@5 + 1; }\n";
        expected =
            "#include \"file.h\"\n\n"
            "int Narf::zort(int newParameter)\n"
            "{ return newParameter + 1; }\n";
        testDocuments << CppTestDocument::create("file.cpp", original, expected);

        ExtractLiteralAsParameter factory;
        QuickFixOperationTest(testDocuments, &factory);
    }

    void testNotTriggeringForInvalidCode()
    {
        QList<TestDocumentPtr> testDocuments;
        QByteArray original;
        original =
            "T(\"test\")\n"
            "{\n"
            "    const int i = @14;\n"
            "}\n";
        testDocuments << CppTestDocument::create("file.cpp", original, "");

        ExtractLiteralAsParameter factory;
        QuickFixOperationTest(testDocuments, &factory);
    }

    void test_data()
    {
        QTest::addColumn<QByteArray>("original");
        QTest::addColumn<QByteArray>("expected");

        QTest::newRow("ExtractLiteralAsParameter_freeFunction")
            << QByteArray(
                   "void foo(const char *a, long b = 1)\n"
                   "{return 1@56 + 123 + 156;}\n")
            << QByteArray(
                   "void foo(const char *a, long b = 1, int newParameter = 156)\n"
                   "{return newParameter + 123 + newParameter;}\n");
        QTest::newRow("ExtractLiteralAsParameter_memberFunction")
            << QByteArray(
                   "class Narf {\n"
                   "public:\n"
                   "    int zort();\n"
                   "};\n\n"
                   "int Narf::zort()\n"
                   "{ return 15@5 + 1; }\n")
            << QByteArray(
                   "class Narf {\n"
                   "public:\n"
                   "    int zort(int newParameter = 155);\n"
                   "};\n\n"
                   "int Narf::zort(int newParameter)\n"
                   "{ return newParameter + 1; }\n");
        QTest::newRow("ExtractLiteralAsParameter_memberFunctionInline")
            << QByteArray(
                   "class Narf {\n"
                   "public:\n"
                   "    int zort()\n"
                   "    { return 15@5 + 1; }\n"
                   "};\n")
            << QByteArray(
                   "class Narf {\n"
                   "public:\n"
                   "    int zort(int newParameter = 155)\n"
                   "    { return newParameter + 1; }\n"
                   "};\n");
    }

    void test()
    {
        QFETCH(QByteArray, original);
        QFETCH(QByteArray, expected);
        ExtractLiteralAsParameter factory;
        QuickFixOperationTest(singleDocument(original, expected), &factory);
    }

};

QObject *ExtractLiteralAsParameter::createTest() { return new ExtractLiteralAsParameterTest; }

#endif // WITH_TESTS
} // namespace

void registerExtractLiteralAsParameterQuickfix()
{
    CppQuickFixFactory::registerFactory<ExtractLiteralAsParameter>();
}

} // namespace CppEditor::Internal

#ifdef WITH_TESTS
#include <extractliteralasparameter.moc>
#endif