cppquickfixes.cpp 75.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
hjk's avatar
hjk committed
3 4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29

30
#include "cppcompleteswitch.h"
31 32
#include "cppeditor.h"
#include "cppquickfix.h"
33
#include "cppinsertdecldef.h"
34
#include "cppinsertqtpropertymembers.h"
Leandro Melo's avatar
Leandro Melo committed
35 36
#include "cppquickfixassistant.h"
#include "cppcompleteswitch.h"
37
#include "cppfunctiondecldeflink.h"
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

#include <ASTVisitor.h>
#include <AST.h>
#include <ASTMatcher.h>
#include <ASTPatternBuilder.h>
#include <CoreTypes.h>
#include <Literals.h>
#include <Name.h>
#include <Names.h>
#include <Symbol.h>
#include <Symbols.h>
#include <Token.h>
#include <TranslationUnit.h>
#include <Type.h>

#include <cplusplus/DependencyTable.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
56
#include <cpptools/ModelManagerInterface.h>
57 58
#include <cplusplus/CppRewriter.h>
#include <cpptools/cpptoolsconstants.h>
59
#include <cpptools/cpprefactoringchanges.h>
60
#include <cpptools/insertionpointlocator.h>
61
#include <cpptools/cpptoolsreuse.h>
62 63
#include <cpptools/cppclassesfilter.h>
#include <cpptools/searchsymbols.h>
64
#include <cpptools/symbolfinder.h>
65
#include <extensionsystem/iplugin.h>
66
#include <extensionsystem/pluginmanager.h>
67

68 69
#include <utils/qtcassert.h>

70 71 72 73
#include <QFileInfo>
#include <QApplication>
#include <QTextBlock>
#include <QTextCursor>
74 75
#include <cctype>

76 77
using namespace CppEditor;
using namespace CppEditor::Internal;
78
using namespace CppTools;
79
using namespace CPlusPlus;
hjk's avatar
hjk committed
80
using namespace TextEditor;
81 82
using namespace Utils;

83 84 85 86 87
static inline bool isQtStringLiteral(const QByteArray &id)
{
    return id == "QLatin1String" || id == "QLatin1Literal" || id == "QStringLiteral";
}

88 89 90 91 92
static inline bool isQtStringTranslation(const QByteArray &id)
{
    return id == "tr" || id == "trUtf8" || id == "translate" || id == "QT_TRANSLATE_NOOP";
}

93 94 95 96 97 98 99
namespace {

/*
    Rewrite
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
100 101

    Activates on: <= < > >= == !=
102 103 104 105
*/
class UseInverseOp: public CppQuickFixFactory
{
public:
106
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
107
    {
108
        CppRefactoringFilePtr file = interface->currentFile();
109

Leandro Melo's avatar
Leandro Melo committed
110
        const QList<AST *> &path = interface->path();
111 112 113
        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
114
            return;
Leandro Melo's avatar
Leandro Melo committed
115
        if (! interface->isCursorOn(binary->binary_op_token))
116
            return;
117 118

        Kind invertToken;
119
        switch (file->tokenAt(binary->binary_op_token).kind()) {
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        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:
139
            return;
140 141
        }

Leandro Melo's avatar
Leandro Melo committed
142
        result.append(CppQuickFixOperation::Ptr(new Operation(interface, index, binary, invertToken)));
143 144 145 146 147 148 149 150 151 152 153 154
    }

private:
    class Operation: public CppQuickFixOperation
    {
        BinaryExpressionAST *binary;
        NestedExpressionAST *nested;
        UnaryExpressionAST *negation;

        QString replacement;

