cppquickfix.cpp 57.6 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
#include "cppdeclfromdef.h"
33

34
#include <cplusplus/ASTPath.h>
35
#include <cplusplus/CppDocument.h>
36
#include <cplusplus/ResolveExpression.h>
Tobias Hunger's avatar
Tobias Hunger committed
37
#include <cplusplus/Overview.h>
38
#include <cplusplus/TypeOfExpression.h>
39
#include <cplusplus/DependencyTable.h>
Roberto Raggi's avatar
Roberto Raggi committed
40
#include <cplusplus/CppRewriter.h>
41

42
#include <TranslationUnit.h>
43
44
#include <ASTVisitor.h>
#include <AST.h>
45
46
#include <ASTPatternBuilder.h>
#include <ASTMatcher.h>
47
#include <Token.h>
48
49
50
51
52
#include <Type.h>
#include <CoreTypes.h>
#include <Symbol.h>
#include <Symbols.h>
#include <Name.h>
Tobias Hunger's avatar
Tobias Hunger committed
53
#include <Names.h>
54
#include <Literals.h>
55

56
#include <cppeditor/cppeditor.h>
Roberto Raggi's avatar
Roberto Raggi committed
57
#include <cppeditor/cpprefactoringchanges.h>
58
#include <cpptools/cpptoolsconstants.h>
59
#include <cpptools/cppmodelmanagerinterface.h>
Roberto Raggi's avatar
Roberto Raggi committed
60
#include <extensionsystem/pluginmanager.h>
61

Robert Loehning's avatar
Robert Loehning committed
62
#include <QtGui/QApplication>
63
#include <QtGui/QTextBlock>
64
65
66

using namespace CppEditor::Internal;
using namespace CPlusPlus;
67
using namespace Utils;
68

69
70
namespace {

71
72
73
74
class CppQuickFixState: public TextEditor::QuickFixState
{
public:
    QList<CPlusPlus::AST *> path;
75
    Snapshot snapshot;
76
    SemanticInfo info;
77
78
};

79
80
/*
    Rewrite
81
82
83
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
84
*/
85
class UseInverseOp: public CppQuickFixOperation
86
87
{
public:
88
89
    UseInverseOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), binary(0), nested(0), negation(0)
90
91
92
93
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
94
        return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    }

    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());
133
134
135
136
137
138
139
140
141
142
143
144

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

145
146
147
        return index;
    }

148
    virtual void createChanges()
149
    {
150
        ChangeSet changes;
151
152
        if (negation) {
            // can't remove parentheses since that might break precedence
153
            changes.remove(range(negation->unary_op_token));
154
        } else if (nested) {
155
            changes.insert(startOf(nested), "!");
156
        } else {
157
158
            changes.insert(startOf(binary), "!(");
            changes.insert(endOf(binary), ")");
159
        }
160
        changes.replace(range(binary->binary_op_token), replacement);
161
        refactoringChanges()->changeFile(fileName(), changes);
162
163
164
165
    }

private:
    BinaryExpressionAST *binary;
166
167
168
    NestedExpressionAST *nested;
    UnaryExpressionAST *negation;

169
170
171
172
173
174
175
176
177
178
    QString replacement;
};

/*
    Rewrite
    a op b

    As
    b flipop a
*/
179
class FlipBinaryOp: public CppQuickFixOperation
180
181
{
public:
182
183
    FlipBinaryOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), binary(0)
184
185
186
187
188
189
    {}


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

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

236
    virtual void createChanges()
237
    {
238
239
        ChangeSet changes;

240
        changes.flip(range(binary->left_expression), range(binary->right_expression));
241
        if (! replacement.isEmpty())
242
            changes.replace(range(binary->binary_op_token), replacement);
243

244
        refactoringChanges()->changeFile(fileName(), changes);
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    }

private:
    BinaryExpressionAST *binary;
    QString replacement;
};

/*
    Rewrite
    !a && !b

    As
    !(a || b)
*/
259
class RewriteLogicalAndOp: public CppQuickFixOperation
260
261
{
public:
262
263
    RewriteLogicalAndOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), left(0), right(0), pattern(0)
264
265
266
267
    {}

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

