cppquickfix.cpp 42.2 KB
Newer Older
1
2
3
4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

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

33
#include <cplusplus/ASTPath.h>
34
#include <cplusplus/CppDocument.h>
35
#include <cplusplus/ResolveExpression.h>
Tobias Hunger's avatar
Tobias Hunger committed
36
#include <cplusplus/Overview.h>
37

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

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

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

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

63
64
namespace {

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

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

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

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

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

138
139
140
        return index;
    }

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

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

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

/*
    Rewrite
    a op b

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


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

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

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

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

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

private:
    BinaryExpressionAST *binary;
    QString replacement;
};

/*
    Rewrite
    !a && !b

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

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

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

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

        if (! expression)
            return -1;

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

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

292
        return -1;
293
294
    }

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

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

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

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

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

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

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

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

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

                    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.

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

                break;
            }
        }

        return -1;
    }

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

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

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

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

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

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

414
415
            prevDeclarator = declarator;
        }
416

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

private:
    SimpleDeclarationAST *declaration;
};

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

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

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

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

        return -1;
    }

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

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

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

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

private:
    StatementAST *_statement;
};

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

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

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

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

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

        return -1;
    }

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

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

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

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

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

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

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

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

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

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

        return -1;
    }

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

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

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

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

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

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

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

  and
    if (something || something_else)
      x;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

con's avatar
con committed
780
781
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

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

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

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

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

con's avatar
con committed
799
800
801
802
803
804
805
806
807
        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;
        }
808

con's avatar
con committed
809
        if (path.size() > 1) {
810
811
812
813
            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());
814

con's avatar
con committed
815
816
                        if ((type == TypeString && (id == "QLatin1String" || id == "QLatin1Literal"))
                                || (type == TypeChar && id == "QLatin1Char"))
817
818
819
820
                            return -1; // skip it
                    }
                }
            }
821
822
        }

con's avatar
con committed
823
824
825
826
        if (type == TypeString) {
            if (charAt(startOf(literal)) == QLatin1Char('@'))
                type = TypeObjCString;
        }
827
        return path.size() - 1; // very high priority
828
829
    }

830
    virtual void createChanges()
831
    {
832
833
        ChangeSet changes;

con's avatar
con committed
834
835
836
        const int startPos = startOf(literal);
        QLatin1String replacement = (type == TypeChar ? QLatin1String("QLatin1Char(")
            : QLatin1String("QLatin1String("));
837

con's avatar
con committed
838
        if (type == TypeObjCString)
839
            changes.replace(startPos, startPos + 1, replacement);
840
        else
841
            changes.insert(startPos, replacement);
842

con's avatar
con committed
843
        changes.insert(endOf(literal), ")");
844

845
        refactoringChanges()->changeFile(fileName(), changes);
846
847
848
    }

private:
con's avatar
con committed
849
850
    ExpressionAST *literal;
    Type type;
851
852
};

Tobias Hunger's avatar
Tobias Hunger committed
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
/*
  Replace
    "abcd"
  With
    tr("abcd") or
    QCoreApplication::translate("CONTEXT", "abcd")
*/
class TranslateStringLiteral: public CppQuickFixOperation
{
public:
    TranslateStringLiteral(TextEditor::BaseTextEditor *editor)
        : CppQuickFixOperation(editor), m_literal(0)
    { }

    enum TranslationOption { unknown, useTr, useQCoreApplicationTranslate };

    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())
            return -1; // nothing to do

        m_literal = path.last()->asStringLiteral();
        if (!m_literal)
            return -1; // nothing to do

        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());

                        if (id == "tr" || id == "trUtf8"
                            || id == "QApplication::translate"
                            || id == "QCoreApplication::translate")
                            return -1; // skip it
                    }
                }
            }
            for (int i = path.size() - 1; i >= 0; --i)
            {
                if (FunctionDefinitionAST *definition = path.at(i)->asFunctionDefinition()) {
                    Function *function = definition->symbol;
                    LookupContext context(document(), snapshot());

                    ClassOrNamespace *b = context.lookupType(function);
                    if (b) {
                        QList<ClassOrNamespace *> todo;
                        todo.append(b);
                        QSet<ClassOrNamespace *> done;
                        while(!todo.isEmpty()) {
                            ClassOrNamespace *current = todo.first();
                            todo.removeFirst();
                            if (done.contains(current))
                                continue;
                            done.insert(current);
                            foreach (Symbol *s, current->symbols()) {
                                if (Class *klass = s->asClass()) {
                                    if (strcmp(klass->name()->identifier()->chars(),
                                               "QObject") == 0) {
                                        m_option = useTr;
                                        return path.size() - 1;
                                    }
                                }
                            }
                            todo.append(current->usings());
                        }
                    }
                    // We need to do a QCA::translate, so we need a context.
                    // Use fully qualified class name:
                    QList<ClassOrNamespace *> stack;
                    if (b) {
                        stack.append(b);
                        while (b->parent()) {
                            b = b->parent();
                            stack.prepend(b);
                        }
                    }
                    foreach(ClassOrNamespace *current, stack) {
                        foreach(Symbol *s, current->symbols()) {
                            if (!s || !s->name() || !s->name()->identifier()
                                || !s->name()->identifier()->chars()) {
                                continue;
                            }
                            m_context += s->name()->identifier()->chars();
                            m_context.append("::");
                        }
                    }
                    if (m_context.size() >= 2)
                        m_context.chop(2);
                    else if (m_context.isEmpty())
                        m_context.append("GLOBAL");
                }
            }
        }

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

    virtual void createChanges()
    {
        ChangeSet changes;

        const int startPos = startOf(m_literal);
        QByteArray replacement("tr(");
        if (m_option == useQCoreApplicationTranslate) {
            replacement = ("QCoreApplication::translate(\"");
            replacement += m_context;
            replacement += "\", ";
        }

        changes.insert(startPos, replacement);
        changes.insert(endOf(m_literal), ")");

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

private:
    ExpressionAST *m_literal;
    TranslationOption m_option;
    QByteArray m_context;
};

