cppquickfix.cpp 40.7 KB
Newer Older
1
2
3
4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
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
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "cppquickfix.h"
#include "cppeditor.h"
32
33

#include <cplusplus/CppDocument.h>
34
#include <cplusplus/ResolveExpression.h>
35

36
#include <TranslationUnit.h>
37
38
#include <ASTVisitor.h>
#include <AST.h>
39
40
#include <ASTPatternBuilder.h>
#include <ASTMatcher.h>
41
#include <Token.h>
42
43
44
45
46
47
#include <Type.h>
#include <CoreTypes.h>
#include <Symbol.h>
#include <Symbols.h>
#include <Name.h>
#include <Literals.h>
48

49
#include <cpptools/cpptoolsconstants.h>
50
#include <cpptools/cppmodelmanagerinterface.h>
51

Robert Loehning's avatar
Robert Loehning committed
52
#include <QtGui/QApplication>
53
#include <QtGui/QTextBlock>
54
55
56
57

using namespace CppEditor::Internal;
using namespace CPlusPlus;

58
59
namespace {

60
61
62
63
64
65
66
67
68
class ASTPath: public ASTVisitor
{
    Document::Ptr _doc;
    unsigned _line;
    unsigned _column;
    QList<AST *> _nodes;

public:
    ASTPath(Document::Ptr doc)
Roberto Raggi's avatar
Roberto Raggi committed
69
70
71
        : ASTVisitor(doc->translationUnit()),
          _doc(doc), _line(0), _column(0)
    {}
72
73
74
75
76

    QList<AST *> operator()(const QTextCursor &cursor)
    {
        _nodes.clear();
        _line = cursor.blockNumber() + 1;
77
        _column = cursor.positionInBlock() + 1;
78
79
80
81
        accept(_doc->translationUnit()->ast());
        return _nodes;
    }

82
83
#if 0
    // Useful for debugging:
84
85
86
87
88
89
    static void dump(const QList<AST *> nodes)
    {
        qDebug() << "ASTPath dump," << nodes.size() << "nodes:";
        for (int i = 0; i < nodes.size(); ++i)
            qDebug() << qPrintable(QString(i + 1, QLatin1Char('-'))) << typeid(*nodes.at(i)).name();
    }
90
#endif
91

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
protected:
    virtual bool preVisit(AST *ast)
    {
        unsigned firstToken = ast->firstToken();
        unsigned lastToken = ast->lastToken();

        if (firstToken > 0 && lastToken > firstToken) {
            unsigned startLine, startColumn;
            getTokenStartPosition(firstToken, &startLine, &startColumn);

            if (_line > startLine || (_line == startLine && _column >= startColumn)) {

                unsigned endLine, endColumn;
                getTokenEndPosition(lastToken - 1, &endLine, &endColumn);

107
                if (_line < endLine || (_line == endLine && _column <= endColumn)) {
108
109
110
111
112
113
114
115
116
117
                    _nodes.append(ast);
                    return true;
                }
            }
        }

        return false;
    }
};

118
119
/*
    Rewrite
120
121
122
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
123
124
125
126
127
*/
class UseInverseOp: public QuickFixOperation
{
public:
    UseInverseOp()
128
        : binary(0), nested(0), negation(0)
129
130
131
132
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
133
        return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
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
    }

    virtual int match(const QList<AST *> &path)
    {
        int index = path.size() - 1;
        binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return -1;
        if (! isCursorOn(binary->binary_op_token))
            return -1;

        CPlusPlus::Kind invertToken;
        switch (tokenAt(binary->binary_op_token).kind()) {
        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 -1;
        }

        CPlusPlus::Token tok;
        tok.f.kind = invertToken;
        replacement = QLatin1String(tok.spell());
172
173
174
175
176
177
178
179
180
181
182
183

        // check for enclosing nested expression
        if (index - 1 >= 0)
            nested = path[index - 1]->asNestedExpression();

        // check for ! before parentheses
        if (nested && index - 2 >= 0) {
            negation = path[index - 2]->asUnaryExpression();
            if (negation && ! tokenAt(negation->unary_op_token).is(T_EXCLAIM))
                negation = 0;
        }

184
185
186
187
188
        return index;
    }

    virtual void createChangeSet()
    {
189
190
191
192
193
194
195
196
197
        if (negation) {
            // can't remove parentheses since that might break precedence
            remove(negation->unary_op_token);
        } else if (nested) {
            insert(startOf(nested), "!");
        } else {
            insert(startOf(binary), "!(");
            insert(endOf(binary), ")");
        }
198
199
200
201
202
        replace(binary->binary_op_token, replacement);
    }

private:
    BinaryExpressionAST *binary;
203
204
205
    NestedExpressionAST *nested;
    UnaryExpressionAST *negation;

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    QString replacement;
};

/*
    Rewrite
    a op b

    As
    b flipop a
*/
class FlipBinaryOp: public QuickFixOperation
{
public:
    FlipBinaryOp()
        : binary(0)
    {}


    virtual QString description() const
    {
        if (replacement.isEmpty())
Robert Loehning's avatar
Robert Loehning committed
227
            return QApplication::translate("CppTools::QuickFix", "Swap Operands");
228
        else
Robert Loehning's avatar
Robert Loehning committed
229
            return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
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
    }