    public:
155
        Operation(const CppQuickFixInterface &interface,
Leandro Melo's avatar
Leandro Melo committed
156 157
            int priority, BinaryExpressionAST *binary, Kind invertToken)
            : CppQuickFixOperation(interface, priority)
158
            , binary(binary), nested(0), negation(0)
159 160 161 162 163 164 165
        {
            Token tok;
            tok.f.kind = invertToken;
            replacement = QLatin1String(tok.spell());

            // check for enclosing nested expression
            if (priority - 1 >= 0)
Leandro Melo's avatar
Leandro Melo committed
166
                nested = interface->path()[priority - 1]->asNestedExpression();
167 168 169

            // check for ! before parentheses
            if (nested && priority - 2 >= 0) {
Leandro Melo's avatar
Leandro Melo committed
170
                negation = interface->path()[priority - 2]->asUnaryExpression();
171
                if (negation && ! interface->currentFile()->tokenAt(negation->unary_op_token).is(T_EXCLAIM))
172 173 174 175 176 177 178 179 180
                    negation = 0;
            }
        }

        virtual QString description() const
        {
            return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
        }

181
        void perform()
182
        {
183 184 185
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());

186 187 188
            ChangeSet changes;
            if (negation) {
                // can't remove parentheses since that might break precedence
189
                changes.remove(currentFile->range(negation->unary_op_token));
190
            } else if (nested) {
191
                changes.insert(currentFile->startOf(nested), QLatin1String("!"));
192
            } else {
193 194
                changes.insert(currentFile->startOf(binary), QLatin1String("!("));
                changes.insert(currentFile->endOf(binary), QLatin1String(")"));
195
            }
196
            changes.replace(currentFile->range(binary->binary_op_token), replacement);
197 198
            currentFile->setChangeSet(changes);
            currentFile->apply();
199 200 201 202 203 204 205 206 207 208
        }
    };
};

/*
    Rewrite
    a op b

    As
    b flipop a
209 210

    Activates on: <= < > >= == != && ||
211 212 213 214
*/
class FlipBinaryOp: public CppQuickFixFactory
{
public:
215
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
216
    {
Leandro Melo's avatar
Leandro Melo committed
217
        const QList<AST *> &path = interface->path();
218
        CppRefactoringFilePtr file = interface->currentFile();
219 220 221 222

        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
223
            return;
Leandro Melo's avatar
Leandro Melo committed
224
        if (! interface->isCursorOn(binary->binary_op_token))
225
            return;
226 227

        Kind flipToken;
228
        switch (file->tokenAt(binary->binary_op_token).kind()) {
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        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:
248
            return;
249 250 251 252 253 254 255 256 257
        }

        QString replacement;
        if (flipToken != T_EOF_SYMBOL) {
            Token tok;
            tok.f.kind = flipToken;
            replacement = QLatin1String(tok.spell());
        }

Leandro Melo's avatar
Leandro Melo committed
258
        result.append(QuickFixOperation::Ptr(new Operation(interface, index, binary, replacement)));
259 260 261 262 263 264
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
265
        Operation(const CppQuickFixInterface &interface,
Leandro Melo's avatar
Leandro Melo committed
266 267
                  int priority, BinaryExpressionAST *binary, QString replacement)
            : CppQuickFixOperation(interface)
268 269 270 271 272 273 274 275 276 277 278 279 280 281
            , binary(binary)
            , replacement(replacement)
        {
            setPriority(priority);
        }

        virtual QString description() const
        {
            if (replacement.isEmpty())
                return QApplication::translate("CppTools::QuickFix", "Swap Operands");
            else
                return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
        }

282
        void perform()
283
        {
284 285
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());
286

287
            ChangeSet changes;
288
            changes.flip(currentFile->range(binary->left_expression), currentFile->range(binary->right_expression));
289
            if (! replacement.isEmpty())
290
                changes.replace(currentFile->range(binary->binary_op_token), replacement);
291

292 293
            currentFile->setChangeSet(changes);
            currentFile->apply();
294 295 296 297 298 299 300 301 302 303 304 305 306 307
        }

    private:
        BinaryExpressionAST *binary;
        QString replacement;
    };
};

