cppquickfixes.cpp 58.1 KB
Newer Older
1
2
3
4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
8
9
10
11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
30
31
32
**
**************************************************************************/

33
#include "cppcompleteswitch.h"
34
35
#include "cppeditor.h"
#include "cppquickfix.h"
36
#include "cppinsertdecldef.h"
37
#include "cppinsertqtpropertymembers.h"
Leandro Melo's avatar
Leandro Melo committed
38
39
#include "cppquickfixassistant.h"
#include "cppcompleteswitch.h"
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

#include <ASTVisitor.h>
#include <AST.h>
#include <ASTMatcher.h>
#include <ASTPatternBuilder.h>
#include <CoreTypes.h>
#include <Literals.h>
#include <Name.h>
#include <Names.h>
#include <Symbol.h>
#include <Symbols.h>
#include <Token.h>
#include <TranslationUnit.h>
#include <Type.h>

#include <cplusplus/DependencyTable.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cplusplus/CppRewriter.h>
#include <cpptools/cpptoolsconstants.h>
60
#include <cpptools/cpprefactoringchanges.h>
61
#include <cpptools/insertionpointlocator.h>
62
63
#include <extensionsystem/iplugin.h>

Friedemann Kleint's avatar
Friedemann Kleint committed
64
#include <QtCore/QFileInfo>
65
66
67
68
69
70
#include <QtGui/QApplication>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>

using namespace CppEditor;
using namespace CppEditor::Internal;
71
using namespace CppTools;
72
73
74
75
76
77
78
79
80
81
82
using namespace TextEditor;
using namespace CPlusPlus;
using namespace Utils;

namespace {

/*
    Rewrite
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
83
84

    Activates on: <= < > >= == !=
85
86
87
88
*/
class UseInverseOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
89
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
90
91
    {
        QList<CppQuickFixOperation::Ptr> result;
Leandro Melo's avatar
Leandro Melo committed
92
        const CppRefactoringFile &file = interface->currentFile();
93

Leandro Melo's avatar
Leandro Melo committed
94
        const QList<AST *> &path = interface->path();
95
96
97
98
        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return result;
Leandro Melo's avatar
Leandro Melo committed
99
        if (! interface->isCursorOn(binary->binary_op_token))
100
101
102
            return result;

        Kind invertToken;
103
        switch (file.tokenAt(binary->binary_op_token).kind()) {
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        case T_LESS_EQUAL:
            invertToken = T_GREATER;
            break;
        case T_LESS:
            invertToken = T_GREATER_EQUAL;
            break;
        case T_GREATER:
            invertToken = T_LESS_EQUAL;
            break;
        case T_GREATER_EQUAL:
            invertToken = T_LESS;
            break;
        case T_EQUAL_EQUAL:
            invertToken = T_EXCLAIM_EQUAL;
            break;
        case T_EXCLAIM_EQUAL:
            invertToken = T_EQUAL_EQUAL;
            break;
        default:
            return result;
        }

Leandro Melo's avatar
Leandro Melo committed
126
        result.append(CppQuickFixOperation::Ptr(new Operation(interface, index, binary, invertToken)));
127
128
129
130
131
132
133
134
135
136
137
138
139
        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
        BinaryExpressionAST *binary;
        NestedExpressionAST *nested;
        UnaryExpressionAST *negation;

        QString replacement;

    public:
Leandro Melo's avatar
Leandro Melo committed
140
141
142
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
            int priority, BinaryExpressionAST *binary, Kind invertToken)
            : CppQuickFixOperation(interface, priority)
143
            , binary(binary), nested(0), negation(0)
144
145
146
147
148
149
150
        {
            Token tok;
            tok.f.kind = invertToken;
            replacement = QLatin1String(tok.spell());

            // check for enclosing nested expression
            if (priority - 1 >= 0)
Leandro Melo's avatar
Leandro Melo committed
151
                nested = interface->path()[priority - 1]->asNestedExpression();
152
153
154

            // check for ! before parentheses
            if (nested && priority - 2 >= 0) {
Leandro Melo's avatar
Leandro Melo committed
155
156
                negation = interface->path()[priority - 2]->asUnaryExpression();
                if (negation && ! interface->currentFile().tokenAt(negation->unary_op_token).is(T_EXCLAIM))
157
158
159
160
161
162
163
164
165
                    negation = 0;
            }
        }

        virtual QString description() const
        {
            return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
        }

166
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
167
168
169
170
        {
            ChangeSet changes;
            if (negation) {
                // can't remove parentheses since that might break precedence
171
                changes.remove(currentFile->range(negation->unary_op_token));
172
            } else if (nested) {
173
                changes.insert(currentFile->startOf(nested), "!");
174
            } else {
175
176
                changes.insert(currentFile->startOf(binary), "!(");
                changes.insert(currentFile->endOf(binary), ")");
177
            }
178
            changes.replace(currentFile->range(binary->binary_op_token), replacement);
179
            currentFile->change(changes);
180
181
182
183
184
185
186
187
188
189
        }
    };
};

