cppquickfix.cpp 46.9 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

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

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

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

using namespace CppEditor::Internal;
using namespace CPlusPlus;
64
using namespace Utils;
65

66
67
namespace {

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

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

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

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

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

142
143
144
        return index;
    }

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

private:
    BinaryExpressionAST *binary;
163
164
165
    NestedExpressionAST *nested;
    UnaryExpressionAST *negation;

166
167
168
169
170
171
172
173
174
175
    QString replacement;
};

/*
    Rewrite
    a op b

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


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

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

233
    virtual void createChanges()
234
    {
235
236
        ChangeSet changes;

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

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

private:
    BinaryExpressionAST *binary;
    QString replacement;
};

/*
    Rewrite
    !a && !b

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

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

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

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

        if (! expression)
            return -1;

282
        if (! isCursorOn(expression->binary_op_token))
283
284
            return -1;

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

296
        return -1;
297
298
    }

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

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

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

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

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

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

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

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

376
                    const int cursorPosition = selectionStart();
377
378
379
380
381
382
383

                    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.

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

                break;
            }
        }

        return -1;
    }

395
    virtual void createChanges()
396
    {
397
398
        ChangeSet changes;

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

404
        DeclaratorAST *prevDeclarator = declaration->declarator_list->value;
405
406
407
408

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

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

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

418
419
            prevDeclarator = declarator;
        }
420

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

private:
    SimpleDeclarationAST *declaration;
};

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

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

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

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

        return -1;
    }

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

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

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

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

private:
    StatementAST *_statement;
};

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

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

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

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

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

        return -1;
    }

535
    virtual void createChanges()
536
    {
537
        ChangeSet changes;
538

539
        changes.copy(range(core), startOf(condition));
540
541

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

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

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

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

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

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

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

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

        return -1;
    }

608
    virtual void createChanges()
609
    {
610
        ChangeSet changes;
611

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

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

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

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

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

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

  and
    if (something || something_else)
      x;

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

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

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

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

680
        if (! pattern || ! pattern->statement)
681
682
            return -1;

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

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

            if (isCursorOn(condition->binary_op_token))
                return index;
706
707
708
        }

        return -1;
Roberto Raggi's avatar
Roberto Raggi committed
709
710
    }

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

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

    void splitAndCondition()
    {
723
        ChangeSet changes;
Roberto Raggi's avatar
Roberto Raggi committed
724

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

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

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

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

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

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

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

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

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

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

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

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

con's avatar
con committed
784
785
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

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

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

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

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

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

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

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

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

835
    virtual void createChanges()
836
    {
837
838
        ChangeSet changes;

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

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

con's avatar
con committed
848
        changes.insert(endOf(literal), ")");
849

850
        refactoringChanges()->changeFile(fileName(), changes);
851
852
853
    }

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

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

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

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

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

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

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

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

    virtual void createChanges()
    {
        ChangeSet changes;

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

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

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

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

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

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

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

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

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

1003
        if (! stringLiteral)
1004
1005
            return -1;

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

1009
1010
1011
1012
1013
        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());
1014

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

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

1025
    virtual void createChanges()
1026
    {
1027
1028
        ChangeSet changes;

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

1036
        refactoringChanges()->changeFile(fileName(), changes);
1037
1038
1039
1040
    }

private:
    StringLiteralAST *stringLiteral;
1041
    CallAST *qlatin1Call;
1042
1043
};

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
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
/*
  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;
    }

};

1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318