271
    virtual int match(const QList<AST *> &path)
272
    {
273
274
275
276
277
278
279
280
281
282
283
284
        BinaryExpressionAST *expression = 0;

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

        if (! expression)
            return -1;

285
        if (! isCursorOn(expression->binary_op_token))
286
287
            return -1;

288
289
290
291
292
293
294
295
        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)) {
296
            return index;
297
298
        }

299
        return -1;
300
301
    }

302
    virtual void createChanges()
303
    {
304
        ChangeSet changes;
305
306
307
        changes.replace(range(pattern->binary_op_token), QLatin1String("||"));
        changes.remove(range(left->unary_op_token));
        changes.remove(range(right->unary_op_token));
308
309
310
311
312
        const int start = startOf(pattern);
        const int end = endOf(pattern);
        changes.insert(start, QLatin1String("!("));
        changes.insert(end, QLatin1String(")"));

313
        refactoringChanges()->changeFile(fileName(), changes);
314
        refactoringChanges()->reindent(fileName(), range(pattern));
315
316
317
318
319
320
321
322
323
324
    }

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

325
class SplitSimpleDeclarationOp: public CppQuickFixOperation
326
327
{
public:
328
329
    SplitSimpleDeclarationOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), declaration(0)
330
331
332
333
    {}

    virtual QString description() const
    {
Robert Loehning's avatar
Robert Loehning committed
334
        return QApplication::translate("CppTools::QuickFix", "Split Declaration");
335
336
337
338
    }

    bool checkDeclaration(SimpleDeclarationAST *declaration) const
    {
339
340
341
        if (! declaration->semicolon_token)
            return false;

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
        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;
    }

364
    virtual int match(const QList<AST *> &path)
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    {
        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;

379
                    const int cursorPosition = selectionStart();
380
381
382
383
384
385
386

                    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.

387
                    if (core_declarator && isCursorOn(core_declarator))
388
                        return index; // got a core-declarator under the text cursor.
389
390
391
392
393
394
395
396
397
                }

                break;
            }
        }

        return -1;
    }

398
    virtual void createChanges()
399
    {
400
401
        ChangeSet changes;

402
        SpecifierListAST *specifiers = declaration->decl_specifier_list;
403
404
405
        int declSpecifiersStart = startOf(specifiers->firstToken());
        int declSpecifiersEnd = endOf(specifiers->lastToken() - 1);
        int insertPos = endOf(declaration->semicolon_token);
406

407
        DeclaratorAST *prevDeclarator = declaration->declarator_list->value;
408
409
410
411

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

412
            changes.insert(insertPos, QLatin1String("\n"));
413
            changes.copy(declSpecifiersStart, declSpecifiersEnd, insertPos);
414
            changes.insert(insertPos, QLatin1String(" "));
415
            changes.move(range(declarator), insertPos);
416
            changes.insert(insertPos, QLatin1String(";"));
417

418
            const int prevDeclEnd = endOf(prevDeclarator);
419
            changes.remove(prevDeclEnd, startOf(declarator));
420

421
422
            prevDeclarator = declarator;
        }
423

424
        refactoringChanges()->changeFile(fileName(), changes);
425
        refactoringChanges()->reindent(fileName(), range(declaration));
426
427
428
429
430
431
    }

private:
    SimpleDeclarationAST *declaration;
};

432
433
434
435
/*
    Add curly braces to a if statement that doesn't already contain a
    compound statement.
*/
436
class AddBracesToIfOp: public CppQuickFixOperation
437
438
{
public:
439
440
    AddBracesToIfOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), _statement(0)
441
442
443
444
    {}

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

448
    virtual int match(const QList<AST *> &path)
449
450
451
452
    {
        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
Roberto Raggi's avatar
Roberto Raggi committed
453
        if (ifStatement && isCursorOn(ifStatement->if_token) && ifStatement->statement
454
455
456
457
458
459
460
461
462
            && ! 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();
463
464
            if (ifStatement && ifStatement->statement
                && isCursorOn(ifStatement->statement)
465
466
467
468
469
470
471
472
473
474
475
476
                && ! ifStatement->statement->asCompoundStatement()) {
                _statement = ifStatement->statement;
                return index;
            }
        }

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

        return -1;
    }