/*
    Rewrite
    a op b

    As
    b flipop a
190
191

    Activates on: <= < > >= == != && ||
192
193
194
195
*/
class FlipBinaryOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
196
    virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
197
198
    {
        QList<QuickFixOperation::Ptr> result;
Leandro Melo's avatar
Leandro Melo committed
199
200
        const QList<AST *> &path = interface->path();
        const CppRefactoringFile &file = interface->currentFile();
201
202
203
204
205

        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return result;
Leandro Melo's avatar
Leandro Melo committed
206
        if (! interface->isCursorOn(binary->binary_op_token))
207
208
209
            return result;

        Kind flipToken;
210
        switch (file.tokenAt(binary->binary_op_token).kind()) {
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
        case T_LESS_EQUAL:
            flipToken = T_GREATER_EQUAL;
            break;
        case T_LESS:
            flipToken = T_GREATER;
            break;
        case T_GREATER:
            flipToken = T_LESS;
            break;
        case T_GREATER_EQUAL:
            flipToken = T_LESS_EQUAL;
            break;
        case T_EQUAL_EQUAL:
        case T_EXCLAIM_EQUAL:
        case T_AMPER_AMPER:
        case T_PIPE_PIPE:
            flipToken = T_EOF_SYMBOL;
            break;
        default:
            return result;
        }

        QString replacement;
        if (flipToken != T_EOF_SYMBOL) {
            Token tok;
            tok.f.kind = flipToken;
            replacement = QLatin1String(tok.spell());
        }

Leandro Melo's avatar
Leandro Melo committed
240
        result.append(QuickFixOperation::Ptr(new Operation(interface, index, binary, replacement)));
241
242
243
244
245
246
247
        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
248
249
250
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
                  int priority, BinaryExpressionAST *binary, QString replacement)
            : CppQuickFixOperation(interface)
251
252
253
254
255
256
257
258
259
260
261
262
263
264
            , binary(binary)
            , replacement(replacement)
        {
            setPriority(priority);
        }

        virtual QString description() const
        {
            if (replacement.isEmpty())
                return QApplication::translate("CppTools::QuickFix", "Swap Operands");
            else
                return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
        }

265
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
266
267
268
        {
            ChangeSet changes;

269
            changes.flip(currentFile->range(binary->left_expression), currentFile->range(binary->right_expression));
270
            if (! replacement.isEmpty())
271
                changes.replace(currentFile->range(binary->binary_op_token), replacement);
272

273
            currentFile->change(changes);
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        }

    private:
        BinaryExpressionAST *binary;
        QString replacement;
    };
};

/*
    Rewrite
    !a && !b

    As
    !(a || b)
288
289

    Activates on: &&
290
291
292
293
*/
class RewriteLogicalAndOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
294
    virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
295
296
297
    {
        QList<QuickFixOperation::Ptr> result;
        BinaryExpressionAST *expression = 0;
Leandro Melo's avatar
Leandro Melo committed
298
299
        const QList<AST *> &path = interface->path();
        const CppRefactoringFile &file = interface->currentFile();
300
301
302
303
304
305
306
307
308
309
310

        int index = path.size() - 1;
        for (; index != -1; --index) {
            expression = path.at(index)->asBinaryExpression();
            if (expression)
                break;
        }

        if (! expression)
            return result;

Leandro Melo's avatar
Leandro Melo committed
311
        if (! interface->isCursorOn(expression->binary_op_token))
312
313
            return result;

Leandro Melo's avatar
Leandro Melo committed
314
        QSharedPointer<Operation> op(new Operation(interface));
315
316

        if (expression->match(op->pattern, &matcher) &&
317
318
319
                file.tokenAt(op->pattern->binary_op_token).is(T_AMPER_AMPER) &&
                file.tokenAt(op->left->unary_op_token).is(T_EXCLAIM) &&
                file.tokenAt(op->right->unary_op_token).is(T_EXCLAIM)) {
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
            op->setDescription(QApplication::translate("CppTools::QuickFix", "Rewrite Condition Using ||"));
            op->setPriority(index);
            result.append(op);
        }

        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        QSharedPointer<ASTPatternBuilder> mk;
        UnaryExpressionAST *left;
        UnaryExpressionAST *right;
        BinaryExpressionAST *pattern;

Leandro Melo's avatar
Leandro Melo committed
337
338
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
339
340
341
342
343
344
345
            , mk(new ASTPatternBuilder)
        {
            left = mk->UnaryExpression();
            right = mk->UnaryExpression();
            pattern = mk->BinaryExpression(left, right);
        }

346
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
347
348
        {
            ChangeSet changes;
349
350
351
352
353
            changes.replace(currentFile->range(pattern->binary_op_token), QLatin1String("||"));
            changes.remove(currentFile->range(left->unary_op_token));
            changes.remove(currentFile->range(right->unary_op_token));
            const int start = currentFile->startOf(pattern);
            const int end = currentFile->endOf(pattern);
354
355
356
            changes.insert(start, QLatin1String("!("));
            changes.insert(end, QLatin1String(")"));

357
            currentFile->change(changes);
358
            currentFile->indent(currentFile->range(pattern));
359
360
361
362
363
364
365
        }
    };