/*
    Rewrite
    !a && !b

    As
    !(a || b)
308 309

    Activates on: &&
310 311 312 313
*/
class RewriteLogicalAndOp: public CppQuickFixFactory
{
public:
314
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
315 316
    {
        BinaryExpressionAST *expression = 0;
Leandro Melo's avatar
Leandro Melo committed
317
        const QList<AST *> &path = interface->path();
318
        CppRefactoringFilePtr file = interface->currentFile();
319 320 321 322 323 324 325 326 327

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

        if (! expression)
328
            return;
329

Leandro Melo's avatar
Leandro Melo committed
330
        if (! interface->isCursorOn(expression->binary_op_token))
331
            return;
332

Leandro Melo's avatar
Leandro Melo committed
333
        QSharedPointer<Operation> op(new Operation(interface));
334 335

        if (expression->match(op->pattern, &matcher) &&
336 337 338
                file->tokenAt(op->pattern->binary_op_token).is(T_AMPER_AMPER) &&
                file->tokenAt(op->left->unary_op_token).is(T_EXCLAIM) &&
                file->tokenAt(op->right->unary_op_token).is(T_EXCLAIM)) {
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
            op->setDescription(QApplication::translate("CppTools::QuickFix", "Rewrite Condition Using ||"));
            op->setPriority(index);
            result.append(op);
        }
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        QSharedPointer<ASTPatternBuilder> mk;
        UnaryExpressionAST *left;
        UnaryExpressionAST *right;
        BinaryExpressionAST *pattern;

354
        Operation(const CppQuickFixInterface &interface)
Leandro Melo's avatar
Leandro Melo committed
355
            : CppQuickFixOperation(interface)
356 357 358 359 360 361 362
            , mk(new ASTPatternBuilder)
        {
            left = mk->UnaryExpression();
            right = mk->UnaryExpression();
            pattern = mk->BinaryExpression(left, right);
        }

363
        void perform()
364
        {
365 366 367
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());

368
            ChangeSet changes;
369 370 371 372 373
            changes.replace(currentFile->range(pattern->binary_op_token), QLatin1String("||"));
            changes.remove(currentFile->range(left->unary_op_token));
            changes.remove(currentFile->range(right->unary_op_token));
            const int start = currentFile->startOf(pattern);
            const int end = currentFile->endOf(pattern);
374 375 376
            changes.insert(start, QLatin1String("!("));
            changes.insert(end, QLatin1String(")"));

377 378 379
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
380 381 382 383 384 385 386
        }
    };

private:
    ASTMatcher matcher;
};

387 388 389 390 391 392 393
/*
    Rewrite
    int *a, b;

    As
    int *a;
    int b;
394 395

    Activates on: the type or the variable names.
396
*/
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
class SplitSimpleDeclarationOp: public CppQuickFixFactory
{
    static bool checkDeclaration(SimpleDeclarationAST *declaration)
    {
        if (! declaration->semicolon_token)
            return false;

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

public:
427
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
428 429
    {
        CoreDeclaratorAST *core_declarator = 0;
Leandro Melo's avatar
Leandro Melo committed
430
        const QList<AST *> &path = interface->path();
431
        CppRefactoringFilePtr file = interface->currentFile();
432
        const int cursorPosition = file->cursor().selectionStart();
433 434 435 436 437 438 439 440 441 442 443

        for (int index = path.size() - 1; 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)) {
                    SimpleDeclarationAST *declaration = simpleDecl;

444 445
                    const int startOfDeclSpecifier = file->startOf(declaration->decl_specifier_list->firstToken());
                    const int endOfDeclSpecifier = file->endOf(declaration->decl_specifier_list->lastToken() - 1);
446 447 448

                    if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier) {
                        // the AST node under cursor is a specifier.
449 450
                        result.append(QuickFixOperation::Ptr(new Operation(interface, index, declaration)));
                        return;
451 452
                    }

Leandro Melo's avatar
Leandro Melo committed
453
                    if (core_declarator && interface->isCursorOn(core_declarator)) {
454
                        // got a core-declarator under the text cursor.
455 456
                        result.append(QuickFixOperation::Ptr(new Operation(interface, index, declaration)));
                        return;
457 458 459
                    }
                }

460
                return;
461 462 463 464 465 466 467 468
            }
        }
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
469
        Operation(const CppQuickFixInterface &interface, int priority, SimpleDeclarationAST *decl)
Leandro Melo's avatar
Leandro Melo committed
470
            : CppQuickFixOperation(interface, priority)