477
    virtual void createChanges()
478
    {
479
480
481
482
483
484
485
486
        ChangeSet changes;

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

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

487
488
        refactoringChanges()->changeFile(fileName(), changes);
        refactoringChanges()->reindent(fileName(), range(start, end));
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    }

private:
    StatementAST *_statement;
};

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

    With
    Type name = foo;
    if (name) {...}
*/
503
class MoveDeclarationOutOfIfOp: public CppQuickFixOperation
504
505
{
public:
506
507
    MoveDeclarationOutOfIfOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), condition(0), pattern(0), core(0)
508
509
510
511
    {}

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

515
    virtual int match(const QList<AST *> &path)
516
517
518
519
520
521
522
523
524
525
526
527
528
    {
        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;

529
                    if (isCursorOn(core))
530
531
532
533
534
535
536
537
                        return index;
                }
            }
        }

        return -1;
    }

538
    virtual void createChanges()
539
    {
540
        ChangeSet changes;
541

542
        changes.copy(range(core), startOf(condition));
543
544

        int insertPos = startOf(pattern);
545
        changes.move(range(condition), insertPos);
546
547
        changes.insert(insertPos, QLatin1String(";\n"));

548
        refactoringChanges()->changeFile(fileName(), changes);
549
        refactoringChanges()->reindent(fileName(), range(pattern));
550
551
552
553
554
555
556
557
558
559
560
    }

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

561
562
563
564
565
566
567
568
/*
    Replace
    while (Type name = foo()) {...}

    With
    Type name;
    while ((name = foo()) != 0) {...}
*/
569
class MoveDeclarationOutOfWhileOp: public CppQuickFixOperation
570
571
{
public:
572
573
    MoveDeclarationOutOfWhileOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), condition(0), pattern(0), core(0)
574
575
576
577
    {}

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

581
    virtual int match(const QList<AST *> &path)
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
    {
        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;

602
                    if (isCursorOn(core))
603
604
605
606
607
608
609
610
                        return index;
                }
            }
        }

        return -1;
    }

611
    virtual void createChanges()
612
    {
613
        ChangeSet changes;
614

615
616
        changes.insert(startOf(condition), QLatin1String("("));
        changes.insert(endOf(condition), QLatin1String(") != 0"));
617
618

        int insertPos = startOf(pattern);
619
        const int conditionStart = startOf(condition);
620
621
        changes.move(conditionStart, startOf(core), insertPos);
        changes.copy(range(core), insertPos);
622
623
        changes.insert(insertPos, QLatin1String(";\n"));

624
        refactoringChanges()->changeFile(fileName(), changes);
625
        refactoringChanges()->reindent(fileName(), range(pattern));
626
627
628
629
630
631
632
633
634
635
636
    }

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

Roberto Raggi's avatar
Roberto Raggi committed
637
638
639
640
641
642
643
644
645
646
/*
  Replace
     if (something && something_else) {
     }

  with
     if (something) {
        if (something_else) {
        }
     }
Roberto Raggi's avatar
Roberto Raggi committed
647
648
649
650
651
652
653
654
655
656

  and
    if (something || something_else)
      x;

  with
    if (something)
      x;
    else if (something_else)
      x;
Roberto Raggi's avatar
Roberto Raggi committed
657
*/
658
class SplitIfStatementOp: public CppQuickFixOperation
Roberto Raggi's avatar
Roberto Raggi committed
659
660
{
public:
661
662
    SplitIfStatementOp(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), condition(0), pattern(0)
Roberto Raggi's avatar
Roberto Raggi committed
663
664
665
666
    {}

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

670
    virtual int match(const QList<AST *> &path)
Roberto Raggi's avatar
Roberto Raggi committed
671
    {
672
        pattern = 0;
Roberto Raggi's avatar
Roberto Raggi committed
673

674
675
676
677
678
679
680
681
682
        int index = path.size() - 1;
        for (; index != -1; --index) {
            AST *node = path.at(index);
            if (IfStatementAST *stmt = node->asIfStatement()) {
                pattern = stmt;
                break;
            }
        }

683
        if (! pattern || ! pattern->statement)
684
685
            return -1;

686
        unsigned splitKind = 0;
687
688
689
690
691
692
693
        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);
694
695
696
697
698
699
700
701
702
703

            // 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()) {
704
705
                return -1;
            }
