cppquickfix.cpp 32 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/ASTPath.h>
34
#include <cplusplus/CppDocument.h>
35
#include <cplusplus/ResolveExpression.h>
36

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

Roberto Raggi's avatar
Roberto Raggi committed
50
#include <cppeditor/cpprefactoringchanges.h>
51
#include <cpptools/cpptoolsconstants.h>
52
#include <cpptools/cppmodelmanagerinterface.h>
Roberto Raggi's avatar
Roberto Raggi committed
53
#include <extensionsystem/pluginmanager.h>
54

Robert Loehning's avatar
Robert Loehning committed
55
#include <QtGui/QApplication>
56
#include <QtGui/QTextBlock>
57
58
59

using namespace CppEditor::Internal;
using namespace CPlusPlus;
60
using namespace Utils;
61

62
63
namespace {

64
65
66
67
class CppQuickFixState: public TextEditor::QuickFixState
{
public:
    QList<CPlusPlus::AST *> path;
68
    SemanticInfo info;
69
70
};

71
72
/*
    Rewrite
73
74
75
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
76
*/
77
class UseInverseOp: public CppQuickFixOperation
78
79
{
public:
80
81
    UseInverseOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), binary(0), nested(0), negation(0)
82
83
84
85
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
86
        return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
    }

    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());
125
126
127
128
129
130
131
132
133
134
135
136

        // 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;
        }

137
138
139
        return index;
    }

140
    virtual void createChanges()
141
    {
142
        ChangeSet changes;
143
144
        if (negation) {
            // can't remove parentheses since that might break precedence
145
            changes.remove(range(negation->unary_op_token));
146
        } else if (nested) {
147
            changes.insert(startOf(nested), "!");
148
        } else {
149
150
            changes.insert(startOf(binary), "!(");
            changes.insert(endOf(binary), ")");
151
        }
152
        changes.replace(range(binary->binary_op_token), replacement);
153
        refactoringChanges()->changeFile(fileName(), changes);
154
155
156
157
    }

private:
    BinaryExpressionAST *binary;
158
159
160
    NestedExpressionAST *nested;
    UnaryExpressionAST *negation;

161
162
163
164
165
166
167
168
169
170
    QString replacement;
};

/*
    Rewrite
    a op b

    As
    b flipop a
*/
171
class FlipBinaryOp: public CppQuickFixOperation
172
173
{
public:
174
175
    FlipBinaryOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), binary(0)
176
177
178
179
180
181
    {}


    virtual QString description() const
    {
        if (replacement.isEmpty())
Robert Loehning's avatar
Robert Loehning committed
182
            return QApplication::translate("CppTools::QuickFix", "Swap Operands");
183
        else
Robert Loehning's avatar
Robert Loehning committed
184
            return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    }

    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;
    }

228
    virtual void createChanges()
229
    {
230
231
        ChangeSet changes;

232
        changes.flip(range(binary->left_expression), range(binary->right_expression));
233
        if (! replacement.isEmpty())
234
            changes.replace(range(binary->binary_op_token), replacement);
235

236
        refactoringChanges()->changeFile(fileName(), changes);
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    }

private:
    BinaryExpressionAST *binary;
    QString replacement;
};

/*
    Rewrite
    !a && !b

    As
    !(a || b)
*/
251
class RewriteLogicalAndOp: public CppQuickFixOperation
252
253
{
public:
254
255
    RewriteLogicalAndOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), left(0), right(0), pattern(0)
256
257
258
259
    {}

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

263
    virtual int match(const QList<AST *> &path)
264
    {
265
266
267
268
269
270
271
272
273
274
275
276
        BinaryExpressionAST *expression = 0;

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

        if (! expression)
            return -1;

277
        if (! isCursorOn(expression->binary_op_token))
278
279
            return -1;

280
281
282
283
284
285
286
287
        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)) {
288
            return index;
289
290
        }

291
        return -1;
292
293
    }

294
    virtual void createChanges()
295
    {
296
        ChangeSet changes;
297
298
299
        changes.replace(range(pattern->binary_op_token), QLatin1String("||"));
        changes.remove(range(left->unary_op_token));
        changes.remove(range(right->unary_op_token));
300
301
302
303
304
        const int start = startOf(pattern);
        const int end = endOf(pattern);
        changes.insert(start, QLatin1String("!("));
        changes.insert(end, QLatin1String(")"));

305
        refactoringChanges()->changeFile(fileName(), changes);
306
        refactoringChanges()->reindent(fileName(), range(pattern));
307
308
309
310
311
312
313
314
315
316
    }

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