471 472 473 474 475 476
            , declaration(decl)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split Declaration"));
        }

477
        void perform()
478
        {
479 480 481
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());

482 483 484
            ChangeSet changes;

            SpecifierListAST *specifiers = declaration->decl_specifier_list;
485 486 487
            int declSpecifiersStart = currentFile->startOf(specifiers->firstToken());
            int declSpecifiersEnd = currentFile->endOf(specifiers->lastToken() - 1);
            int insertPos = currentFile->endOf(declaration->semicolon_token);
488 489 490 491 492 493 494 495 496

            DeclaratorAST *prevDeclarator = declaration->declarator_list->value;

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

                changes.insert(insertPos, QLatin1String("\n"));
                changes.copy(declSpecifiersStart, declSpecifiersEnd, insertPos);
                changes.insert(insertPos, QLatin1String(" "));
497
                changes.move(currentFile->range(declarator), insertPos);
498 499
                changes.insert(insertPos, QLatin1String(";"));

500 501
                const int prevDeclEnd = currentFile->endOf(prevDeclarator);
                changes.remove(prevDeclEnd, currentFile->startOf(declarator));
502 503 504 505

                prevDeclarator = declarator;
            }

506 507 508
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(declaration));
            currentFile->apply();
509 510 511 512 513 514 515 516 517
        }

    private:
        SimpleDeclarationAST *declaration;
    };
};

/*
    Add curly braces to a if statement that doesn't already contain a
518 519 520 521 522
    compound statement. I.e.

    if (a)
        b;
    becomes
523
    if (a)
524
        b;
525 526

    Activates on: the if
527 528 529 530
*/
class AddBracesToIfOp: public CppQuickFixFactory
{
public:
531
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
532
    {
Leandro Melo's avatar
Leandro Melo committed
533
        const QList<AST *> &path = interface->path();
534 535 536 537

        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
Leandro Melo's avatar
Leandro Melo committed
538
        if (ifStatement && interface->isCursorOn(ifStatement->if_token) && ifStatement->statement
539
            && ! ifStatement->statement->asCompoundStatement()) {
540 541
            result.append(QuickFixOperation::Ptr(new Operation(interface, index, ifStatement->statement)));
            return;
542 543 544 545 546 547 548
        }

        // 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();
            if (ifStatement && ifStatement->statement
Leandro Melo's avatar
Leandro Melo committed
549
                && interface->isCursorOn(ifStatement->statement)
550
                && ! ifStatement->statement->asCompoundStatement()) {
551 552
                result.append(QuickFixOperation::Ptr(new Operation(interface, index, ifStatement->statement)));
                return;
553 554 555 556 557 558 559 560 561 562 563
            }
        }

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

private:
    class Operation: public CppQuickFixOperation
    {
    public:
564
        Operation(const CppQuickFixInterface &interface, int priority, StatementAST *statement)
Leandro Melo's avatar
Leandro Melo committed
565
            : CppQuickFixOperation(interface, priority)
566 567 568 569 570 571
            , _statement(statement)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Add Curly Braces"));
        }

572
        void perform()
573
        {
574 575 576
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());

577 578
            ChangeSet changes;

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

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

585 586 587
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(Utils::ChangeSet::Range(start, end));
            currentFile->apply();
588 589 590 591 592 593 594 595 596 597 598 599 600 601
        }

    private:
        StatementAST *_statement;
    };
};

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

    With
    Type name = foo;
    if (name) {...}
602 603

    Activates on: the name of the introduced variable