706
707
708

            if (isCursorOn(condition->binary_op_token))
                return index;
709
710
711
        }

        return -1;
Roberto Raggi's avatar
Roberto Raggi committed
712
713
    }

714
    virtual void createChanges()
Roberto Raggi's avatar
Roberto Raggi committed
715
    {
716
        Token binaryToken = tokenAt(condition->binary_op_token);
Roberto Raggi's avatar
Roberto Raggi committed
717

718
        if (binaryToken.is(T_AMPER_AMPER))
Roberto Raggi's avatar
Roberto Raggi committed
719
720
721
722
723
724
725
            splitAndCondition();
        else
            splitOrCondition();
    }

    void splitAndCondition()
    {
726
        ChangeSet changes;
Roberto Raggi's avatar
Roberto Raggi committed
727

728
        int startPos = startOf(pattern);
729
        changes.insert(startPos, QLatin1String("if ("));
730
        changes.move(range(condition->left_expression), startPos);
731
732
733
        changes.insert(startPos, QLatin1String(") {\n"));

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

737
        refactoringChanges()->changeFile(fileName(), changes);
738
        refactoringChanges()->reindent(fileName(), range(pattern));
Roberto Raggi's avatar
Roberto Raggi committed
739
740
    }

Roberto Raggi's avatar
Roberto Raggi committed
741
742
    void splitOrCondition()
    {
743
744
        ChangeSet changes;

Roberto Raggi's avatar
Roberto Raggi committed
745
746
747
        StatementAST *ifTrueStatement = pattern->statement;
        CompoundStatementAST *compoundStatement = ifTrueStatement->asCompoundStatement();

748
        int insertPos = endOf(ifTrueStatement);
Roberto Raggi's avatar
Roberto Raggi committed
749
        if (compoundStatement)
750
            changes.insert(insertPos, QLatin1String(" "));
Roberto Raggi's avatar
Roberto Raggi committed
751
        else
752
753
754
755
            changes.insert(insertPos, QLatin1String("\n"));
        changes.insert(insertPos, QLatin1String("else if ("));

        const int rExprStart = startOf(condition->right_expression);
756
        changes.move(rExprStart, startOf(pattern->rparen_token), insertPos);
757
        changes.insert(insertPos, QLatin1String(")"));
758

759
        const int rParenEnd = endOf(pattern->rparen_token);
760
        changes.copy(rParenEnd, endOf(pattern->statement), insertPos);
761
762

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

765
        refactoringChanges()->changeFile(fileName(), changes);
766
        refactoringChanges()->reindent(fileName(), range(pattern));
Roberto Raggi's avatar
Roberto Raggi committed
767
768
    }

Roberto Raggi's avatar
Roberto Raggi committed
769
770
771
772
private:
    BinaryExpressionAST *condition;
    IfStatementAST *pattern;
};
773

774
775
776
777
778
779
/*
  Replace
    "abcd"
  With
    QLatin1String("abcd")
*/
780
class WrapStringLiteral: public CppQuickFixOperation
781
782
{
public:
783
    WrapStringLiteral(TextEditor::BaseTextEditor *editor)
con's avatar
con committed
784
        : CppQuickFixOperation(editor), literal(0), type(TypeNone)
785
786
    {}

con's avatar
con committed
787
788
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

789
790
    virtual QString description() const
    {
con's avatar
con committed
791
792
        if (type == TypeChar)
            return QApplication::translate("CppTools::QuickFix", "Enclose in QLatin1Char(...)");
Robert Loehning's avatar
Robert Loehning committed
793
        return QApplication::translate("CppTools::QuickFix", "Enclose in QLatin1String(...)");
794
795
796
797
    }

    virtual int match(const QList<AST *> &path)
    {
con's avatar
con committed
798
799
        literal = 0;
        type = TypeNone;
800

801
        if (path.isEmpty())
802
            return -1; // nothing to do
803

con's avatar
con committed
804
        literal = path.last()->asStringLiteral();
805

con's avatar
con committed
806
807
808
809
810
811
812
813
814
        if (! literal) {
            literal = path.last()->asNumericLiteral();
            if (!literal || !tokenAt(literal->asNumericLiteral()->literal_token).is(T_CHAR_LITERAL))
                return -1;
            else
                type = TypeChar;
        } else {
            type = TypeString;
        }
815

con's avatar
con committed
816
        if (path.size() > 1) {
817
818
819
820
            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());
821

Tobias Hunger's avatar
Tobias Hunger committed
822
823
                        if (id == "QT_TRANSLATE_NOOP" || id == "tr" || id == "trUtf8"
                                || (type == TypeString && (id == "QLatin1String" || id == "QLatin1Literal"))
con's avatar
con committed
824
                                || (type == TypeChar && id == "QLatin1Char"))
825
826
827
828
                            return -1; // skip it
                    }
                }
            }