    virtual int match(const QList<AST *> &path)
    {
        int index = path.size() - 1;
        binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return -1;
        if (! isCursorOn(binary->binary_op_token))
            return -1;

        CPlusPlus::Kind flipToken;
        switch (tokenAt(binary->binary_op_token).kind()) {
        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 -1;
        }

        if (flipToken != T_EOF_SYMBOL) {
            CPlusPlus::Token tok;
            tok.f.kind = flipToken;
            replacement = QLatin1String(tok.spell());
        }
        return index;
    }

    virtual void createChangeSet()
    {
        flip(binary->left_expression, binary->right_expression);
        if (! replacement.isEmpty())
            replace(binary->binary_op_token, replacement);
    }

private:
    BinaryExpressionAST *binary;
    QString replacement;
};

/*
    Rewrite
    !a && !b

    As
    !(a || b)
*/
292
293
294
class RewriteLogicalAndOp: public QuickFixOperation
{
public:
Roberto Raggi's avatar
Roberto Raggi committed
295
296
    RewriteLogicalAndOp()
        : left(0), right(0), pattern(0)
297
298
299
300
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
301
        return QApplication::translate("CppTools::QuickFix", "Rewrite Condition Using ||");
302
303
    }

304
    virtual int match(const QList<AST *> &path)
305
    {
306
307
308
309
310
311
312
313
314
315
316
317
        BinaryExpressionAST *expression = 0;

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

        if (! expression)
            return -1;

318
        if (! isCursorOn(expression->binary_op_token))
319
320
            return -1;

321
322
323
324
325
326
327
328
        left = mk.UnaryExpression();
        right = mk.UnaryExpression();
        pattern = mk.BinaryExpression(left, right);

        if (expression->match(pattern, &matcher) &&
                tokenAt(pattern->binary_op_token).is(T_AMPER_AMPER) &&
                tokenAt(left->unary_op_token).is(T_EXCLAIM) &&
                tokenAt(right->unary_op_token).is(T_EXCLAIM)) {
329
            return index;
330
331
        }

332
        return -1;
333
334
    }

Roberto Raggi's avatar
Roberto Raggi committed
335
    virtual void createChangeSet()
336
    {
Roberto Raggi's avatar
Roberto Raggi committed
337
        setTopLevelNode(pattern);
338
        replace(pattern->binary_op_token, QLatin1String("||"));
339
340
341
        remove(left->unary_op_token);
        remove(right->unary_op_token);
        insert(startOf(pattern), QLatin1String("!("));
342
        insert(endOf(pattern), QLatin1String(")"));
343
344
345
346
347
348
349
350
351
352
    }

private:
    ASTMatcher matcher;
    ASTPatternBuilder mk;
    UnaryExpressionAST *left;
    UnaryExpressionAST *right;
    BinaryExpressionAST *pattern;
};

353
354
355
class SplitSimpleDeclarationOp: public QuickFixOperation
{
public:
Roberto Raggi's avatar
Roberto Raggi committed
356
357
    SplitSimpleDeclarationOp()
        : declaration(0)
358
359
360
361
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
362
        return QApplication::translate("CppTools::QuickFix", "Split Declaration");
363
364
365
366
    }

    bool checkDeclaration(SimpleDeclarationAST *declaration) const
    {
367
368
369
        if (! declaration->semicolon_token)
            return false;

370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
        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;
    }

392
    virtual int match(const QList<AST *> &path)
393
394
395
396
397
398
399
400
401
402
403
404
405
406
    {
        CoreDeclaratorAST *core_declarator = 0;

        int index = path.size() - 1;
        for (; 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)) {
                    declaration = simpleDecl;

407
                    const int cursorPosition = selectionStart();
408
409
410
411
412
413
414

                    const int startOfDeclSpecifier = startOf(declaration->decl_specifier_list->firstToken());
                    const int endOfDeclSpecifier = endOf(declaration->decl_specifier_list->lastToken() - 1);

                    if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier)
                        return index; // the AST node under cursor is a specifier.

415
                    if (core_declarator && isCursorOn(core_declarator))
416
                        return index; // got a core-declarator under the text cursor.
417
418
419
420
421
422
423
424
425
                }

                break;
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
426
    virtual void createChangeSet()
427
    {
Roberto Raggi's avatar
Roberto Raggi committed
428
        setTopLevelNode(declaration);
429
        SpecifierListAST *specifiers = declaration->decl_specifier_list;
430
431
432
        int declSpecifiersStart = startOf(specifiers->firstToken());
        int declSpecifiersEnd = endOf(specifiers->lastToken() - 1);
        int insertPos = endOf(declaration->semicolon_token);
433

434
        DeclaratorAST *prevDeclarator = declaration->declarator_list->value;
435
436
437
438

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

439
440
441
442
443
444
445
            insert(insertPos, QLatin1String("\n"));
            copy(declSpecifiersStart, declSpecifiersEnd, insertPos);
            insert(insertPos, QLatin1String(" "));
            move(declarator, insertPos);
            insert(insertPos, QLatin1String(";"));

            remove(endOf(prevDeclarator), startOf(declarator));
446

447
448
            prevDeclarator = declarator;
        }
449
450
451
452
453
454
    }

private:
    SimpleDeclarationAST *declaration;
};

455
456
457
458
459
460
461
/*
    Add curly braces to a if statement that doesn't already contain a
    compound statement.
*/
class AddBracesToIfOp: public QuickFixOperation
{
public:
Roberto Raggi's avatar
Roberto Raggi committed
462
463
    AddBracesToIfOp()
        : _statement(0)
464
465
466
467
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
468
        return QApplication::translate("CppTools::QuickFix", "Add Curly Braces");
469
470
    }