604 605 606 607
*/
class MoveDeclarationOutOfIfOp: public CppQuickFixFactory
{
public:
608
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
609
    {
Leandro Melo's avatar
Leandro Melo committed
610 611
        const QList<AST *> &path = interface->path();
        QSharedPointer<Operation> op(new Operation(interface));
612 613 614 615 616 617 618 619

        int index = path.size() - 1;
        for (; index != -1; --index) {
            if (IfStatementAST *statement = path.at(index)->asIfStatement()) {
                if (statement->match(op->pattern, &op->matcher) && op->condition->declarator) {
                    DeclaratorAST *declarator = op->condition->declarator;
                    op->core = declarator->core_declarator;
                    if (! op->core)
620
                        return;
621

Leandro Melo's avatar
Leandro Melo committed
622
                    if (interface->isCursorOn(op->core)) {
623 624
                        op->setPriority(index);
                        result.append(op);
625
                        return;
626 627 628 629 630 631 632 633 634 635
                    }
                }
            }
        }
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
636
        Operation(const CppQuickFixInterface &interface)
Leandro Melo's avatar
Leandro Melo committed
637
            : CppQuickFixOperation(interface)
638 639 640 641 642 643 644 645
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

            condition = mk.Condition();
            pattern = mk.IfStatement(condition);
        }

646
        void perform()
647
        {
648 649 650
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());

651 652
            ChangeSet changes;

653
            changes.copy(currentFile->range(core), currentFile->startOf(condition));
654

655 656
            int insertPos = currentFile->startOf(pattern);
            changes.move(currentFile->range(condition), insertPos);
657 658
            changes.insert(insertPos, QLatin1String(";\n"));

659 660 661
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
662 663 664 665
        }

        ASTMatcher matcher;
        ASTPatternBuilder mk;
666
        CPPEditorWidget *editor;
667 668 669 670 671 672 673 674 675 676 677 678 679
        ConditionAST *condition;
        IfStatementAST *pattern;
        CoreDeclaratorAST *core;
    };
};

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

    With
    Type name;
    while ((name = foo()) != 0) {...}
680 681

    Activates on: the name of the introduced variable
682 683 684 685
*/
class MoveDeclarationOutOfWhileOp: public CppQuickFixFactory
{
public:
686
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
687
    {
Leandro Melo's avatar
Leandro Melo committed
688 689
        const QList<AST *> &path = interface->path();
        QSharedPointer<Operation> op(new Operation(interface));
690 691 692 693 694 695 696 697 698

        int index = path.size() - 1;
        for (; index != -1; --index) {
            if (WhileStatementAST *statement = path.at(index)->asWhileStatement()) {
                if (statement->match(op->pattern, &op->matcher) && op->condition->declarator) {
                    DeclaratorAST *declarator = op->condition->declarator;
                    op->core = declarator->core_declarator;

                    if (! op->core)
699
                        return;
700

701 702
                    if (! declarator->equal_token)
                        return;
703

704 705
                    if (! declarator->initializer)
                        return;
706

Leandro Melo's avatar
Leandro Melo committed
707
                    if (interface->isCursorOn(op->core)) {
708 709
                        op->setPriority(index);
                        result.append(op);
710
                        return;
711 712 713 714 715 716 717 718 719 720
                    }
                }
            }
        }
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
721
        Operation(const CppQuickFixInterface &interface)
Leandro Melo's avatar
Leandro Melo committed
722
            : CppQuickFixOperation(interface)
723 724 725 726 727 728 729 730
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

            condition = mk.Condition();
            pattern = mk.WhileStatement(condition);
        }

731
        void perform()
732
        {
733 734 735
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());

736 737
            ChangeSet changes;

738 739
            changes.insert(currentFile->startOf(condition), QLatin1String("("));
            changes.insert(currentFile->endOf(condition), QLatin1String(") != 0"));
740

741 742 743 744
            int insertPos = currentFile->startOf(pattern);
            const int conditionStart = currentFile->startOf(condition);
            changes.move(conditionStart, currentFile->startOf(core), insertPos);
            changes.copy(currentFile->range(core), insertPos);
745 746
            changes.insert(insertPos, QLatin1String(";\n"));

747 748 749
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
750 751 752 753
        }

        ASTMatcher matcher;
        ASTPatternBuilder mk;
754
        CPPEditorWidget *editor;
755 756 757 758 759 760 761 762 763 764 765 766
        ConditionAST *condition;
        WhileStatementAST *pattern;
        CoreDeclaratorAST *core;
    };
};