829
830
        }

con's avatar
con committed
831
832
833
834
        if (type == TypeString) {
            if (charAt(startOf(literal)) == QLatin1Char('@'))
                type = TypeObjCString;
        }
835
        return path.size() - 1; // very high priority
836
837
    }

838
    virtual void createChanges()
839
    {
840
841
        ChangeSet changes;

con's avatar
con committed
842
843
844
        const int startPos = startOf(literal);
        QLatin1String replacement = (type == TypeChar ? QLatin1String("QLatin1Char(")
            : QLatin1String("QLatin1String("));
845

con's avatar
con committed
846
        if (type == TypeObjCString)
847
            changes.replace(startPos, startPos + 1, replacement);
848
        else
849
            changes.insert(startPos, replacement);
850

con's avatar
con committed
851
        changes.insert(endOf(literal), ")");
852

853
        refactoringChanges()->changeFile(fileName(), changes);
854
855
856
    }

private:
con's avatar
con committed
857
858
    ExpressionAST *literal;
    Type type;
859
860
};

Tobias Hunger's avatar
Tobias Hunger committed
861
862
863
864
865
/*
  Replace
    "abcd"
  With
    tr("abcd") or
Tobias Hunger's avatar
Tobias Hunger committed
866
867
    QCoreApplication::translate("CONTEXT", "abcd") or
    QT_TRANSLATE_NOOP("GLOBAL", "abcd")
Tobias Hunger's avatar
Tobias Hunger committed
868
869
870
871
872
873
874
875
*/
class TranslateStringLiteral: public CppQuickFixOperation
{
public:
    TranslateStringLiteral(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), m_literal(0)
    { }

Tobias Hunger's avatar
Tobias Hunger committed
876
    enum TranslationOption { unknown, useTr, useQCoreApplicationTranslate, useMacro };
Tobias Hunger's avatar
Tobias Hunger committed
877
878
879
880
881
882
883
884
885
886
887
888
889
890

    virtual QString description() const
    {
        return QApplication::translate("CppTools::QuickFix", "Mark as translateable");
    }

    virtual int match(const QList<AST *> &path)
    {
        // Initialize
        m_literal = 0;
        m_option = unknown;
        m_context.clear();

        if (path.isEmpty())
Tobias Hunger's avatar
Tobias Hunger committed
891
            return -1;
Tobias Hunger's avatar
Tobias Hunger committed
892
893
894

        m_literal = path.last()->asStringLiteral();
        if (!m_literal)
Tobias Hunger's avatar
Tobias Hunger committed
895
            return -1; // No string, nothing to do
Tobias Hunger's avatar
Tobias Hunger committed
896

Tobias Hunger's avatar
Tobias Hunger committed
897
898
        // Do we already have a translation markup?
        if (path.size() >= 2) {
Tobias Hunger's avatar
Tobias Hunger committed
899
900
901
902
903
904
            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());

                        if (id == "tr" || id == "trUtf8"
Tobias Hunger's avatar
Tobias Hunger committed
905
906
907
                                || id == "translate"
                                || id == "QT_TRANSLATE_NOOP"
                                || id == "QLatin1String" || id == "QLatin1Literal")
Tobias Hunger's avatar
Tobias Hunger committed
908
909
910
911
                            return -1; // skip it
                    }
                }
            }