471
    virtual int match(const QList<AST *> &path)
472
473
474
475
    {
        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
476
        if (ifStatement && isCursorOn(ifStatement->if_token)
477
478
479
480
481
482
483
484
485
            && ! ifStatement->statement->asCompoundStatement()) {
            _statement = ifStatement->statement;
            return index;
        }

        // 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();
486
487
            if (ifStatement && ifStatement->statement
                && isCursorOn(ifStatement->statement)
488
489
490
491
492
493
494
495
496
497
498
499
                && ! ifStatement->statement->asCompoundStatement()) {
                _statement = ifStatement->statement;
                return index;
            }
        }

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

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
500
    virtual void createChangeSet()
501
    {
Roberto Raggi's avatar
Roberto Raggi committed
502
        setTopLevelNode(_statement);
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
        insert(endOf(_statement->firstToken() - 1), QLatin1String(" {"));
        insert(endOf(_statement->lastToken() - 1), "\n}");
    }

private:
    StatementAST *_statement;
};

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

    With
    Type name = foo;
    if (name) {...}
*/
519
class MoveDeclarationOutOfIfOp: public QuickFixOperation
520
521
{
public:
Roberto Raggi's avatar
Roberto Raggi committed
522
523
    MoveDeclarationOutOfIfOp()
        : condition(0), pattern(0), core(0)
524
525
526
527
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
528
        return QApplication::translate("CppTools::QuickFix", "Move Declaration out of Condition");
529
530
    }

531
    virtual int match(const QList<AST *> &path)
532
533
534
535
536
537
538
539
540
541
542
543
544
    {
        condition = mk.Condition();
        pattern = mk.IfStatement(condition);

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

545
                    if (isCursorOn(core))
546
547
548
549
550
551
552
553
                        return index;
                }
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
554
    virtual void createChangeSet()
555
    {
Roberto Raggi's avatar
Roberto Raggi committed
556
        setTopLevelNode(pattern);
557

558
559
560
561
562
        copy(core, startOf(condition));

        int insertPos = startOf(pattern);
        move(condition, insertPos);
        insert(insertPos, QLatin1String(";\n"));
563
564
565
566
567
568
569
570
571
572
573
    }

private:
    ASTMatcher matcher;
    ASTPatternBuilder mk;
    CPPEditor *editor;
    ConditionAST *condition;
    IfStatementAST *pattern;
    CoreDeclaratorAST *core;
};

574
575
576
577
578
579
580
581
582
583
584
/*
    Replace
    while (Type name = foo()) {...}

    With
    Type name;
    while ((name = foo()) != 0) {...}
*/
class MoveDeclarationOutOfWhileOp: public QuickFixOperation
{
public:
Roberto Raggi's avatar
Roberto Raggi committed
585
586
    MoveDeclarationOutOfWhileOp()
        : condition(0), pattern(0), core(0)
587
588
589
590
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
591
        return QApplication::translate("CppTools::QuickFix", "Move Declaration out of Condition");
592
593
    }

594
    virtual int match(const QList<AST *> &path)
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
    {
        condition = mk.Condition();
        pattern = mk.WhileStatement(condition);

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

                    if (! core)
                        return -1;

                    else if (! declarator->equals_token)
                        return -1;

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

615
                    if (isCursorOn(core))
616
617
618
619
620
621
622
623
                        return index;
                }
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
624
    virtual void createChangeSet()
625
    {
Roberto Raggi's avatar
Roberto Raggi committed
626
        setTopLevelNode(pattern);
627
628
629
630
631
632
633
634

        insert(startOf(condition), QLatin1String("("));
        insert(endOf(condition), QLatin1String(") != 0"));

        int insertPos = startOf(pattern);
        move(startOf(condition), startOf(core), insertPos);
        copy(core, insertPos);
        insert(insertPos, QLatin1String(";\n"));
635
636
637
638
639
640
641
642
643
644
645
    }

private:
    ASTMatcher matcher;
    ASTPatternBuilder mk;
    CPPEditor *editor;
    ConditionAST *condition;
    WhileStatementAST *pattern;
    CoreDeclaratorAST *core;
};

Roberto Raggi's avatar
Roberto Raggi committed
646
647
648
649
650
651
652
653
654
655
/*
  Replace
     if (something && something_else) {
     }

  with
     if (something) {
        if (something_else) {
        }
     }
Roberto Raggi's avatar
Roberto Raggi committed
656
657
658
659
660
661
662
663
664
665

  and
    if (something || something_else)
      x;

  with
    if (something)
      x;
    else if (something_else)
      x;
Roberto Raggi's avatar
Roberto Raggi committed
666
667
668
669
*/
class SplitIfStatementOp: public QuickFixOperation
{
public:
Roberto Raggi's avatar
Roberto Raggi committed
670
671
    SplitIfStatementOp()
        : condition(0), pattern(0)
Roberto Raggi's avatar
Roberto Raggi committed
672
673
674
675
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
676
        return QApplication::translate("CppTools::QuickFix", "Split if Statement");
Roberto Raggi's avatar
Roberto Raggi committed
677
678
    }

679
    virtual int match(const QList<AST *> &path)