/*
  Replace
     if (something && something_else) {
     }

  with
767 768
     if (something)
        if (something_else)
769 770 771 772 773 774 775 776 777 778 779
     }

  and
    if (something || something_else)
      x;

  with
    if (something)
      x;
    else if (something_else)
      x;
780 781

    Activates on: && or ||
782 783 784 785
*/
class SplitIfStatementOp: public CppQuickFixFactory
{
public:
786
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
787 788
    {
        IfStatementAST *pattern = 0;
Leandro Melo's avatar
Leandro Melo committed
789
        const QList<AST *> &path = interface->path();
790 791 792 793 794 795 796 797 798 799 800

        int index = path.size() - 1;
        for (; index != -1; --index) {
            AST *node = path.at(index);
            if (IfStatementAST *stmt = node->asIfStatement()) {
                pattern = stmt;
                break;
            }
        }

        if (! pattern || ! pattern->statement)
801
            return;
802 803 804 805 806 807

        unsigned splitKind = 0;
        for (++index; index < path.size(); ++index) {
            AST *node = path.at(index);
            BinaryExpressionAST *condition = node->asBinaryExpression();
            if (! condition)
808
                return;
809

810
            Token binaryToken = interface->currentFile()->tokenAt(condition->binary_op_token);
811 812 813 814 815

            // only accept a chain of ||s or &&s - no mixing
            if (! splitKind) {
                splitKind = binaryToken.kind();
                if (splitKind != T_AMPER_AMPER && splitKind != T_PIPE_PIPE)
816
                    return;
817 818
                // we can't reliably split &&s in ifs with an else branch
                if (splitKind == T_AMPER_AMPER && pattern->else_statement)
819
                    return;
820
            } else if (splitKind != binaryToken.kind()) {
821
                return;
822 823
            }

824 825 826 827
            if (interface->isCursorOn(condition->binary_op_token)) {
                result.append(QuickFixOperation::Ptr(new Operation(interface, index, pattern, condition)));
                return;
            }
828 829 830 831 832 833 834
        }
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
835
        Operation(const CppQuickFixInterface &interface, int priority,
836
                  IfStatementAST *pattern, BinaryExpressionAST *condition)
Leandro Melo's avatar
Leandro Melo committed
837
            : CppQuickFixOperation(interface, priority)
838 839 840 841 842 843 844
            , pattern(pattern)
            , condition(condition)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split if Statement"));
        }

845
        void perform()
846
        {
847 848 849
            CppRefactoringChanges refactoring(snapshot());
            CppRefactoringFilePtr currentFile = refactoring.file(fileName());

850
            const Token binaryToken = currentFile->tokenAt(condition->binary_op_token);
851 852

            if (binaryToken.is(T_AMPER_AMPER))
853
                splitAndCondition(currentFile);
854
            else
855
                splitOrCondition(currentFile);
856 857
        }

858
        void splitAndCondition(CppRefactoringFilePtr currentFile)
859 860 861
        {
            ChangeSet changes;

862
            int startPos = currentFile->startOf(pattern);
863
            changes.insert(startPos, QLatin1String("if ("));
864
            changes.move(currentFile->range(condition->left_expression), startPos);
865 866
            changes.insert(startPos, QLatin1String(") {\n"));

867 868 869
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
            changes.insert(currentFile->endOf(pattern), QLatin1String("\n}"));
870

871 872 873
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
874 875
        }

876
        void splitOrCondition(CppRefactoringFilePtr currentFile)
877 878 879 880 881 882
        {
            ChangeSet changes;

            StatementAST *ifTrueStatement = pattern->statement;
            CompoundStatementAST *compoundStatement = ifTrueStatement->asCompoundStatement();

883
            int insertPos = currentFile->endOf(ifTrueStatement);
884 885 886 887 888 889
            if (compoundStatement)
                changes.insert(insertPos, QLatin1String(" "));
            else
                changes.insert(insertPos, QLatin1String("\n"));
            changes.insert(insertPos, QLatin1String("else if ("));

890 891
            const int rExprStart = currentFile->startOf(condition->right_expression);
            changes.move(rExprStart, currentFile->startOf(pattern->rparen_token), insertPos);
892 893
            changes.insert(insertPos, QLatin1String(")"));

894 895
            const int rParenEnd = currentFile->endOf(pattern->rparen_token);
            changes.copy(rParenEnd, currentFile->endOf(pattern->statement), insertPos);
896

897 898
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
899

900 901 902
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
903 904 905 906 907 908 909 910 911 912
        }