Tobias Hunger's avatar
Tobias Hunger committed
912
        }
913

Roberto Raggi's avatar
Roberto Raggi committed
914
        QSharedPointer<Control> control = context().control();
Tobias Hunger's avatar
Tobias Hunger committed
915
916
917
918
919
920
921
        const Name *trName = control->nameId(control->findOrInsertIdentifier("tr"));

        // 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;
Roberto Raggi's avatar
Roberto Raggi committed
922
                ClassOrNamespace *b = context().lookupType(function);
Tobias Hunger's avatar
Tobias Hunger committed
923
924
                if (b) {
                    // Do we have a tr method?
925
926
                    foreach(const LookupItem &r, b->find(trName)) {
                        Symbol *s = r.declaration();
Tobias Hunger's avatar
Tobias Hunger committed
927
928
929
930
931
                        if (s->type()->isFunctionType()) {
                            m_option = useTr;
                            // no context required for tr
                            return path.size() - 1;
                        }
Tobias Hunger's avatar
Tobias Hunger committed
932
933
                    }
                }
Tobias Hunger's avatar
Tobias Hunger committed
934
935
936
                // We need to do a QCA::translate, so we need a context.
                // Use fully qualified class name:
                Overview oo;
937
                foreach (const Name *n, LookupContext::path(function)) {
Tobias Hunger's avatar
Tobias Hunger committed
938
939
940
941
942
943
944
945
946
                    if (!m_context.isEmpty())
                        m_context.append(QLatin1String("::"));
                    m_context.append(oo.prettyName(n));
                }
                // ... or global if none available!
                if (m_context.isEmpty())
                    m_context = QLatin1String("GLOBAL");
                m_option = useQCoreApplicationTranslate;
                return path.size() - 1;
Tobias Hunger's avatar
Tobias Hunger committed
947
948
949
            }
        }

Tobias Hunger's avatar
Tobias Hunger committed
950
951
952
953
        // We need to use Q_TRANSLATE_NOOP
        m_context = QLatin1String("GLOBAL");
        m_option = useMacro;
        return path.size() - 1;
Tobias Hunger's avatar
Tobias Hunger committed
954
955
956
957
958
959
960
    }

    virtual void createChanges()
    {
        ChangeSet changes;

        const int startPos = startOf(m_literal);
Tobias Hunger's avatar
Tobias Hunger committed
961
        QString replacement(QLatin1String("tr("));
Tobias Hunger's avatar
Tobias Hunger committed
962
        if (m_option == useQCoreApplicationTranslate) {
Tobias Hunger's avatar
Tobias Hunger committed
963
964
965
966
967
            replacement = QLatin1String("QCoreApplication::translate(\"")
                          + m_context + QLatin1String("\", ");
        } else if (m_option == useMacro) {
            replacement = QLatin1String("QT_TRANSLATE_NOOP(\"")
                    + m_context + QLatin1String("\", ");
Tobias Hunger's avatar
Tobias Hunger committed
968
969
970
        }

        changes.insert(startPos, replacement);
971
        changes.insert(endOf(m_literal), QLatin1String(")"));
Tobias Hunger's avatar
Tobias Hunger committed
972
973
974
975
976
977
978

        refactoringChanges()->changeFile(fileName(), changes);
    }

private:
    ExpressionAST *m_literal;
    TranslationOption m_option;
Tobias Hunger's avatar
Tobias Hunger committed
979
    QString m_context;
Tobias Hunger's avatar
Tobias Hunger committed
980
981
};

982
class CStringToNSString: public CppQuickFixOperation
983
984
{
public:
985
    CStringToNSString(TextEditor::BaseTextEditor *editor)
986
987
988
        : CppQuickFixOperation(editor)
        , stringLiteral(0)
        , qlatin1Call(0)
989
990
991
    {}

    virtual QString description() const
Robert Loehning's avatar
Robert Loehning committed
992
993
994
    {
        return QApplication::translate("CppTools::QuickFix", "Convert to Objective-C String Literal");
    }
995
996
997

    virtual int match(const QList<AST *> &path)
    {
998
999
1000
        stringLiteral = 0;
        qlatin1Call = 0;

1001
        if (path.isEmpty())
1002
            return -1; // nothing to do
1003

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

1006
        if (! stringLiteral)
1007
1008
            return -1;

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

1012
1013
1014
1015
1016
        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());
1017

1018
1019
1020
1021
                        if (id == "QLatin1String" || id == "QLatin1Literal")
                            qlatin1Call = call;
                    }
                }