317
class SplitSimpleDeclarationOp: public CppQuickFixOperation
318
319
{
public:
320
321
    SplitSimpleDeclarationOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), declaration(0)
322
323
324
325
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
326
        return QApplication::translate("CppTools::QuickFix", "Split Declaration");
327
328
329
330
    }

    bool checkDeclaration(SimpleDeclarationAST *declaration) const
    {
331
332
333
        if (! declaration->semicolon_token)
            return false;

334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
        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;
    }

356
    virtual int match(const QList<AST *> &path)
357
358
359
360
361
362
363
364
365
366
367
368
369
370
    {
        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;

371
                    const int cursorPosition = selectionStart();
372
373
374
375
376
377
378

                    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.

379
                    if (core_declarator && isCursorOn(core_declarator))
380
                        return index; // got a core-declarator under the text cursor.
381
382
383
384
385
386
387
388
389
                }

                break;
            }
        }

        return -1;
    }

390
    virtual void createChanges()
391
    {
392
393
        ChangeSet changes;

394
        SpecifierListAST *specifiers = declaration->decl_specifier_list;
395
396
397
        int declSpecifiersStart = startOf(specifiers->firstToken());
        int declSpecifiersEnd = endOf(specifiers->lastToken() - 1);
        int insertPos = endOf(declaration->semicolon_token);
398

399
        DeclaratorAST *prevDeclarator = declaration->declarator_list->value;
400
401
402
403

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

404
            changes.insert(insertPos, QLatin1String("\n"));
405
            changes.copy(declSpecifiersStart, declSpecifiersEnd, insertPos);
406
            changes.insert(insertPos, QLatin1String(" "));
407
            changes.move(range(declarator), insertPos);
408
            changes.insert(insertPos, QLatin1String(";"));
409

410
            const int prevDeclEnd = endOf(prevDeclarator);
411
            changes.remove(prevDeclEnd, startOf(declarator));
412

413
414
            prevDeclarator = declarator;
        }
415

416
        refactoringChanges()->changeFile(fileName(), changes);
417
        refactoringChanges()->reindent(fileName(), range(declaration));
418
419
420
421
422
423
    }

private:
    SimpleDeclarationAST *declaration;
};

424
425
426
427
/*
    Add curly braces to a if statement that doesn't already contain a
    compound statement.
*/
428
class AddBracesToIfOp: public CppQuickFixOperation
429
430
{
public:
431
432
    AddBracesToIfOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), _statement(0)
433
434
435
436
    {}

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

440
    virtual int match(const QList<AST *> &path)
441
442
443
444
    {
        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
445
        if (ifStatement && isCursorOn(ifStatement->if_token)
446
447
448
449
450
451
452
453
454
            && ! 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();
455
456
            if (ifStatement && ifStatement->statement
                && isCursorOn(ifStatement->statement)
457
458
459
460
461
462
463
464
465
466
467
468
                && ! ifStatement->statement->asCompoundStatement()) {
                _statement = ifStatement->statement;
                return index;
            }
        }

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

        return -1;
    }

469
    virtual void createChanges()
470
    {
471
472
473
474
475
476
477
478
        ChangeSet changes;

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

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

479
480
        refactoringChanges()->changeFile(fileName(), changes);
        refactoringChanges()->reindent(fileName(), range(start, end));
481
482
483
484
485
486
487
488
489
490
491
492
493
494
    }

private:
    StatementAST *_statement;
};

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

    With
    Type name = foo;
    if (name) {...}
*/
495
class MoveDeclarationOutOfIfOp: public CppQuickFixOperation
496
497
{
public:
498
499
    MoveDeclarationOutOfIfOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), condition(0), pattern(0), core(0)
500
501
502
503
    {}

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

507
    virtual int match(const QList<AST *> &path)
508
509
510
511
512
513
514
515
516
517
518
519
520
    {
        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;

521
                    if (isCursorOn(core))
522
523
524
525
526
527
528
529
                        return index;
                }
            }
        }

        return -1;
    }

530
    virtual void createChanges()