    private:
        IfStatementAST *pattern;
        BinaryExpressionAST *condition;
    };
};

/*
  Replace
913 914 915 916 917 918
    "abcd"  -> QLatin1String("abcd")
    @"abcd" -> QLatin1String("abcd") (Objective C)
    'a'     -> QLatin1Char('a')
    'a'     -> "a"
    "a"     -> 'a' or QLatin1Char('a') (Single character string constants)
    "\n"    -> '\n', QLatin1Char('\n')
919 920 921
  Except if they are already enclosed in
    QLatin1Char, QT_TRANSLATE_NOOP, tr,
    trUtf8, QLatin1Literal, QLatin1String
922

923
    Activates on: the string or character literal
924
*/
925 926 927 928 929 930 931

static inline QString msgQtStringLiteralDescription(const QString &replacement, int qtVersion)
{
    return QApplication::translate("CppTools::QuickFix", "Enclose in %1(...) (Qt %2)")
           .arg(replacement).arg(qtVersion);
}

932 933 934 935 936
static inline QString msgQtStringLiteralDescription(const QString &replacement)
{
    return QApplication::translate("CppTools::QuickFix", "Enclose in %1(...)").arg(replacement);
}

937 938 939
class WrapStringLiteral: public CppQuickFixFactory
{
public:
940
    typedef const CppQuickFixInterface AssistInterfacePtr;
941 942 943 944 945 946 947 948 949 950 951 952

    enum ActionFlags
    {
        EncloseInQLatin1CharAction = 0x1, EncloseInQLatin1StringAction = 0x2, EncloseInQStringLiteralAction = 0x4,
        EncloseActionMask = EncloseInQLatin1CharAction | EncloseInQLatin1StringAction | EncloseInQStringLiteralAction,
        TranslateTrAction = 0x8, TranslateQCoreApplicationAction = 0x10, TranslateNoopAction = 0x20,
        TranslationMask = TranslateTrAction | TranslateQCoreApplicationAction | TranslateNoopAction,
        RemoveObjectiveCAction = 0x40,
        ConvertEscapeSequencesToCharAction = 0x100, ConvertEscapeSequencesToStringAction = 0x200,
        SingleQuoteAction = 0x400, DoubleQuoteAction = 0x800
    };

953 954
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

955 956
    //void match(const AssistInterfacePtr &interface, QuickFixOperations &result);
    void match(const CppQuickFixInterface &interface, QuickFixOperations &result);
957 958 959 960 961 962 963 964 965 966 967
    static QString replacement(unsigned actions);
    static QByteArray stringToCharEscapeSequences(const QByteArray &content);
    static QByteArray charToStringEscapeSequences(const QByteArray &content);

    static ExpressionAST *analyze(const QList<AST *> &path, const CppRefactoringFilePtr &file,
                                  Type *type,
                                  QByteArray *enclosingFunction = 0,
                                  CallAST **enclosingFunctionCall = 0);

    // Operations performs the operations of type ActionFlags passed in as actions.
    class Operation : public CppQuickFixOperation
968
    {
969 970 971 972
    public:
        Operation(const AssistInterfacePtr &interface, int priority,
                  unsigned actions, const QString &description, ExpressionAST *literal,
                  const QString &translationContext = QString());
973

974 975
        void perform();

976 977 978 979 980 981
    private:
        const unsigned m_actions;
        ExpressionAST *m_literal;
        const QString m_translationContext;
    };
};
982

983 984 985
/* Analze a string/character literal like "x", QLatin1String("x") and return the literal
 * (StringLiteral or NumericLiteral for characters) and its type
 * and the enclosing function (QLatin1String, tr...) */