private:
    ASTMatcher matcher;
};

366
367
368
369
370
371
372
/*
    Rewrite
    int *a, b;

    As
    int *a;
    int b;
373
374

    Activates on: the type or the variable names.
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
class SplitSimpleDeclarationOp: public CppQuickFixFactory
{
    static bool checkDeclaration(SimpleDeclarationAST *declaration)
    {
        if (! declaration->semicolon_token)
            return false;

        if (! declaration->decl_specifier_list)
            return false;

        for (SpecifierListAST *it = declaration->decl_specifier_list; it; it = it->next) {
            SpecifierAST *specifier = it->value;

            if (specifier->asEnumSpecifier() != 0)
                return false;

            else if (specifier->asClassSpecifier() != 0)
                return false;
        }

        if (! declaration->declarator_list)
            return false;

        else if (! declaration->declarator_list->next)
            return false;

        return true;
    }

public:
Leandro Melo's avatar
Leandro Melo committed
406
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
407
408
409
    {
        QList<CppQuickFixOperation::Ptr> result;
        CoreDeclaratorAST *core_declarator = 0;
Leandro Melo's avatar
Leandro Melo committed
410
411
        const QList<AST *> &path = interface->path();
        const CppRefactoringFile &file = interface->currentFile();
412
413
414
415
416
417
418
419
420
421
422

        for (int index = path.size() - 1; index != -1; --index) {
            AST *node = path.at(index);

            if (CoreDeclaratorAST *coreDecl = node->asCoreDeclarator())
                core_declarator = coreDecl;

            else if (SimpleDeclarationAST *simpleDecl = node->asSimpleDeclaration()) {
                if (checkDeclaration(simpleDecl)) {
                    SimpleDeclarationAST *declaration = simpleDecl;

423
                    const int cursorPosition = file.cursor().selectionStart();
424

425
426
                    const int startOfDeclSpecifier = file.startOf(declaration->decl_specifier_list->firstToken());
                    const int endOfDeclSpecifier = file.endOf(declaration->decl_specifier_list->lastToken() - 1);
427
428
429

                    if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier) {
                        // the AST node under cursor is a specifier.
Leandro Melo's avatar
Leandro Melo committed
430
                        return singleResult(new Operation(interface, index, declaration));
431
432
                    }

Leandro Melo's avatar
Leandro Melo committed
433
                    if (core_declarator && interface->isCursorOn(core_declarator)) {
434
                        // got a core-declarator under the text cursor.
Leandro Melo's avatar
Leandro Melo committed
435
                        return singleResult(new Operation(interface, index, declaration));
436
437
438
439
440
441
442
443
444
445
446
447
448
449
                    }
                }

                break;
            }
        }

        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
450
451
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, SimpleDeclarationAST *decl)
            : CppQuickFixOperation(interface, priority)
452
453
454
455
456
457
            , declaration(decl)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split Declaration"));
        }

458
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
459
460
461
462
        {
            ChangeSet changes;

            SpecifierListAST *specifiers = declaration->decl_specifier_list;
463
464
465
            int declSpecifiersStart = currentFile->startOf(specifiers->firstToken());
            int declSpecifiersEnd = currentFile->endOf(specifiers->lastToken() - 1);
            int insertPos = currentFile->endOf(declaration->semicolon_token);
466
467
468
469
470
471
472
473
474

            DeclaratorAST *prevDeclarator = declaration->declarator_list->value;

            for (DeclaratorListAST *it = declaration->declarator_list->next; it; it = it->next) {
                DeclaratorAST *declarator = it->value;

                changes.insert(insertPos, QLatin1String("\n"));
                changes.copy(declSpecifiersStart, declSpecifiersEnd, insertPos);
                changes.insert(insertPos, QLatin1String(" "));
475
                changes.move(currentFile->range(declarator), insertPos);
476
477
                changes.insert(insertPos, QLatin1String(";"));

478
479
                const int prevDeclEnd = currentFile->endOf(prevDeclarator);
                changes.remove(prevDeclEnd, currentFile->startOf(declarator));
480
481
482
483

                prevDeclarator = declarator;
            }

484
            currentFile->change(changes);
485
            currentFile->indent(currentFile->range(declaration));
486
487
488
489
490
491
492
493
494
        }

    private:
        SimpleDeclarationAST *declaration;
    };
};

/*
    Add curly braces to a if statement that doesn't already contain a
495
496
497
498
499
500
501
502
    compound statement. I.e.

    if (a)
        b;
    becomes
    if (a) {
        b;
    }
503
504

    Activates on: the if
505
506
507
508
*/
class AddBracesToIfOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
509
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
510
    {
Leandro Melo's avatar
Leandro Melo committed
511
        const QList<AST *> &path = interface->path();
512
513
514
515

        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
Leandro Melo's avatar
Leandro Melo committed
516
        if (ifStatement && interface->isCursorOn(ifStatement->if_token) && ifStatement->statement
517
            && ! ifStatement->statement->asCompoundStatement()) {
Leandro Melo's avatar
Leandro Melo committed
518
            return singleResult(new Operation(interface, index, ifStatement->statement));
519
520
521
522
523
524
525
        }

        // or if we're on the statement contained in the if
        // ### This may not be such a good idea, consider nested ifs...
        for (; index != -1; --index) {
            IfStatementAST *ifStatement = path.at(index)->asIfStatement();
            if (ifStatement && ifStatement->statement
Leandro Melo's avatar
Leandro Melo committed
526
                && interface->isCursorOn(ifStatement->statement)
527
                && ! ifStatement->statement->asCompoundStatement()) {
Leandro Melo's avatar
Leandro Melo committed
528
                return singleResult(new Operation(interface, index, ifStatement->statement));
529
530
531
532
533
534
535
536
537
538
539
540
541
            }
        }

        // ### This could very well be extended to the else branch
        // and other nodes entirely.

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
542
543
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, StatementAST *statement)
            : CppQuickFixOperation(interface, priority)