986
class CStringToNSString: public CppQuickFixOperation
987
988
{
public:
989
    CStringToNSString(TextEditor::BaseTextEditor *editor)
990
991
992
        : CppQuickFixOperation(editor)
        , stringLiteral(0)
        , qlatin1Call(0)
993
994
995
    {}

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

    virtual int match(const QList<AST *> &path)
    {
1002
1003
1004
        stringLiteral = 0;
        qlatin1Call = 0;

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

1008
        stringLiteral = path.last()->asStringLiteral();
1009

1010
        if (! stringLiteral)
1011
1012
            return -1;

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

1016
1017
1018
1019
1020
        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());
1021

1022
1023
1024
1025
                        if (id == "QLatin1String" || id == "QLatin1Literal")
                            qlatin1Call = call;
                    }
                }
1026
1027
1028
            }
        }

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

1032
    virtual void createChanges()
1033
    {
1034
1035
        ChangeSet changes;

1036
        if (qlatin1Call) {
1037
1038
            changes.replace(startOf(qlatin1Call), startOf(stringLiteral), QLatin1String("@"));
            changes.remove(endOf(stringLiteral), endOf(qlatin1Call));
1039
        } else {
1040
            changes.insert(startOf(stringLiteral), "@");
1041
        }
1042

1043
        refactoringChanges()->changeFile(fileName(), changes);
1044
1045
1046
1047
    }

private:
    StringLiteralAST *stringLiteral;
1048
    CallAST *qlatin1Call;
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
1225
1226
1227
1228
/*
  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;
    }

};

1229
1230
1231
} // end of anonymous namespace


1232
CppQuickFixOperation::CppQuickFixOperation(TextEditor::BaseTextEditor *editor)
1233
1234
1235
    : TextEditor::QuickFixOperation(editor)
    , _refactoringChanges(0)
    , _topLevelNode(0)
1236
1237
{ }

1238
1239
CppQuickFixOperation::~CppQuickFixOperation()
{
1240
1241
    if (_refactoringChanges)
        delete _refactoringChanges;
1242
}
Roberto Raggi's avatar
Roberto Raggi committed
1243

1244
int CppQuickFixOperation::match(TextEditor::QuickFixState *state)
1245
{
1246
    CppQuickFixState *s = static_cast<CppQuickFixState *>(state);
1247
    _document = s->info.doc;
1248
1249
    if (_refactoringChanges)
        delete _refactoringChanges;
1250
    _refactoringChanges = new CppRefactoringChanges(s->info.snapshot);
1251
    return match(s->path);
1252
}
Roberto Raggi's avatar
Roberto Raggi committed
1253

1254
1255
1256
Utils::ChangeSet::Range CppQuickFixOperation::range(unsigned tokenIndex) const
{
    const CPlusPlus::Token &token = tokenAt(tokenIndex);
1257
1258
1259
1260
    unsigned line, column;
    _document->translationUnit()->getPosition(token.begin(), &line, &column);
    const int start = editor()->document()->findBlockByNumber(line - 1).position() + column - 1;
    return Utils::ChangeSet::Range(start, start + token.length());
1261
1262
1263
1264
1265
1266
1267
}

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

1268
1269
1270
QString CppQuickFixOperation::fileName() const
{ return document()->fileName(); }

1271
1272
void CppQuickFixOperation::apply()
{
1273
    refactoringChanges()->apply();
1274
1275
}

1276
CppEditor::CppRefactoringChanges *CppQuickFixOperation::refactoringChanges() const
1277
1278
{ return _refactoringChanges; }

1279
1280
Document::Ptr CppQuickFixOperation::document() const
{ return _document; }
1281

1282
const Snapshot