986

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
ExpressionAST *WrapStringLiteral::analyze(const QList<AST *> &path,
                                          const CppRefactoringFilePtr &file,
                                          Type *type,
                                          QByteArray *enclosingFunction /* = 0 */,
                                          CallAST **enclosingFunctionCall /* = 0 */)
{
    *type = TypeNone;
    if (enclosingFunction)
        enclosingFunction->clear();
    if (enclosingFunctionCall)
        *enclosingFunctionCall = 0;

    if (path.isEmpty())
        return 0;

    ExpressionAST *literal = path.last()->asExpression();
    if (literal) {
        if (literal->asStringLiteral()) {
            // Check for Objective C string (@"bla")
            const QChar firstChar = file->charAt(file->startOf(literal));
            *type = firstChar == QLatin1Char('@') ? TypeObjCString : TypeString;
        } else if (NumericLiteralAST *numericLiteral = literal->asNumericLiteral()) {
            // character ('c') constants are numeric.
            if (file->tokenAt(numericLiteral->literal_token).is(T_CHAR_LITERAL))
                *type = TypeChar;
1012
        }
1013
    }
1014

1015 1016 1017 1018 1019 1020 1021 1022
    if (*type != TypeNone && enclosingFunction && path.size() > 1) {
        if (CallAST *call = path.at(path.size() - 2)->asCall()) {
            if (call->base_expression) {
                if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                    if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
                        *enclosingFunction = file->tokenAt(functionName->identifier_token).identifier->chars();
                        if (enclosingFunctionCall)
                            *enclosingFunctionCall = call;
1023 1024 1025 1026
                    }
                }
            }
        }
1027 1028 1029
    }
    return literal;
}
1030

1031
void WrapStringLiteral::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
1032 1033 1034 1035 1036 1037 1038 1039 1040
{
    typedef CppQuickFixOperation::Ptr OperationPtr;

    Type type = TypeNone;
    QByteArray enclosingFunction;
    const QList<AST *> &path = interface->path();
    CppRefactoringFilePtr file = interface->currentFile();
    ExpressionAST *literal = WrapStringLiteral::analyze(path, file, &type, &enclosingFunction);
    if (!literal || type == TypeNone)
1041
        return;
1042 1043 1044
    if ((type == TypeChar && enclosingFunction == "QLatin1Char")
        || isQtStringLiteral(enclosingFunction)
        || isQtStringTranslation(enclosingFunction))
1045
        return;
1046

1047 1048 1049
    const int priority = path.size() - 1; // very high priority
    if (type == TypeChar) {
        unsigned actions = EncloseInQLatin1CharAction;
1050
        QString description = msgQtStringLiteralDescription(WrapStringLiteral::replacement(actions));
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
        result << OperationPtr(new Operation(interface, priority, actions,
                                             description, literal));
        if (NumericLiteralAST *charLiteral = literal->asNumericLiteral()) {
            const QByteArray contents(file->tokenAt(charLiteral->literal_token).identifier->chars());
            if (!charToStringEscapeSequences(contents).isEmpty()) {
                actions = DoubleQuoteAction | ConvertEscapeSequencesToStringAction;
                description = QApplication::translate("CppTools::QuickFix",
                              "Convert to String Literal");
                result << OperationPtr(new Operation(interface, priority, actions,
                                                     description, literal));
            }
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
    } else {
        const unsigned objectiveCActions = type == TypeObjCString ?
                                           unsigned(RemoveObjectiveCAction) : 0u;
        unsigned actions = 0;
        if (StringLiteralAST *stringLiteral = literal->asStringLiteral()) {
            const QByteArray contents(file->tokenAt(stringLiteral->literal_token).identifier->chars());
            if (!stringToCharEscapeSequences(contents).isEmpty()) {
                actions = EncloseInQLatin1CharAction | SingleQuoteAction
                          | ConvertEscapeSequencesToCharAction | objectiveCActions;
                QString description = QApplication::translate("CppTools::QuickFix",
                                      "Convert to Character Literal and Enclose in QLatin1Char(...)");
                result << OperationPtr(new Operation(interface, priority,
                                                     actions, description, literal));
                actions &= ~EncloseInQLatin1CharAction;
                description = QApplication::translate("CppTools::QuickFix",
                              "Convert to Character Literal");
                result << OperationPtr(new Operation(interface, priority