cppquickfix.cpp 57.3 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>
40

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

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

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

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

68
69
namespace {

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

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

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

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

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

144
145
146
        return index;
    }

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

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

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

/*
    Rewrite
    a op b

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


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

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

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

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

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

private:
    BinaryExpressionAST *binary;
    QString replacement;
};

/*
    Rewrite
    !a && !b

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

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

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

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

        if (! expression)
            return -1;

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

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

298
        return -1;
299
300
    }

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

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

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

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

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

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

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

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

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

                    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.

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

                break;
            }
        }

        return -1;
    }

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

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

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

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

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

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

420
421
            prevDeclarator = declarator;
        }
422

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

private:
    SimpleDeclarationAST *declaration;
};

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

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

447
    virtual int match(const QList<AST *> &path)
448
449
450
451
    {
        // 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
452
        if (ifStatement && isCursorOn(ifStatement->if_token) && ifStatement->statement
453
454
455
456
457
458
459
460
461
            && ! 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();
462
463
            if (ifStatement && ifStatement->statement
                && isCursorOn(ifStatement->statement)
464
465
466
467
468
469
470
471
472
473
474
475
                && ! ifStatement->statement->asCompoundStatement()) {
                _statement = ifStatement->statement;
                return index;
            }
        }

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

        return -1;
    }

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

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

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

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

private:
    StatementAST *_statement;
};

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

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

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

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

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

        return -1;
    }

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

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

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

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

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

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

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

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

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

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

        return -1;
    }

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

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

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

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

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

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

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

  and
    if (something || something_else)
      x;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

con's avatar
con committed
805
806
807
808
809
810
811
812
813
        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;
        }
814

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

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

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

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

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

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

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

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

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

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

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

    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
890
            return -1;
Tobias Hunger's avatar
Tobias Hunger committed
891
892
893

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

Tobias Hunger's avatar
Tobias Hunger committed
896
897
        // Do we already have a translation markup?
        if (path.size() >= 2) {
Tobias Hunger's avatar
Tobias Hunger committed
898
899
900
901
902
903
            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
904
905
906
                                || id == "translate"
                                || id == "QT_TRANSLATE_NOOP"
                                || id == "QLatin1String" || id == "QLatin1Literal")
Tobias Hunger's avatar
Tobias Hunger committed
907
908
909
910
                            return -1; // skip it
                    }
                }
            }
Tobias Hunger's avatar
Tobias Hunger committed
911
        }
912

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

Tobias Hunger's avatar
Tobias Hunger committed
949
950
951
952
        // 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
953
954
955
956
957
958
959
    }

    virtual void createChanges()
    {
        ChangeSet changes;

        const int startPos = startOf(m_literal);
Tobias Hunger's avatar
Tobias Hunger committed
960
        QString replacement(QLatin1String("tr("));
Tobias Hunger's avatar
Tobias Hunger committed
961
        if (m_option == useQCoreApplicationTranslate) {
Tobias Hunger's avatar
Tobias Hunger committed
962
963
964
965
966
            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
967
968
969
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private:
    StringLiteralAST *stringLiteral;
1043
    CallAST *qlatin1Call;
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
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
/*
  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;
    }

};

1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236