544
545
546
547
548
549
            , _statement(statement)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Add Curly Braces"));
        }

550
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
551
552
553
        {
            ChangeSet changes;

554
            const int start = currentFile->endOf(_statement->firstToken() - 1);
555
556
            changes.insert(start, QLatin1String(" {"));

557
            const int end = currentFile->endOf(_statement->lastToken() - 1);
558
559
            changes.insert(end, "\n}");

560
            currentFile->change(changes);
561
            currentFile->indent(Utils::ChangeSet::Range(start, end));
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        }

    private:
        StatementAST *_statement;
    };
};

/*
    Replace
    if (Type name = foo()) {...}

    With
    Type name = foo;
    if (name) {...}
576
577

    Activates on: the name of the introduced variable
578
579
580
581
*/
class MoveDeclarationOutOfIfOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
582
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
583
    {
Leandro Melo's avatar
Leandro Melo committed
584
585
        const QList<AST *> &path = interface->path();
        QSharedPointer<Operation> op(new Operation(interface));
586
587
588
589
590
591
592
593
594
595

        int index = path.size() - 1;
        for (; index != -1; --index) {
            if (IfStatementAST *statement = path.at(index)->asIfStatement()) {
                if (statement->match(op->pattern, &op->matcher) && op->condition->declarator) {
                    DeclaratorAST *declarator = op->condition->declarator;
                    op->core = declarator->core_declarator;
                    if (! op->core)
                        return noResult();

Leandro Melo's avatar
Leandro Melo committed
596
                    if (interface->isCursorOn(op->core)) {
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
                        QList<CppQuickFixOperation::Ptr> result;
                        op->setPriority(index);
                        result.append(op);
                        return result;
                    }
                }
            }
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
613
614
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
615
616
617
618
619
620
621
622
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

            condition = mk.Condition();
            pattern = mk.IfStatement(condition);
        }

623
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
624
625
626
        {
            ChangeSet changes;

627
            changes.copy(currentFile->range(core), currentFile->startOf(condition));
628

629
630
            int insertPos = currentFile->startOf(pattern);
            changes.move(currentFile->range(condition), insertPos);
631
632
            changes.insert(insertPos, QLatin1String(";\n"));

633
            currentFile->change(changes);
634
            currentFile->indent(currentFile->range(pattern));
635
636
637
638
        }

        ASTMatcher matcher;
        ASTPatternBuilder mk;
639
        CPPEditorWidget *editor;
640
641
642
643
644
645
646
647
648
649
650
651
652
        ConditionAST *condition;
        IfStatementAST *pattern;
        CoreDeclaratorAST *core;
    };
};

/*
    Replace
    while (Type name = foo()) {...}

    With
    Type name;
    while ((name = foo()) != 0) {...}
653
654

    Activates on: the name of the introduced variable
655
656
657
658
*/
class MoveDeclarationOutOfWhileOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
659
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
660
    {
Leandro Melo's avatar
Leandro Melo committed
661
662
        const QList<AST *> &path = interface->path();
        QSharedPointer<Operation> op(new Operation(interface));
663
664
665
666
667
668
669
670
671
672
673

        int index = path.size() - 1;
        for (; index != -1; --index) {
            if (WhileStatementAST *statement = path.at(index)->asWhileStatement()) {
                if (statement->match(op->pattern, &op->matcher) && op->condition->declarator) {
                    DeclaratorAST *declarator = op->condition->declarator;
                    op->core = declarator->core_declarator;

                    if (! op->core)
                        return noResult();

674
                    else if (! declarator->equal_token)
675
676
677
678
679
                        return noResult();

                    else if (! declarator->initializer)
                        return noResult();

Leandro Melo's avatar
Leandro Melo committed
680
                    if (interface->isCursorOn(op->core)) {
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
                        QList<CppQuickFixOperation::Ptr> result;
                        op->setPriority(index);
                        result.append(op);
                        return result;
                    }
                }
            }
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
697
698
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
699
700
701
702
703
704
705
706
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

            condition = mk.Condition();
            pattern = mk.WhileStatement(condition);
        }

707
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
708
709
710
        {
            ChangeSet changes;

711
712
            changes.insert(currentFile->startOf(condition), QLatin1String("("));
            changes.insert(currentFile->endOf(condition), QLatin1String(") != 0"));
713

714
715
716
717
            int insertPos = currentFile->startOf(pattern);
            const int conditionStart = currentFile->startOf(condition);
            changes.move(conditionStart, currentFile->startOf(core), insertPos);
            changes.copy(currentFile->range(core), insertPos);
718
719
            changes.insert(insertPos, QLatin1String(";\n"));

720
            currentFile->change(changes);
721
            currentFile->indent(currentFile->range(pattern));
722
723
724
725
        }

        ASTMatcher matcher;
        ASTPatternBuilder mk;
726
        CPPEditorWidget *editor;
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
        ConditionAST *condition;
        WhileStatementAST *pattern;
        CoreDeclaratorAST *core;
    };
};