Roberto Raggi's avatar
Roberto Raggi committed
680
    {
681
        pattern = 0;
Roberto Raggi's avatar
Roberto Raggi committed
682

683
684
685
686
687
688
689
690
691
        int index = path.size() - 1;
        for (; index != -1; --index) {
            AST *node = path.at(index);
            if (IfStatementAST *stmt = node->asIfStatement()) {
                pattern = stmt;
                break;
            }
        }

692
        if (! pattern || ! pattern->statement)
693
694
            return -1;

695
        unsigned splitKind = 0;
696
697
698
699
700
701
702
        for (++index; index < path.size(); ++index) {
            AST *node = path.at(index);
            condition = node->asBinaryExpression();
            if (! condition)
                return -1;

            Token binaryToken = tokenAt(condition->binary_op_token);
703
704
705
706
707
708
709
710
711
712

            // 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 -1;
                // we can't reliably split &&s in ifs with an else branch
                if (splitKind == T_AMPER_AMPER && pattern->else_statement)
                    return -1;
            } else if (splitKind != binaryToken.kind()) {
713
714
                return -1;
            }
715
716
717

            if (isCursorOn(condition->binary_op_token))
                return index;
718
719
720
        }

        return -1;
Roberto Raggi's avatar
Roberto Raggi committed
721
722
    }

Roberto Raggi's avatar
Roberto Raggi committed
723
    virtual void createChangeSet()
Roberto Raggi's avatar
Roberto Raggi committed
724
    {
725
        Token binaryToken = tokenAt(condition->binary_op_token);
Roberto Raggi's avatar
Roberto Raggi committed
726

727
        if (binaryToken.is(T_AMPER_AMPER))
Roberto Raggi's avatar
Roberto Raggi committed
728
729
730
731
732
733
734
            splitAndCondition();
        else
            splitOrCondition();
    }

    void splitAndCondition()
    {
Roberto Raggi's avatar
Roberto Raggi committed
735
        setTopLevelNode(pattern);
Roberto Raggi's avatar
Roberto Raggi committed
736

737
738
739
740
741
742
743
        int startPos = startOf(pattern);
        insert(startPos, QLatin1String("if ("));
        move(condition->left_expression, startPos);
        insert(startPos, QLatin1String(") {\n"));

        remove(endOf(condition->left_expression), startOf(condition->right_expression));
        insert(endOf(pattern), QLatin1String("\n}"));
Roberto Raggi's avatar
Roberto Raggi committed
744
745
    }

Roberto Raggi's avatar
Roberto Raggi committed
746
747
748
749
750
    void splitOrCondition()
    {
        StatementAST *ifTrueStatement = pattern->statement;
        CompoundStatementAST *compoundStatement = ifTrueStatement->asCompoundStatement();

751
        setTopLevelNode(pattern);
Roberto Raggi's avatar
Roberto Raggi committed
752

753
        int insertPos = endOf(ifTrueStatement);
Roberto Raggi's avatar
Roberto Raggi committed
754
        if (compoundStatement)
755
            insert(insertPos, QLatin1String(" "));
Roberto Raggi's avatar
Roberto Raggi committed
756
        else
757
758
759
760
761
            insert(insertPos, QLatin1String("\n"));
        insert(insertPos, QLatin1String("else if ("));
        move(startOf(condition->right_expression), startOf(pattern->rparen_token), insertPos);
        insert(insertPos, QLatin1String(")"));
        copy(endOf(pattern->rparen_token), endOf(pattern->statement), insertPos);
762

763
        remove(endOf(condition->left_expression), startOf(condition->right_expression));
Roberto Raggi's avatar
Roberto Raggi committed
764
765
    }

Roberto Raggi's avatar
Roberto Raggi committed
766
767
768
769
private:
    BinaryExpressionAST *condition;
    IfStatementAST *pattern;
};
770

771
772
773
774
775
776
777
778
779
780
/*
  Replace
    "abcd"
  With
    QLatin1String("abcd")
*/
class WrapStringLiteral: public QuickFixOperation
{
public:
    WrapStringLiteral()
781
        : stringLiteral(0), isObjCStringLiteral(false)
782
783
784
785
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
786
        return QApplication::translate("CppTools::QuickFix", "Enclose in QLatin1String(...)");
787
788
789
790
791
792
793
794
795
796
797
798
799
    }

    virtual int match(const QList<AST *> &path)
    {
        if (path.isEmpty())
            return -1;

        int index = path.size() - 1;
        stringLiteral = path[index]->asStringLiteral();

        if (!stringLiteral)
            return -1;

800
801
        isObjCStringLiteral = charAt(startOf(stringLiteral)) == QLatin1Char('@');

802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
        // check if it is already wrapped in QLatin1String or -Literal
        if (index-2 < 0)
            return index;

        CallAST *call = path[index-1]->asCall();
        PostfixExpressionAST *postfixExp = path[index-2]->asPostfixExpression();
        if (call && postfixExp
            && postfixExp->base_expression
            && postfixExp->postfix_expression_list
            && postfixExp->postfix_expression_list->value == call)
        {
            NameAST *callName = postfixExp->base_expression->asName();
            if (!callName)
                return index;

            QByteArray callNameString(tokenAt(callName->firstToken()).spell());
            if (callNameString == "QLatin1String"
                || callNameString == "QLatin1Literal"
                )
                return -1;
        }

        return index;
    }

    virtual void createChangeSet()
    {
829
830
831
832
833
834
835
836
        const int startPos = startOf(stringLiteral);
        const QLatin1String replacement("QLatin1String(");

        if (isObjCStringLiteral)
            replace(startPos, startPos + 1, replacement);
        else
            insert(startPos, replacement);

837
838
839
840
841
        insert(endOf(stringLiteral), ")");
    }

private:
    StringLiteralAST *stringLiteral;
842
    bool isObjCStringLiteral;
843
844
};