531
    {
532
        ChangeSet changes;
533

534
        changes.copy(range(core), startOf(condition));
535
536

        int insertPos = startOf(pattern);
537
        changes.move(range(condition), insertPos);
538
539
        changes.insert(insertPos, QLatin1String(";\n"));

540
        refactoringChanges()->changeFile(fileName(), changes);
541
        refactoringChanges()->reindent(fileName(), range(pattern));
542
543
544
545
546
547
548
549
550
551
552
    }

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

553
554
555
556
557
558
559
560
/*
    Replace
    while (Type name = foo()) {...}

    With
    Type name;
    while ((name = foo()) != 0) {...}
*/
561
class MoveDeclarationOutOfWhileOp: public CppQuickFixOperation
562
563
{
public:
564
565
    MoveDeclarationOutOfWhileOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), condition(0), pattern(0), core(0)
566
567
568
569
    {}

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

573
    virtual int match(const QList<AST *> &path)
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
    {
        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;

594
                    if (isCursorOn(core))
595
596
597
598
599
600
601
602
                        return index;
                }
            }
        }

        return -1;
    }

603
    virtual void createChanges()
604
    {
605
        ChangeSet changes;
606

607
608
        changes.insert(startOf(condition), QLatin1String("("));
        changes.insert(endOf(condition), QLatin1String(") != 0"));
609
610

        int insertPos = startOf(pattern);
611
        const int conditionStart = startOf(condition);
612
613
        changes.move(conditionStart, startOf(core), insertPos);
        changes.copy(range(core), insertPos);
614
615
        changes.insert(insertPos, QLatin1String(";\n"));

616
        refactoringChanges()->changeFile(fileName(), changes);
617
        refactoringChanges()->reindent(fileName(), range(pattern));
618
619
620
621
622
623
624
625
626
627
628
    }

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

Roberto Raggi's avatar
Roberto Raggi committed
629
630
631
632
633
634
635
636
637
638
/*
  Replace
     if (something && something_else) {
     }

  with
     if (something) {
        if (something_else) {
        }
     }
Roberto Raggi's avatar
Roberto Raggi committed
639
640
641
642
643
644
645
646
647
648

  and
    if (something || something_else)
      x;

  with
    if (something)
      x;
    else if (something_else)
      x;
Roberto Raggi's avatar
Roberto Raggi committed
649
*/
650
class SplitIfStatementOp: public CppQuickFixOperation
Roberto Raggi's avatar
Roberto Raggi committed
651
652
{
public:
653
654
    SplitIfStatementOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), condition(0), pattern(0)
Roberto Raggi's avatar
Roberto Raggi committed
655
656
657
658
    {}

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

662
    virtual int match(const QList<AST *> &path)
Roberto Raggi's avatar
Roberto Raggi committed
663
    {
664
        pattern = 0;
Roberto Raggi's avatar
Roberto Raggi committed
665

666
667
668
669
670
671
672
673
674
        int index = path.size() - 1;
        for (; index != -1; --index) {
            AST *node = path.at(index);
            if (IfStatementAST *stmt = node->asIfStatement()) {
                pattern = stmt;
                break;
            }
        }

675
        if (! pattern || ! pattern->statement)
676
677
            return -1;

678
        unsigned splitKind = 0;
679
680
681
682
683
684
685
        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);
686
687
688
689
690
691
692
693
694
695

            // 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()) {
696
697
                return -1;
            }
698
699
700

            if (isCursorOn(condition->binary_op_token))
                return index;
701
702
703
        }

        return -1;
Roberto Raggi's avatar
Roberto Raggi committed
704
705
    }

706
    virtual void createChanges()
Roberto Raggi's avatar
Roberto Raggi committed
707
    {
708
        Token binaryToken = tokenAt(condition->binary_op_token);
Roberto Raggi's avatar
Roberto Raggi committed
709

710
        if (binaryToken.is(T_AMPER_AMPER))
Roberto Raggi's avatar
Roberto Raggi committed
711
712
713
714
715
716
717
            splitAndCondition();
        else
            splitOrCondition();
    }

    void splitAndCondition()
    {
718
        ChangeSet changes;
Roberto Raggi's avatar
Roberto Raggi committed
719

720
        int startPos = startOf(pattern);
721
        changes.insert(startPos, QLatin1String("if ("));
722
        changes.move(range(condition->left_expression), startPos);
723
724
725
        changes.insert(startPos, QLatin1String(") {\n"));

        const int lExprEnd = endOf(condition->left_expression);
726
        changes.remove(lExprEnd, startOf(condition->right_expression));
727
728
        changes.insert(endOf(pattern), QLatin1String("\n}"));

729
        refactoringChanges()->changeFile(fileName(), changes);
730
        refactoringChanges()->reindent(fileName(), range(pattern));
Roberto Raggi's avatar
Roberto Raggi committed
731
732
    }