/*
  Replace
     if (something && something_else) {
     }

  with
     if (something) {
        if (something_else) {
        }
     }

  and
    if (something || something_else)
      x;

  with
    if (something)
      x;
    else if (something_else)
      x;
753
754

    Activates on: && or ||
755
756
757
758
*/
class SplitIfStatementOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
759
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
760
761
    {
        IfStatementAST *pattern = 0;
Leandro Melo's avatar
Leandro Melo committed
762
        const QList<AST *> &path = interface->path();
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782

        int index = path.size() - 1;
        for (; index != -1; --index) {
            AST *node = path.at(index);
            if (IfStatementAST *stmt = node->asIfStatement()) {
                pattern = stmt;
                break;
            }
        }

        if (! pattern || ! pattern->statement)
            return noResult();

        unsigned splitKind = 0;
        for (++index; index < path.size(); ++index) {
            AST *node = path.at(index);
            BinaryExpressionAST *condition = node->asBinaryExpression();
            if (! condition)
                return noResult();

Leandro Melo's avatar
Leandro Melo committed
783
            Token binaryToken = interface->currentFile().tokenAt(condition->binary_op_token);
784
785
786
787
788
789
790
791
792
793
794
795
796

            // only accept a chain of ||s or &&s - no mixing
            if (! splitKind) {
                splitKind = binaryToken.kind();
                if (splitKind != T_AMPER_AMPER && splitKind != T_PIPE_PIPE)
                    return noResult();
                // we can't reliably split &&s in ifs with an else branch
                if (splitKind == T_AMPER_AMPER && pattern->else_statement)
                    return noResult();
            } else if (splitKind != binaryToken.kind()) {
                return noResult();
            }

Leandro Melo's avatar
Leandro Melo committed
797
798
            if (interface->isCursorOn(condition->binary_op_token))
                return singleResult(new Operation(interface, index, pattern, condition));
799
800
801
802
803
804
805
806
807
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
808
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority,
809
                  IfStatementAST *pattern, BinaryExpressionAST *condition)
Leandro Melo's avatar
Leandro Melo committed
810
            : CppQuickFixOperation(interface, priority)
811
812
813
814
815
816
817
            , pattern(pattern)
            , condition(condition)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split if Statement"));
        }

818
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
819
        {
820
            const Token binaryToken = currentFile->tokenAt(condition->binary_op_token);
821
822

            if (binaryToken.is(T_AMPER_AMPER))
823
                splitAndCondition(currentFile);
824
            else
825
                splitOrCondition(currentFile);
826
827
        }

828
        void splitAndCondition(CppRefactoringFile *currentFile)
829
830
831
        {
            ChangeSet changes;

832
            int startPos = currentFile->startOf(pattern);
833
            changes.insert(startPos, QLatin1String("if ("));
834
            changes.move(currentFile->range(condition->left_expression), startPos);
835
836
            changes.insert(startPos, QLatin1String(") {\n"));

837
838
839
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
            changes.insert(currentFile->endOf(pattern), QLatin1String("\n}"));
840

841
            currentFile->change(changes);
842
            currentFile->indent(currentFile->range(pattern));
843
844
        }

845
        void splitOrCondition(CppRefactoringFile *currentFile)
846
847
848
849
850
851
        {
            ChangeSet changes;

            StatementAST *ifTrueStatement = pattern->statement;
            CompoundStatementAST *compoundStatement = ifTrueStatement->asCompoundStatement();

852
            int insertPos = currentFile->endOf(ifTrueStatement);
853
854
855
856
857
858
            if (compoundStatement)
                changes.insert(insertPos, QLatin1String(" "));
            else
                changes.insert(insertPos, QLatin1String("\n"));
            changes.insert(insertPos, QLatin1String("else if ("));

859
860
            const int rExprStart = currentFile->startOf(condition->right_expression);
            changes.move(rExprStart, currentFile->startOf(pattern->rparen_token), insertPos);
861
862
            changes.insert(insertPos, QLatin1String(")"));

863
864
            const int rParenEnd = currentFile->endOf(pattern->rparen_token);
            changes.copy(rParenEnd, currentFile->endOf(pattern->statement), insertPos);
865

866
867
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
868

869
            currentFile->change(changes);
870
            currentFile->indent(currentFile->range(pattern));
871
872
873
874
875
876
877
878
879
880
        }

    private:
        IfStatementAST *pattern;
        BinaryExpressionAST *condition;
    };
};