845
846
847
848
849
850
851
852
class CStringToNSString: public QuickFixOperation
{
public:
    CStringToNSString()
        : stringLiteral(0), qlatin1Call(0)
    {}

    virtual QString description() const
Robert Loehning's avatar
Robert Loehning committed
853
854
855
    {
        return QApplication::translate("CppTools::QuickFix", "Convert to Objective-C String Literal");
    }
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912

    virtual int match(const QList<AST *> &path)
    {
        if (path.isEmpty())
            return -1;

        int index = path.size() - 1;
        stringLiteral = path[index]->asStringLiteral();

        if (!stringLiteral)
            return -1;

        if (charAt(startOf(stringLiteral)) == QLatin1Char('@'))
            return -1;

        // check if it is already wrapped in QLatin1String or -Literal
        if (index-2 < 0)
            return index;

        CallAST *call = path[index-1]->asCall();
        PostfixExpressionAST *postfixExp = path[index-2]->asPostfixExpression();
        if (call && postfixExp
            && postfixExp->base_expression
            && postfixExp->postfix_expression_list
            && postfixExp->postfix_expression_list->value == call)
        {
            NameAST *callName = postfixExp->base_expression->asName();
            if (!callName)
                return index;

            if (!(postfixExp->postfix_expression_list->next)) {
                QByteArray callNameString(tokenAt(callName->firstToken()).spell());
                if (callNameString == "QLatin1String"
                    || callNameString == "QLatin1Literal"
                    )
                    qlatin1Call = postfixExp;
            }
        }

        return index;
    }

    virtual void createChangeSet()
    {
        if (qlatin1Call) {
            replace(startOf(qlatin1Call), startOf(stringLiteral), QLatin1String("@"));
            remove(endOf(stringLiteral), endOf(qlatin1Call));
        } else {
            insert(startOf(stringLiteral), "@");
        }
    }

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

913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
/*
  Replace
    a + b
  With
    a % b
  If a and b are of string type.
*/
class UseFastStringConcatenation: public QuickFixOperation
{
public:
    UseFastStringConcatenation()
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
928
        return QApplication::translate("CppTools::QuickFix", "Use Fast String Concatenation with %");
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
    }

    virtual int match(const QList<AST *> &path)
    {
        if (path.isEmpty())
            return -1;

        // need to search 'up' too
        int index = path.size() - 1;
        if (BinaryExpressionAST *binary = asPlusNode(path[index])) {
            while (0 != (binary = asPlusNode(binary->left_expression)))
                _binaryExpressions.prepend(binary);
        }

        // search 'down'
        for (index = path.size() - 1; index != -1; --index) {
            AST *node = path.at(index);
            if (BinaryExpressionAST *binary = asPlusNode(node)) {
                _binaryExpressions.append(binary);
            } else if (! _binaryExpressions.isEmpty()) {
                break;
            }
        }

        if (_binaryExpressions.isEmpty())
            return -1;

        // verify types of arguments
        BinaryExpressionAST *prevBinary = 0;
        foreach (BinaryExpressionAST *binary, _binaryExpressions) {
            if (binary->left_expression != prevBinary) {
                if (!hasCorrectType(binary->left_expression))
                    return -1;
            }
            if (binary->right_expression != prevBinary) {
                if (!hasCorrectType(binary->right_expression))
                    return -1;
            }
            prevBinary = binary;
        }

        return index + _binaryExpressions.size();
    }

    virtual void createChangeSet()
    {
        // replace + -> %
        foreach (BinaryExpressionAST *binary, _binaryExpressions)
            replace(binary->binary_op_token, "%");

        // wrap literals in QLatin1Literal
        foreach (StringLiteralAST *literal, _stringLiterals) {
            insert(startOf(literal), "QLatin1Literal(");
            insert(endOf(literal), ")");
        }

        // replace QLatin1String/QString/QByteArray(literal) -> QLatin1Literal(literal)
        foreach (PostfixExpressionAST *postfix, _incorrectlyWrappedLiterals) {
            replace(postfix->base_expression, "QLatin1Literal");
        }
    }

    BinaryExpressionAST *asPlusNode(AST *ast)
    {
        BinaryExpressionAST *binary = ast->asBinaryExpression();
        if (binary && tokenAt(binary->binary_op_token).kind() == T_PLUS)
            return binary;
        return 0;
    }

    bool hasCorrectType(ExpressionAST *ast)
    {
        if (StringLiteralAST *literal = ast->asStringLiteral()) {
            _stringLiterals += literal;
            return true;
        }

        if (PostfixExpressionAST *postfix = ast->asPostfixExpression()) {
            if (postfix->base_expression && postfix->postfix_expression_list
                && postfix->postfix_expression_list->value
                && !postfix->postfix_expression_list->next)
            {
                NameAST *name = postfix->base_expression->asName();
                CallAST *call = postfix->postfix_expression_list->value->asCall();
                if (name && call) {
                    QByteArray nameStr(name->name->identifier()->chars());
                    if ((nameStr == "QLatin1String"
                         || nameStr == "QString"
                         || nameStr == "QByteArray")
                        && call->expression_list
                        && call->expression_list->value
                        && call->expression_list->value->asStringLiteral()
                        && !call->expression_list->next)
                    {
                        _incorrectlyWrappedLiterals += postfix;
                        return true;
                    }
                }
            }
        }

        const QList<LookupItem> &lookup = typeOf(ast);
        if (lookup.isEmpty())
            return false;
        return isQtStringType(lookup[0].type());
    }