1022
1023
1024
            }
        }

1025
        return path.size() - 1; // very high priority
1026
1027
    }

1028
    virtual void createChanges()
1029
    {
1030
1031
        ChangeSet changes;

1032
        if (qlatin1Call) {
1033
1034
            changes.replace(startOf(qlatin1Call), startOf(stringLiteral), QLatin1String("@"));
            changes.remove(endOf(stringLiteral), endOf(qlatin1Call));
1035
        } else {
1036
            changes.insert(startOf(stringLiteral), "@");
1037
        }
1038

1039
        refactoringChanges()->changeFile(fileName(), changes);
1040
1041
1042
1043
    }

private:
    StringLiteralAST *stringLiteral;
1044
    CallAST *qlatin1Call;
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
/*
  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
*/
class ConvertNumericLiteral: public CppQuickFixOperation
{
public:
    ConvertNumericLiteral(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor)
    {}

    virtual int match(const QList<AST *> &path)
    {
        literal = 0;

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

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

        if (! literal)
            return -1;

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

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

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

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

    virtual void createChanges()
    {
        ChangeSet changes;
        int start = startOf(literal);
        changes.replace(start, start + numberLength, replacement);
        refactoringChanges()->changeFile(fileName(), changes);
    }

protected:
    NumericLiteralAST *literal;
    const NumericLiteral *numeric;
    ulong value;
    int numberLength;
    QString replacement;
};

/*
  Convert integer literal to hex representation.
  Replace
    32
    040
  With
    0x20

*/
class ConvertNumericToHex: public ConvertNumericLiteral
{
public:
    ConvertNumericToHex(TextEditor::BaseTextEditor *editor)
        : ConvertNumericLiteral(editor)
    {}

    virtual QString description() const
    {
        return QApplication::translate("CppTools::QuickFix", "Convert to Hexadecimal");
    }

    virtual int match(const QList<AST *> &path)
    {
        int ret = ConvertNumericLiteral::match(path);
        if (ret != -1 && !numeric->isHex()) {
            replacement.sprintf("0x%lX", value);
            return ret;
        }
        return -1;
    }

};

/*
  Convert integer literal to octal representation.
  Replace
    32
    0x20
  With
    040
*/
class ConvertNumericToOctal: public ConvertNumericLiteral
{
public:
    ConvertNumericToOctal(TextEditor::BaseTextEditor *editor)
        : ConvertNumericLiteral(editor)
    {}

    virtual QString description() const
    {
        return QApplication::translate("CppTools::QuickFix", "Convert to Octal");
    }

    virtual int match(const QList<AST *> &path)
    {
        int ret = ConvertNumericLiteral::match(path);
        if (ret != -1 && value != 0) {
            const char * const str = numeric->chars();
            if (numberLength > 1 && str[0] == '0' && str[1] != 'x' && str[1] != 'X')
                return -1;
            replacement.sprintf("0%lo", value);
            return ret;
        }
        return -1;
    }

};

/*
  Convert integer literal to decimal representation.
  Replace
    0x20
    040
  With
    32
*/
class ConvertNumericToDecimal: public ConvertNumericLiteral
{
public:
    ConvertNumericToDecimal(TextEditor::BaseTextEditor *editor)
        : ConvertNumericLiteral(editor)
    {}

    virtual QString description() const
    {
        return QApplication::translate("CppTools::QuickFix", "Convert to Decimal");
    }

    virtual int match(const QList<AST *> &path)
    {
        int ret = ConvertNumericLiteral::match(path);
        if (ret != -1 && (value != 0 || numeric->isHex())) {
            const char * const str = numeric->chars();
            if (numberLength > 1 && str[0] != '0')
                return -1;
            replacement.sprintf("%lu", value);
            return ret;
        }
        return -1;
    }

};

1225
1226