/*
  Replace
881
    "abcd" -> QLatin1String("abcd")
882
    @"abcd" -> QLatin1String("abcd")
883
884
885
886
    'a' -> QLatin1Char('a')
  Except if they are already enclosed in
    QLatin1Char, QT_TRANSLATE_NOOP, tr,
    trUtf8, QLatin1Literal, QLatin1String
887
888

    Activates on: the string literal
889
890
891
892
893
894
*/
class WrapStringLiteral: public CppQuickFixFactory
{
public:
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

Leandro Melo's avatar
Leandro Melo committed
895
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
896
897
898
    {
        ExpressionAST *literal = 0;
        Type type = TypeNone;
Leandro Melo's avatar
Leandro Melo committed
899
900
        const QList<AST *> &path = interface->path();
        const CppRefactoringFile &file = interface->currentFile();
901
902
903
904
905
906
907
908

        if (path.isEmpty())
            return noResult(); // nothing to do

        literal = path.last()->asStringLiteral();

        if (! literal) {
            literal = path.last()->asNumericLiteral();
909
            if (!literal || !file.tokenAt(literal->asNumericLiteral()->literal_token).is(T_CHAR_LITERAL))
910
911
912
913
914
915
916
917
918
919
                return noResult();
            else
                type = TypeChar;
        } else {
            type = TypeString;
        }

        if (path.size() > 1) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
Roberto Raggi's avatar
Roberto Raggi committed
920
921
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
922
                            const QByteArray id(file.tokenAt(functionName->identifier_token).identifier->chars());
Roberto Raggi's avatar
Roberto Raggi committed
923
924
925
926
927
928

                            if (id == "QT_TRANSLATE_NOOP" || id == "tr" || id == "trUtf8"
                                    || (type == TypeString && (id == "QLatin1String" || id == "QLatin1Literal"))
                                    || (type == TypeChar && id == "QLatin1Char"))
                                return noResult(); // skip it
                        }
929
930
931
932
933
934
                    }
                }
            }
        }

        if (type == TypeString) {
935
            if (file.charAt(file.startOf(literal)) == QLatin1Char('@'))
936
937
                type = TypeObjCString;
        }
Leandro Melo's avatar
Leandro Melo committed
938
        return singleResult(new Operation(interface,
939
940
941
942
943
944
945
946
947
                                          path.size() - 1, // very high priority
                                          type,
                                          literal));
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
948
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, Type type,
949
                  ExpressionAST *literal)
Leandro Melo's avatar
Leandro Melo committed
950
            : CppQuickFixOperation(interface, priority)
951
952
953
954
955
956
957
958
959
960
961
            , type(type)
            , literal(literal)
        {
            if (type == TypeChar)
                setDescription(QApplication::translate("CppTools::QuickFix",
                                                       "Enclose in QLatin1Char(...)"));
            else
                setDescription(QApplication::translate("CppTools::QuickFix",
                                                       "Enclose in QLatin1String(...)"));
        }

962
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
963
964
965
        {
            ChangeSet changes;

966
            const int startPos = currentFile->startOf(literal);
967
968
969
970
971
972
973
974
            QLatin1String replacement = (type == TypeChar ? QLatin1String("QLatin1Char(")
                                                          : QLatin1String("QLatin1String("));

            if (type == TypeObjCString)
                changes.replace(startPos, startPos + 1, replacement);
            else
                changes.insert(startPos, replacement);

975
            changes.insert(currentFile->endOf(literal), ")");
976

977
            currentFile->change(changes);
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
        }

    private:
        Type type;
        ExpressionAST *literal;
    };
};

/*
  Replace
    "abcd"
  With
    tr("abcd") or
    QCoreApplication::translate("CONTEXT", "abcd") or
    QT_TRANSLATE_NOOP("GLOBAL", "abcd")
993
  depending on what is available.
994
995

    Activates on: the string literal
996
997
998
999
1000
1001
*/
class TranslateStringLiteral: public CppQuickFixFactory
{
public:
    enum TranslationOption { unknown, useTr, useQCoreApplicationTranslate, useMacro };

Leandro Melo's avatar
Leandro Melo committed
1002
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
1003
    {
Leandro Melo's avatar
Leandro Melo committed
1004
        const QList<AST *> &path = interface->path();
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
        // Initialize
        ExpressionAST *literal = 0;
        QString trContext;

        if (path.isEmpty())
            return noResult();

        literal = path.last()->asStringLiteral();
        if (!literal)
            return noResult(); // No string, nothing to do

        // Do we already have a translation markup?
        if (path.size() >= 2) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
Roberto Raggi's avatar
Roberto Raggi committed
1020
1021
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
Leandro Melo's avatar
Leandro Melo committed
1022
                            const QByteArray id(interface->currentFile().tokenAt(functionName->identifier_token).identifier->chars());
Roberto Raggi's avatar
Roberto Raggi committed
1023
1024
1025
1026
1027
1028
1029

                            if (id == "tr" || id == "trUtf8"
                                    || id == "translate"
                                    || id == "QT_TRANSLATE_NOOP"
                                    || id == "QLatin1String" || id == "QLatin1Literal")
                                return noResult(); // skip it
                        }
1030
1031
1032
1033
1034
                    }
                }
            }
        }