    bool isBuiltinStringType(FullySpecifiedType type)
    {
        // char*
        if (PointerType *ptrTy = type->asPointerType())
            if (IntegerType *intTy = ptrTy->elementType()->asIntegerType())
                if (intTy->kind() == IntegerType::Char)
                    return true;
        return false;
    }

    bool isQtStringType(FullySpecifiedType type)
    {
        if (NamedType *nameTy = type->asNamedType()) {
            if (!nameTy->name() || !nameTy->name()->identifier())
                return false;

            QByteArray name(nameTy->name()->identifier()->chars());
            if (name == "QString"
                || name == "QByteArray"
                || name == "QLatin1String"
                || name == "QLatin1Literal"
                || name == "QStringRef"
                || name == "QChar"
                )
                return true;
        }

        return false;
    }

private:
    QList<BinaryExpressionAST *> _binaryExpressions;
    QList<StringLiteralAST *> _stringLiterals;
    QList<PostfixExpressionAST *> _incorrectlyWrappedLiterals;
};

1072
1073
1074
} // end of anonymous namespace


Roberto Raggi's avatar
Roberto Raggi committed
1075
1076
QuickFixOperation::QuickFixOperation()
    : _editor(0), _topLevelNode(0)
1077
1078
1079
1080
1081
{ }

QuickFixOperation::~QuickFixOperation()
{ }

Roberto Raggi's avatar
Roberto Raggi committed
1082
1083
1084
1085
1086
1087
CPlusPlus::AST *QuickFixOperation::topLevelNode() const
{ return _topLevelNode; }

void QuickFixOperation::setTopLevelNode(CPlusPlus::AST *topLevelNode)
{ _topLevelNode = topLevelNode; }

Roberto Raggi's avatar
Roberto Raggi committed
1088
1089
1090
const Utils::ChangeSet &QuickFixOperation::changeSet() const
{ return _changeSet; }

Roberto Raggi's avatar
Roberto Raggi committed
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
Document::Ptr QuickFixOperation::document() const
{ return _document; }

void QuickFixOperation::setDocument(CPlusPlus::Document::Ptr document)
{ _document = document; }

Snapshot QuickFixOperation::snapshot() const
{ return _snapshot; }

void QuickFixOperation::setSnapshot(const CPlusPlus::Snapshot &snapshot)
1101
1102
1103
{
    _snapshot = snapshot;
}
Roberto Raggi's avatar
Roberto Raggi committed
1104
1105
1106
1107
1108
1109
1110

CPPEditor *QuickFixOperation::editor() const
{ return _editor; }

void QuickFixOperation::setEditor(CPPEditor *editor)
{ _editor = editor; }

1111
1112
1113
QTextCursor QuickFixOperation::textCursor() const
{ return _textCursor; }

1114
1115
1116
void QuickFixOperation::setTextCursor(const QTextCursor &cursor)
{ _textCursor = cursor; }

1117
1118
1119
1120
1121
1122
int QuickFixOperation::selectionStart() const
{ return _textCursor.selectionStart(); }

int QuickFixOperation::selectionEnd() const
{ return _textCursor.selectionEnd(); }

1123
const CPlusPlus::Token &QuickFixOperation::tokenAt(unsigned index) const
Roberto Raggi's avatar
Roberto Raggi committed
1124
{ return _document->translationUnit()->tokenAt(index); }
1125

1126
int QuickFixOperation::startOf(unsigned index) const
1127
{
1128
    unsigned line, column;
Roberto Raggi's avatar
Roberto Raggi committed
1129
    _document->translationUnit()->getPosition(tokenAt(index).begin(), &line, &column);
1130
1131
    return _textCursor.document()->findBlockByNumber(line - 1).position() + column - 1;
}
1132

1133
1134
1135
1136
1137
1138
int QuickFixOperation::startOf(const CPlusPlus::AST *ast) const
{
    return startOf(ast->firstToken());
}

int QuickFixOperation::endOf(unsigned index) const
1139
1140
{
    unsigned line, column;
Roberto Raggi's avatar
Roberto Raggi committed
1141
    _document->translationUnit()->getPosition(tokenAt(index).end(), &line, &column);
1142
    return _textCursor.document()->findBlockByNumber(line - 1).position() + column - 1;
1143
1144
}

1145
1146
1147
1148
1149
int QuickFixOperation::endOf(const CPlusPlus::AST *ast) const
{
    return endOf(ast->lastToken() - 1);
}

1150
1151
1152
1153
1154
1155
1156
1157
1158
void QuickFixOperation::startAndEndOf(unsigned index, int *start, int *end) const
{
    unsigned line, column;
    CPlusPlus::Token token(tokenAt(index));
    _document->translationUnit()->getPosition(token.begin(), &line, &column);
    *start = _textCursor.document()->findBlockByNumber(line - 1).position() + column - 1;
    *end = *start + token.length();
}

1159
bool QuickFixOperation::isCursorOn(unsigned tokenIndex) const
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
{
    QTextCursor tc = textCursor();
    int cursorBegin = tc.selectionStart();

    int start = startOf(tokenIndex);
    int end = endOf(tokenIndex);

    if (cursorBegin >= start && cursorBegin <= end)
        return true;

    return false;
}