Roberto Raggi's avatar
Roberto Raggi committed
733
734
    void splitOrCondition()
    {
735
736
        ChangeSet changes;

Roberto Raggi's avatar
Roberto Raggi committed
737
738
739
        StatementAST *ifTrueStatement = pattern->statement;
        CompoundStatementAST *compoundStatement = ifTrueStatement->asCompoundStatement();

740
        int insertPos = endOf(ifTrueStatement);
Roberto Raggi's avatar
Roberto Raggi committed
741
        if (compoundStatement)
742
            changes.insert(insertPos, QLatin1String(" "));
Roberto Raggi's avatar
Roberto Raggi committed
743
        else
744
745
746
747
            changes.insert(insertPos, QLatin1String("\n"));
        changes.insert(insertPos, QLatin1String("else if ("));

        const int rExprStart = startOf(condition->right_expression);
748
        changes.move(rExprStart, startOf(pattern->rparen_token), insertPos);
749
        changes.insert(insertPos, QLatin1String(")"));
750

751
        const int rParenEnd = endOf(pattern->rparen_token);
752
        changes.copy(rParenEnd, endOf(pattern->statement), insertPos);
753
754

        const int lExprEnd = endOf(condition->left_expression);
755
        changes.remove(lExprEnd, startOf(condition->right_expression));
756

757
        refactoringChanges()->changeFile(fileName(), changes);
758
        refactoringChanges()->reindent(fileName(), range(pattern));
Roberto Raggi's avatar
Roberto Raggi committed
759
760
    }

Roberto Raggi's avatar
Roberto Raggi committed
761
762
763
764
private:
    BinaryExpressionAST *condition;
    IfStatementAST *pattern;
};
765

766
767
768
769
770
771
/*
  Replace
    "abcd"
  With
    QLatin1String("abcd")
*/
772
class WrapStringLiteral: public CppQuickFixOperation
773
774
{
public:
775
776
    WrapStringLiteral(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), stringLiteral(0), isObjCStringLiteral(false)
777
778
779
780
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
781
        return QApplication::translate("CppTools::QuickFix", "Enclose in QLatin1String(...)");
782
783
784
785
    }

    virtual int match(const QList<AST *> &path)
    {
786
787
788
        stringLiteral = 0;
        isObjCStringLiteral = false;

789
        if (path.isEmpty())
790
            return -1; // nothing to do
791

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

794
        if (! stringLiteral)
795
796
            return -1;

797
798
799
800
801
        else if (path.size() > 1) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
                    if (SimpleNameAST *functionName = call->base_expression->asSimpleName()) {
                        const QByteArray id(tokenAt(functionName->identifier_token).identifier->chars());
802

803
804
805
806
807
                        if (id == "QLatin1String" || id == "QLatin1Literal")
                            return -1; // skip it
                    }
                }
            }
808
809
        }

810
811
        isObjCStringLiteral = charAt(startOf(stringLiteral)) == QLatin1Char('@');
        return path.size() - 1; // very high priority
812
813
    }

814
    virtual void createChanges()
815
    {
816
817
        ChangeSet changes;

818
819
820
821
        const int startPos = startOf(stringLiteral);
        const QLatin1String replacement("QLatin1String(");

        if (isObjCStringLiteral)
822
            changes.replace(startPos, startPos + 1, replacement);
823
        else
824
            changes.insert(startPos, replacement);
825

826
827
        changes.insert(endOf(stringLiteral), ")");

828
        refactoringChanges()->changeFile(fileName(), changes);
829
830
831
832
    }

private:
    StringLiteralAST *stringLiteral;
833
    bool isObjCStringLiteral;
834
835
};