Leandro Melo's avatar
Leandro Melo committed
1035
        QSharedPointer<Control> control = interface->context().control();
1036
        const Name *trName = control->identifier("tr");
1037
1038
1039
1040
1041
1042

        // Check whether we are in a method:
        for (int i = path.size() - 1; i >= 0; --i)
        {
            if (FunctionDefinitionAST *definition = path.at(i)->asFunctionDefinition()) {
                Function *function = definition->symbol;
Leandro Melo's avatar
Leandro Melo committed
1043
                ClassOrNamespace *b = interface->context().lookupType(function);
1044
1045
1046
1047
1048
1049
                if (b) {
                    // Do we have a tr method?
                    foreach(const LookupItem &r, b->find(trName)) {
                        Symbol *s = r.declaration();
                        if (s->type()->isFunctionType()) {
                            // no context required for tr
Leandro Melo's avatar
Leandro Melo committed
1050
                            return singleResult(new Operation(interface, path.size() - 1, literal, useTr, trContext));
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
                        }
                    }
                }
                // We need to do a QCA::translate, so we need a context.
                // Use fully qualified class name:
                Overview oo;
                foreach (const Name *n, LookupContext::path(function)) {
                    if (!trContext.isEmpty())
                        trContext.append(QLatin1String("::"));
                    trContext.append(oo.prettyName(n));
                }
                // ... or global if none available!
                if (trContext.isEmpty())
                    trContext = QLatin1String("GLOBAL");
Leandro Melo's avatar
Leandro Melo committed
1065
                return singleResult(new Operation(interface, path.size() - 1, literal, useQCoreApplicationTranslate, trContext));
1066
1067
1068
1069
            }
        }

        // We need to use Q_TRANSLATE_NOOP
Leandro Melo's avatar
Leandro Melo committed
1070
        return singleResult(new Operation(interface, path.size() - 1, literal, useMacro, QLatin1String("GLOBAL")));
1071
1072
1073
1074
1075
1076
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
1077
1078
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, ExpressionAST *literal, TranslationOption option, const QString &context)
            : CppQuickFixOperation(interface, priority)
1079
1080
1081
1082
            , m_literal(literal)
            , m_option(option)
            , m_context(context)
        {
1083
            setDescription(QApplication::translate("CppTools::QuickFix", "Mark as Translatable"));
1084
1085
        }

1086
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1087
1088
1089
        {
            ChangeSet changes;

1090
            const int startPos = currentFile->startOf(m_literal);
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
            QString replacement(QLatin1String("tr("));
            if (m_option == useQCoreApplicationTranslate) {
                replacement = QLatin1String("QCoreApplication::translate(\"")
                        + m_context + QLatin1String("\", ");
            } else if (m_option == useMacro) {
                replacement = QLatin1String("QT_TRANSLATE_NOOP(\"")
                        + m_context + QLatin1String("\", ");
            }

            changes.insert(startPos, replacement);
1101
            changes.insert(currentFile->endOf(m_literal), QLatin1String(")"));
1102

1103
            currentFile->change(changes);
1104
1105
1106
1107
1108
1109
1110
1111
1112
        }

    private:
        ExpressionAST *m_literal;
        TranslationOption m_option;
        QString m_context;
    };
};

1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
/**
 * Replace
 *    "abcd"
 *    QLatin1String("abcd")
 *    QLatin1Literal("abcd")
 * With
 *    @"abcd"
 *
 * Activates on: the string literal, if the file type is a Objective-C(++) file.
 */
1123
1124
1125
class CStringToNSString: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
1126
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
1127
    {
Leandro Melo's avatar
Leandro Melo committed
1128
        const CppRefactoringFile &file = interface->currentFile();
1129

Leandro Melo's avatar
Leandro Melo committed
1130
        if (interface->editor()->mimeType() != CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)
1131
1132
1133
1134
            return noResult();

        StringLiteralAST *stringLiteral = 0;
        CallAST *qlatin1Call = 0;
Leandro Melo's avatar
Leandro Melo committed
1135
        const QList<AST *> &path = interface->path();
1136
1137
1138
1139
1140
1141
1142
1143
1144

        if (path.isEmpty())
            return noResult(); // nothing to do

        stringLiteral = path.last()->asStringLiteral();

        if (! stringLiteral)
            return noResult();

1145
        else if (file.charAt(file.startOf(stringLiteral)) == QLatin1Char('@'))
1146
1147
1148
1149
1150
            return noResult(); // it's already an objc string literal.

        else if (path.size() > 1) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
Roberto Raggi's avatar
Roberto Raggi committed
1151
1152
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
Leandro Melo's avatar
Leandro Melo committed
1153
                            const QByteArray id(interface->currentFile().tokenAt(functionName->identifier_token).identifier->chars());
1154

Roberto Raggi's avatar
Roberto Raggi committed
1155
1156
1157
                            if (id == "QLatin1String" || id == "QLatin1Literal")
                                qlatin1Call = call;
                        }