1173
bool QuickFixOperation::isCursorOn(const CPlusPlus::AST *ast) const
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
{
    QTextCursor tc = textCursor();
    int cursorBegin = tc.selectionStart();

    int start = startOf(ast);
    int end = endOf(ast);

    if (cursorBegin >= start && cursorBegin <= end)
        return true;

    return false;
}

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
1187
QuickFixOperation::Range QuickFixOperation::createRange(AST *ast) const
1188
{
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
1189
1190
1191
1192
1193
1194
1195
1196
    QTextCursor tc = _textCursor;
    Range r(tc);
    r.begin.setPosition(startOf(ast));
    r.end.setPosition(endOf(ast));
    return r;
}

void QuickFixOperation::reindent(const Range &range)
1197
{
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
1198
1199
1200
    QTextCursor tc = range.begin;
    tc.setPosition(range.end.position(), QTextCursor::KeepAnchor);
    _editor->indentInsertedText(tc);
1201
1202
}

1203
1204
void QuickFixOperation::move(int start, int end, int to)
{
1205
    _changeSet.move(start, end-start, to);
1206
1207
1208
1209
}

void QuickFixOperation::move(unsigned tokenIndex, int to)
{
1210
1211
1212
    int start, end;
    startAndEndOf(tokenIndex, &start, &end);
    move(start, end, to);
1213
1214
1215
1216
1217
1218
1219
1220
1221
}

void QuickFixOperation::move(const CPlusPlus::AST *ast, int to)
{
    move(startOf(ast), endOf(ast), to);
}

void QuickFixOperation::replace(int start, int end, const QString &replacement)
{
1222
    _changeSet.replace(start, end-start, replacement);
1223
1224
1225
1226
}

void QuickFixOperation::replace(unsigned tokenIndex, const QString &replacement)
{
1227
1228
1229
    int start, end;
    startAndEndOf(tokenIndex, &start, &end);
    replace(start, end, replacement);
1230
1231
1232
1233
1234
1235
1236
1237
1238
}

void QuickFixOperation::replace(const CPlusPlus::AST *ast, const QString &replacement)
{
    replace(startOf(ast), endOf(ast), replacement);
}

void QuickFixOperation::insert(int at, const QString &text)
{
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
    _changeSet.insert(at, text);
}

void QuickFixOperation::remove(int start, int end)
{
    _changeSet.remove(start, end-start);
}

void QuickFixOperation::remove(unsigned tokenIndex)
{
1249
1250
1251
    int start, end;
    startAndEndOf(tokenIndex, &start, &end);
    remove(start, end);
1252
1253
1254
1255
1256
1257
1258
}

void QuickFixOperation::remove(const CPlusPlus::AST *ast)
{
    remove(startOf(ast), endOf(ast));
}

Christian Kamm's avatar
Christian Kamm committed
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
void QuickFixOperation::flip(int start1, int end1, int start2, int end2)
{
    _changeSet.flip(start1, end1-start1, start2, end2-start2);
}

void QuickFixOperation::flip(const CPlusPlus::AST *ast1, const CPlusPlus::AST *ast2)
{
    flip(startOf(ast1), endOf(ast1), startOf(ast2), endOf(ast2));
}

1269
1270
1271
1272
1273
1274
1275
void QuickFixOperation::copy(int start, int end, int to)
{
    _changeSet.copy(start, end-start, to);
}

void QuickFixOperation::copy(unsigned tokenIndex, int to)
{
1276
1277
1278
    int start, end;
    startAndEndOf(tokenIndex, &start, &end);
    copy(start, end, to);
1279
1280
1281
1282
1283
}

void QuickFixOperation::copy(const CPlusPlus::AST *ast, int to)
{
    copy(startOf(ast), endOf(ast), to);
1284
1285
}

1286
1287
1288
1289
1290
1291
1292
1293
QString QuickFixOperation::textOf(int firstOffset, int lastOffset) const
{
    QTextCursor tc = _textCursor;
    tc.setPosition(firstOffset);
    tc.setPosition(lastOffset, QTextCursor::KeepAnchor);
    return tc.selectedText();
}

1294
QString QuickFixOperation::textOf(const AST *ast) const
1295
{
1296
    return textOf(startOf(ast), endOf(ast));
1297
1298
}

1299
1300
1301
1302
1303
QChar QuickFixOperation::charAt(int offset) const
{
    return textOf(offset, offset + 1).at(0);
}

1304
void QuickFixOperation::apply()
1305
{
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
1306
    Range range;
1307

Roberto Raggi's avatar
Roberto Raggi committed
1308
1309
    if (_topLevelNode)
        range = createRange(_topLevelNode);
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
1310
1311

    _textCursor.beginEditBlock();
1312

1313
    _changeSet.apply(&_textCursor);
1314

Roberto Raggi's avatar
Roberto Raggi committed
1315
    if (_topLevelNode)
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
1316
        reindent(range);
1317

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
1318
    _textCursor.endEditBlock();
1319
1320
}

1321
1322
1323
1324
1325
1326
/**
 * Returns a list of possible fully specified types associated with the
 * given expression.
 *
 * NOTE: The fully specified types only stay valid until the next call to typeOf.
 */
1327
const QList<LookupItem> QuickFixOperation::typeOf(CPlusPlus::ExpressionAST *ast)
1328
1329
1330
1331
1332
{
    unsigned line, column;
    document()->translationUnit()->getTokenStartPosition(ast->firstToken(), &line, &column);
    Symbol *lastVisibleSymbol = document()->findSymbolAt(line, column);

1333
1334
1335
1336
    _lookupContext = LookupContext(lastVisibleSymbol, document(), document(), snapshot());

    ResolveExpression resolveExpression(_lookupContext);
    return resolveExpression(ast);
1337
1338
}