836
class CStringToNSString: public CppQuickFixOperation
837
838
{
public:
839
    CStringToNSString(TextEditor::BaseTextEditor *editor)
840
841
842
        : CppQuickFixOperation(editor)
        , stringLiteral(0)
        , qlatin1Call(0)
843
844
845
    {}

    virtual QString description() const
Robert Loehning's avatar
Robert Loehning committed
846
847
848
    {
        return QApplication::translate("CppTools::QuickFix", "Convert to Objective-C String Literal");
    }
849
850
851

    virtual int match(const QList<AST *> &path)
    {
852
853
854
        stringLiteral = 0;
        qlatin1Call = 0;

855
        if (path.isEmpty())
856
            return -1; // nothing to do
857

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

860
        if (! stringLiteral)
861
862
            return -1;

863
864
        else if (charAt(startOf(stringLiteral)) == QLatin1Char('@'))
            return -1; // it's already an objc string literal.
865

866
867
868
869
870
        else if (path.size() > 1) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
                    if (SimpleNameAST *functionName = call->base_expression->asSimpleName()) {
                        const QByteArray id(tokenAt(functionName->identifier_token).identifier->chars());
871

872
873
874
875
                        if (id == "QLatin1String" || id == "QLatin1Literal")
                            qlatin1Call = call;
                    }
                }
876
877
878
            }
        }

879
        return path.size() - 1; // very high priority
880
881
    }

882
    virtual void createChanges()
883
    {
884
885
        ChangeSet changes;

886
        if (qlatin1Call) {
887
888
            changes.replace(startOf(qlatin1Call), startOf(stringLiteral), QLatin1String("@"));
            changes.remove(endOf(stringLiteral), endOf(qlatin1Call));
889
        } else {
890
            changes.insert(startOf(stringLiteral), "@");
891
        }
892

893
        refactoringChanges()->changeFile(fileName(), changes);
894
895
896
897
    }

private:
    StringLiteralAST *stringLiteral;
898
    CallAST *qlatin1Call;
899
900
};

901
902
903
} // end of anonymous namespace


904
CppQuickFixOperation::CppQuickFixOperation(TextEditor::BaseTextEditor *editor)
905
906
907
    : TextEditor::QuickFixOperation(editor)
    , _refactoringChanges(0)
    , _topLevelNode(0)
908
909
{ }

910
911
CppQuickFixOperation::~CppQuickFixOperation()
{
912
913
    if (_refactoringChanges)
        delete _refactoringChanges;
914
}
Roberto Raggi's avatar
Roberto Raggi committed
915

916
int CppQuickFixOperation::match(TextEditor::QuickFixState *state)
917
{
918
    CppQuickFixState *s = static_cast<CppQuickFixState *>(state);
919
    _document = s->info.doc;
920
921
    if (_refactoringChanges)
        delete _refactoringChanges;
922
    _refactoringChanges = new CppRefactoringChanges(s->info.snapshot);
923
    return match(s->path);
924
}
Roberto Raggi's avatar
Roberto Raggi committed
925

926
927
928
Utils::ChangeSet::Range CppQuickFixOperation::range(unsigned tokenIndex) const
{
    const CPlusPlus::Token &token = tokenAt(tokenIndex);
929
930
931
932
    unsigned line, column;
    _document->translationUnit()->getPosition(token.begin(), &line, &column);
    const int start = editor()->document()->findBlockByNumber(line - 1).position() + column - 1;
    return Utils::ChangeSet::Range(start, start + token.length());
933
934
935
936
937
938
939
}

Utils::ChangeSet::Range CppQuickFixOperation::range(CPlusPlus::AST *ast) const
{
    return Utils::ChangeSet::Range(startOf(ast), endOf(ast));
}

940
941
942
QString CppQuickFixOperation::fileName() const
{ return document()->fileName(); }

943
944
void CppQuickFixOperation::apply()
{
945
    refactoringChanges()->apply();
946
947
}

948
CppEditor::CppRefactoringChanges *CppQuickFixOperation::refactoringChanges() const
949
950
{ return _refactoringChanges; }

951
952
Document::Ptr CppQuickFixOperation::document() const
{ return _document; }
953

954
const Snapshot &CppQuickFixOperation::snapshot() const
955
956
957
{
    return _refactoringChanges->snapshot();
}
958