1158
1159
1160
1161
1162
                    }
                }
            }
        }

Leandro Melo's avatar
Leandro Melo committed
1163
        return singleResult(new Operation(interface, path.size() - 1, stringLiteral, qlatin1Call));
1164
1165
1166
1167
1168
1169
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
1170
1171
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, StringLiteralAST *stringLiteral, CallAST *qlatin1Call)
            : CppQuickFixOperation(interface, priority)
1172
1173
1174
1175
1176
1177
1178
            , stringLiteral(stringLiteral)
            , qlatin1Call(qlatin1Call)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Convert to Objective-C String Literal"));
        }

1179
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1180
1181
1182
1183
        {
            ChangeSet changes;

            if (qlatin1Call) {
1184
1185
                changes.replace(currentFile->startOf(qlatin1Call), currentFile->startOf(stringLiteral), QLatin1String("@"));
                changes.remove(currentFile->endOf(stringLiteral), currentFile->endOf(qlatin1Call));
1186
            } else {
1187
                changes.insert(currentFile->startOf(stringLiteral), "@");
1188
1189
            }

1190
            currentFile->change(changes);
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
        }

    private:
        StringLiteralAST *stringLiteral;
        CallAST *qlatin1Call;
    };
};

/*
  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
1214
1215

    Activates on: numeric literals
1216
1217
1218
1219
*/
class ConvertNumericLiteral: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
1220
    virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
1221
1222
1223
    {
        QList<QuickFixOperation::Ptr> result;

Leandro Melo's avatar
Leandro Melo committed
1224
1225
        const QList<AST *> &path = interface->path();
        const CppRefactoringFile &file = interface->currentFile();
1226
1227
1228
1229
1230
1231
1232
1233
1234

        if (path.isEmpty())
            return result; // nothing to do

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

        if (! literal)
            return result;

1235
        Token token = file.tokenAt(literal->asNumericLiteral()->literal_token);
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
        if (!token.is(T_NUMERIC_LITERAL))
            return result;
        const NumericLiteral *numeric = token.number;
        if (numeric->isDouble() || numeric->isFloat())
            return result;

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

        // convert to number
        bool valid;
        ulong value = QString::fromUtf8(spell).left(numberLength).toULong(&valid, 0);
        if (!valid) // e.g. octal with digit > 7
            return result;

        const int priority = path.size() - 1; // very high priority
1257
        const int start = file.startOf(literal);
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
        const char * const str = numeric->chars();

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

            */
            QString replacement;
            replacement.sprintf("0x%lX", value);
Leandro Melo's avatar
Leandro Melo committed
1272
            QuickFixOperation::Ptr op(new ConvertNumeric(interface, start, start + numberLength, replacement));
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
            op->setDescription(QApplication::translate("CppTools::QuickFix", "Convert to Hexadecimal"));
            op->setPriority(priority);
            result.append(op);
        }

        if (value != 0) {
            if (!(numberLength > 1 && str[0] == '0' && str[1] != 'x' && str[1] != 'X')) {
                /*
                  Convert integer literal to octal representation.
                  Replace
                    32
                    0x20
                  With
                    040
                */
                QString replacement;
                replacement.sprintf("0%lo", value);
Leandro Melo's avatar
Leandro Melo committed
1290
                QuickFixOperation::Ptr op(new ConvertNumeric(interface, start, start + numberLength, replacement));
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
                op->setDescription(QApplication::translate("CppTools::QuickFix", "Convert to Octal"));
                op->setPriority(priority);
                result.append(op);
            }
        }

        if (value != 0 || numeric->isHex()) {
            if (!(numberLength > 1 && str[0] != '0')) {
                /*
                  Convert integer literal to decimal representation.
                  Replace
                    0x20
                    040
                  With
                    32
                */
                QString replacement;
                replacement.sprintf("%lu", value);
Leandro Melo's avatar
Leandro Melo committed
1309
                QuickFixOperation::Ptr op(new ConvertNumeric(interface, start, start + numberLength, replacement));
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
                op->setDescription(QApplication::translate("CppTools::QuickFix", "Convert to Decimal"));
                op->setPriority(priority);
                result.append(op);
            }
        }

        return result;
    }

private:
    class ConvertNumeric: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
1323
1324
1325
        ConvertNumeric(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
                       int start, int end, const QString &replacement)
            : CppQuickFixOperation(interface)
1326
1327
1328
1329
1330
            , start(start)
            , end(end)
            , replacement(replacement)
        {}

1331
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1332
1333
1334
        {
            ChangeSet changes;
            changes.replace(start, end, replacement);
1335
            currentFile->change(changes);
1336
1337
1338
1339
1340
1341
1342
1343
        }

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

1344
1345
/*
    Can be triggered on a class forward declaration to add the matching #include.