1339
CPPQuickFixCollector::CPPQuickFixCollector()
1340
    : _modelManager(CppTools::CppModelManagerInterface::instance()), _editable(0), _editor(0)
1341
1342
1343
1344
1345
{ }

CPPQuickFixCollector::~CPPQuickFixCollector()
{ }

1346
1347
1348
1349
1350
1351
TextEditor::ITextEditable *CPPQuickFixCollector::editor() const
{ return _editable; }

int CPPQuickFixCollector::startPosition() const
{ return _editable->position(); }

1352
1353
1354
1355
bool CPPQuickFixCollector::supportsEditor(TextEditor::ITextEditable *editor)
{ return qobject_cast<CPPEditorEditable *>(editor) != 0; }

bool CPPQuickFixCollector::triggersCompletion(TextEditor::ITextEditable *)
1356
{ return false; }
1357
1358
1359
1360

int CPPQuickFixCollector::startCompletion(TextEditor::ITextEditable *editable)
{
    Q_ASSERT(editable != 0);
1361

1362
    _editable = editable;
1363
    _editor = qobject_cast<CPPEditor *>(editable->widget());
1364
1365
1366
1367
    Q_ASSERT(_editor != 0);

    const SemanticInfo info = _editor->semanticInfo();

1368
    if (info.revision != _editor->editorRevision()) {
1369
1370
1371
1372
1373
        // outdated
        qWarning() << "TODO: outdated semantic info, force a reparse.";
        return -1;
    }

1374
    if (info.doc) {
1375
1376
1377
        ASTPath astPath(info.doc);

        const QList<AST *> path = astPath(_editor->textCursor());
Roberto Raggi's avatar
Roberto Raggi committed
1378
1379
        if (path.isEmpty())
            return -1;
1380

Roberto Raggi's avatar
Roberto Raggi committed
1381
1382
1383
1384
1385
1386
        QSharedPointer<RewriteLogicalAndOp> rewriteLogicalAndOp(new RewriteLogicalAndOp());
        QSharedPointer<SplitIfStatementOp> splitIfStatementOp(new SplitIfStatementOp());
        QSharedPointer<MoveDeclarationOutOfIfOp> moveDeclarationOutOfIfOp(new MoveDeclarationOutOfIfOp());
        QSharedPointer<MoveDeclarationOutOfWhileOp> moveDeclarationOutOfWhileOp(new MoveDeclarationOutOfWhileOp());
        QSharedPointer<SplitSimpleDeclarationOp> splitSimpleDeclarationOp(new SplitSimpleDeclarationOp());
        QSharedPointer<AddBracesToIfOp> addBracesToIfOp(new AddBracesToIfOp());
1387
1388
        QSharedPointer<UseInverseOp> useInverseOp(new UseInverseOp());
        QSharedPointer<FlipBinaryOp> flipBinaryOp(new FlipBinaryOp());
1389
        QSharedPointer<WrapStringLiteral> wrapStringLiteral(new WrapStringLiteral());
1390
        QSharedPointer<CStringToNSString> wrapCString(new CStringToNSString());
1391
        QSharedPointer<UseFastStringConcatenation> useFastStringConcat(new UseFastStringConcatenation());
1392

1393
1394
        QList<QuickFixOperationPtr> candidates;
        candidates.append(rewriteLogicalAndOp);
1395
        candidates.append(splitIfStatementOp);
1396
1397
        candidates.append(moveDeclarationOutOfIfOp);
        candidates.append(moveDeclarationOutOfWhileOp);
1398
        candidates.append(splitSimpleDeclarationOp);
1399
        candidates.append(addBracesToIfOp);
1400
1401
        candidates.append(useInverseOp);
        candidates.append(flipBinaryOp);
1402
        candidates.append(wrapStringLiteral);
1403
1404
        if (_editor->mimeType() == CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)
            candidates.append(wrapCString);
1405
        candidates.append(useFastStringConcat);
Roberto Raggi's avatar
Roberto Raggi committed
1406

1407
        QMap<int, QList<QuickFixOperationPtr> > matchedOps;
Roberto Raggi's avatar
Roberto Raggi committed
1408

1409
        foreach (QuickFixOperationPtr op, candidates) {
Roberto Raggi's avatar
Roberto Raggi committed
1410
1411
1412
            op->setSnapshot(info.snapshot);
            op->setDocument(info.doc);
            op->setEditor(_editor);
1413
1414
            op->setTextCursor(_editor->textCursor());
            int priority = op->match(path);
1415
            if (priority != -1)
1416
                matchedOps[priority].append(op);
1417
        }
Roberto Raggi's avatar
Roberto Raggi committed
1418

1419
        QMapIterator<int, QList<QuickFixOperationPtr> > it(matchedOps);
1420
1421
1422
1423
        it.toBack();
        if (it.hasPrevious()) {
            it.previous();

1424
            _quickFixes = it.value();
1425
1426
        }

1427
1428
        if (! _quickFixes.isEmpty())
            return editable->position();
1429
1430
    }

1431
1432
1433
    return -1;
}

1434
void CPPQuickFixCollector::completions(QList<TextEditor::CompletionItem> *quickFixItems)
1435
{
1436
1437
1438
1439
1440
1441
1442
1443
    for (int i = 0; i < _quickFixes.size(); ++i) {
        QuickFixOperationPtr op = _quickFixes.at(i);

        TextEditor::CompletionItem item(this);
        item.text = op->description();
        item.data = QVariant::fromValue(i);
        quickFixItems->append(item);
    }