959
const CPlusPlus::Token &CppQuickFixOperation::tokenAt(unsigned index) const
Roberto Raggi's avatar
Roberto Raggi committed
960
{ return _document->translationUnit()->tokenAt(index); }
961

962
int CppQuickFixOperation::startOf(unsigned index) const
963
{
964
    unsigned line, column;
Roberto Raggi's avatar
Roberto Raggi committed
965
    _document->translationUnit()->getPosition(tokenAt(index).begin(), &line, &column);
966
    return editor()->document()->findBlockByNumber(line - 1).position() + column - 1;
967
}
968

969
int CppQuickFixOperation::startOf(const CPlusPlus::AST *ast) const
970
971
972
973
{
    return startOf(ast->firstToken());
}

974
int CppQuickFixOperation::endOf(unsigned index) const
975
976
{
    unsigned line, column;
Roberto Raggi's avatar
Roberto Raggi committed
977
    _document->translationUnit()->getPosition(tokenAt(index).end(), &line, &column);
978
    return editor()->document()->findBlockByNumber(line - 1).position() + column - 1;
979
980
}

981
int CppQuickFixOperation::endOf(const CPlusPlus::AST *ast) const
982
{
983
984
985
986
    if (unsigned end = ast->lastToken())
        return endOf(end - 1);
    else
        return 0;
987
988
}

989
void CppQuickFixOperation::startAndEndOf(unsigned index, int *start, int *end) const
990
991
992
993
{
    unsigned line, column;
    CPlusPlus::Token token(tokenAt(index));
    _document->translationUnit()->getPosition(token.begin(), &line, &column);
994
    *start = editor()->document()->findBlockByNumber(line - 1).position() + column - 1;
995
996
997
    *end = *start + token.length();
}

998
bool CppQuickFixOperation::isCursorOn(unsigned tokenIndex) const
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
{
    QTextCursor tc = textCursor();
    int cursorBegin = tc.selectionStart();

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

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

    return false;
}

1012
bool CppQuickFixOperation::isCursorOn(const CPlusPlus::AST *ast) const
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
{
    QTextCursor tc = textCursor();
    int cursorBegin = tc.selectionStart();

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

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

    return false;
}

1026
QString CppQuickFixOperation::textOf(const AST *ast) const
1027
{
1028
    return textOf(startOf(ast), endOf(ast));
1029
1030
}

1031
CppQuickFixCollector::CppQuickFixCollector()
1032
1033
{
}
1034

1035
CppQuickFixCollector::~CppQuickFixCollector()
1036
{
1037
}
1038

1039
1040
1041
1042
1043
bool CppQuickFixCollector::supportsEditor(TextEditor::ITextEditable *editor)
{
    return CppTools::CppModelManagerInterface::instance()->isCppEditor(editor);
}

1044
1045
1046
1047
TextEditor::QuickFixState *CppQuickFixCollector::initializeCompletion(TextEditor::ITextEditable *editable)
{
    if (CPPEditor *editor = qobject_cast<CPPEditor *>(editable->widget())) {
        const SemanticInfo info = editor->semanticInfo();
1048

1049
1050
1051
1052
        if (info.revision != editor->editorRevision()) {
            // outdated
            qWarning() << "TODO: outdated semantic info, force a reparse.";
            return 0;
1053
        }
Roberto Raggi's avatar
Roberto Raggi committed
1054

1055
1056
        if (info.doc) {
            ASTPath astPath(info.doc);
1057

1058
1059
1060
1061
1062
1063
1064
            const QList<AST *> path = astPath(editor->textCursor());
            if (! path.isEmpty()) {
                CppQuickFixState *state = new CppQuickFixState;
                state->path = path;
                state->info = info;
                return state;
            }
1065
        }
1066
1067
    }

1068
    return 0;
1069
1070
}

Roberto Raggi's avatar
Roberto Raggi committed
1071
1072
CppQuickFixFactory::CppQuickFixFactory(QObject *parent)
    : TextEditor::IQuickFixFactory(parent)
1073
{
Roberto Raggi's avatar
Roberto Raggi committed
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
}

CppQuickFixFactory::~CppQuickFixFactory()
{
}

QList<TextEditor::QuickFixOperation::Ptr> CppQuickFixFactory::quickFixOperations(TextEditor::BaseTextEditor *editor)
{
    QList<TextEditor::QuickFixOperation::Ptr> quickFixOperations;