cppquickfixes.cpp 66.5 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
30 31 32
**
**************************************************************************/

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

#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>
59
#include <cplusplus/ModelManagerInterface.h>
60 61
#include <cplusplus/CppRewriter.h>
#include <cpptools/cpptoolsconstants.h>
62
#include <cpptools/cpprefactoringchanges.h>
63
#include <cpptools/insertionpointlocator.h>
64
#include <cpptools/cpptoolsreuse.h>
65 66
#include <cpptools/cppclassesfilter.h>
#include <cpptools/searchsymbols.h>
67
#include <extensionsystem/iplugin.h>
68
#include <extensionsystem/pluginmanager.h>
69

Friedemann Kleint's avatar
Friedemann Kleint committed
70
#include <QtCore/QFileInfo>
71 72 73 74
#include <QtGui/QApplication>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>

75 76
#include <cctype>

77 78
using namespace CppEditor;
using namespace CppEditor::Internal;
79
using namespace CppTools;
80 81 82 83
using namespace TextEditor;
using namespace CPlusPlus;
using namespace Utils;

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

89 90 91 92 93 94 95
namespace {

/*
    Rewrite
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
96 97

    Activates on: <= < > >= == !=
98 99 100 101
*/
class UseInverseOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
102
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
103 104
    {
        QList<CppQuickFixOperation::Ptr> result;
105
        CppRefactoringFilePtr file = interface->currentFile();
106

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

        Kind invertToken;
116
        switch (file->tokenAt(binary->binary_op_token).kind()) {
117 118 119 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:
            return result;
        }

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

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

        QString replacement;

    public:
Leandro Melo's avatar
Leandro Melo committed
153 154 155
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
            int priority, BinaryExpressionAST *binary, Kind invertToken)
            : CppQuickFixOperation(interface, priority)
156
            , binary(binary), nested(0), negation(0)
157 158 159 160 161 162 163
        {
            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
164
                nested = interface->path()[priority - 1]->asNestedExpression();
165 166 167

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

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

179
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
180 181 182 183
        {
            ChangeSet changes;
            if (negation) {
                // can't remove parentheses since that might break precedence
184
                changes.remove(currentFile->range(negation->unary_op_token));
185
            } else if (nested) {
186
                changes.insert(currentFile->startOf(nested), "!");
187
            } else {
188 189
                changes.insert(currentFile->startOf(binary), "!(");
                changes.insert(currentFile->endOf(binary), ")");
190
            }
191
            changes.replace(currentFile->range(binary->binary_op_token), replacement);
192 193
            currentFile->setChangeSet(changes);
            currentFile->apply();
194 195 196 197 198 199 200 201 202 203
        }
    };
};

/*
    Rewrite
    a op b

    As
    b flipop a
204 205

    Activates on: <= < > >= == != && ||
206 207 208 209
*/
class FlipBinaryOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
210
    virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
211 212
    {
        QList<QuickFixOperation::Ptr> result;
Leandro Melo's avatar
Leandro Melo committed
213
        const QList<AST *> &path = interface->path();
214
        CppRefactoringFilePtr file = interface->currentFile();
215 216 217 218 219

        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return result;
Leandro Melo's avatar
Leandro Melo committed
220
        if (! interface->isCursorOn(binary->binary_op_token))
221 222 223
            return result;

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

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

Leandro Melo's avatar
Leandro Melo committed
254
        result.append(QuickFixOperation::Ptr(new Operation(interface, index, binary, replacement)));
255 256 257 258 259 260 261
        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
262 263 264
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
                  int priority, BinaryExpressionAST *binary, QString replacement)
            : CppQuickFixOperation(interface)
265 266 267 268 269 270 271 272 273 274 275 276 277 278
            , 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);
        }

279
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
280 281 282
        {
            ChangeSet changes;

283
            changes.flip(currentFile->range(binary->left_expression), currentFile->range(binary->right_expression));
284
            if (! replacement.isEmpty())
285
                changes.replace(currentFile->range(binary->binary_op_token), replacement);
286

287 288
            currentFile->setChangeSet(changes);
            currentFile->apply();
289 290 291 292 293 294 295 296 297 298 299 300 301 302
        }

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

/*
    Rewrite
    !a && !b

    As
    !(a || b)
303 304

    Activates on: &&
305 306 307 308
*/
class RewriteLogicalAndOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
309
    virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
310 311 312
    {
        QList<QuickFixOperation::Ptr> result;
        BinaryExpressionAST *expression = 0;
Leandro Melo's avatar
Leandro Melo committed
313
        const QList<AST *> &path = interface->path();
314
        CppRefactoringFilePtr file = interface->currentFile();
315 316 317 318 319 320 321 322 323 324 325

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

        if (! expression)
            return result;

Leandro Melo's avatar
Leandro Melo committed
326
        if (! interface->isCursorOn(expression->binary_op_token))
327 328
            return result;

Leandro Melo's avatar
Leandro Melo committed
329
        QSharedPointer<Operation> op(new Operation(interface));
330 331

        if (expression->match(op->pattern, &matcher) &&
332 333 334
                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)) {
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            op->setDescription(QApplication::translate("CppTools::QuickFix", "Rewrite Condition Using ||"));
            op->setPriority(index);
            result.append(op);
        }

        return result;
    }

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

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

361
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
362 363
        {
            ChangeSet changes;
364 365 366 367 368
            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);
369 370 371
            changes.insert(start, QLatin1String("!("));
            changes.insert(end, QLatin1String(")"));

372 373 374
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
375 376 377 378 379 380 381
        }
    };

private:
    ASTMatcher matcher;
};

382 383 384 385 386 387 388
/*
    Rewrite
    int *a, b;

    As
    int *a;
    int b;
389 390

    Activates on: the type or the variable names.
391
*/
392 393 394 395 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
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:
Leandro Melo's avatar
Leandro Melo committed
422
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
423 424 425
    {
        QList<CppQuickFixOperation::Ptr> result;
        CoreDeclaratorAST *core_declarator = 0;
Leandro Melo's avatar
Leandro Melo committed
426
        const QList<AST *> &path = interface->path();
427
        CppRefactoringFilePtr file = interface->currentFile();
428 429 430 431 432 433 434 435 436 437 438

        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;

439
                    const int cursorPosition = file->cursor().selectionStart();
440

441 442
                    const int startOfDeclSpecifier = file->startOf(declaration->decl_specifier_list->firstToken());
                    const int endOfDeclSpecifier = file->endOf(declaration->decl_specifier_list->lastToken() - 1);
443 444 445

                    if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier) {
                        // the AST node under cursor is a specifier.
Leandro Melo's avatar
Leandro Melo committed
446
                        return singleResult(new Operation(interface, index, declaration));
447 448
                    }

Leandro Melo's avatar
Leandro Melo committed
449
                    if (core_declarator && interface->isCursorOn(core_declarator)) {
450
                        // got a core-declarator under the text cursor.
Leandro Melo's avatar
Leandro Melo committed
451
                        return singleResult(new Operation(interface, index, declaration));
452 453 454 455 456 457 458 459 460 461 462 463 464 465
                    }
                }

                break;
            }
        }

        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
466 467
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, SimpleDeclarationAST *decl)
            : CppQuickFixOperation(interface, priority)
468 469 470 471 472 473
            , declaration(decl)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split Declaration"));
        }

474
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
475 476 477 478
        {
            ChangeSet changes;

            SpecifierListAST *specifiers = declaration->decl_specifier_list;
479 480 481
            int declSpecifiersStart = currentFile->startOf(specifiers->firstToken());
            int declSpecifiersEnd = currentFile->endOf(specifiers->lastToken() - 1);
            int insertPos = currentFile->endOf(declaration->semicolon_token);
482 483 484 485 486 487 488 489 490

            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(" "));
491
                changes.move(currentFile->range(declarator), insertPos);
492 493
                changes.insert(insertPos, QLatin1String(";"));

494 495
                const int prevDeclEnd = currentFile->endOf(prevDeclarator);
                changes.remove(prevDeclEnd, currentFile->startOf(declarator));
496 497 498 499

                prevDeclarator = declarator;
            }

500 501 502
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(declaration));
            currentFile->apply();
503 504 505 506 507 508 509 510 511
        }

    private:
        SimpleDeclarationAST *declaration;
    };
};

/*
    Add curly braces to a if statement that doesn't already contain a
512 513 514 515 516 517 518 519
    compound statement. I.e.

    if (a)
        b;
    becomes
    if (a) {
        b;
    }
520 521

    Activates on: the if
522 523 524 525
*/
class AddBracesToIfOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
526
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
527
    {
Leandro Melo's avatar
Leandro Melo committed
528
        const QList<AST *> &path = interface->path();
529 530 531 532

        // 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
533
        if (ifStatement && interface->isCursorOn(ifStatement->if_token) && ifStatement->statement
534
            && ! ifStatement->statement->asCompoundStatement()) {
Leandro Melo's avatar
Leandro Melo committed
535
            return singleResult(new Operation(interface, index, ifStatement->statement));
536 537 538 539 540 541 542
        }

        // 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
543
                && interface->isCursorOn(ifStatement->statement)
544
                && ! ifStatement->statement->asCompoundStatement()) {
Leandro Melo's avatar
Leandro Melo committed
545
                return singleResult(new Operation(interface, index, ifStatement->statement));
546 547 548 549 550 551 552 553 554 555 556 557 558
            }
        }

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

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
559 560
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, StatementAST *statement)
            : CppQuickFixOperation(interface, priority)
561 562 563 564 565 566
            , _statement(statement)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Add Curly Braces"));
        }

567
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
568 569 570
        {
            ChangeSet changes;

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

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

577 578 579
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(Utils::ChangeSet::Range(start, end));
            currentFile->apply();
580 581 582 583 584 585 586 587 588 589 590 591 592 593
        }

    private:
        StatementAST *_statement;
    };
};

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

    With
    Type name = foo;
    if (name) {...}
594 595

    Activates on: the name of the introduced variable
596 597 598 599
*/
class MoveDeclarationOutOfIfOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
600
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
601
    {
Leandro Melo's avatar
Leandro Melo committed
602 603
        const QList<AST *> &path = interface->path();
        QSharedPointer<Operation> op(new Operation(interface));
604 605 606 607 608 609 610 611 612 613

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

Leandro Melo's avatar
Leandro Melo committed
614
                    if (interface->isCursorOn(op->core)) {
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
                        QList<CppQuickFixOperation::Ptr> result;
                        op->setPriority(index);
                        result.append(op);
                        return result;
                    }
                }
            }
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
631 632
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
633 634 635 636 637 638 639 640
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

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

641
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
642 643 644
        {
            ChangeSet changes;

645
            changes.copy(currentFile->range(core), currentFile->startOf(condition));
646

647 648
            int insertPos = currentFile->startOf(pattern);
            changes.move(currentFile->range(condition), insertPos);
649 650
            changes.insert(insertPos, QLatin1String(";\n"));

651 652 653
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
654 655 656 657
        }

        ASTMatcher matcher;
        ASTPatternBuilder mk;
658
        CPPEditorWidget *editor;
659 660 661 662 663 664 665 666 667 668 669 670 671
        ConditionAST *condition;
        IfStatementAST *pattern;
        CoreDeclaratorAST *core;
    };
};

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

    With
    Type name;
    while ((name = foo()) != 0) {...}
672 673

    Activates on: the name of the introduced variable
674 675 676 677
*/
class MoveDeclarationOutOfWhileOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
678
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
679
    {
Leandro Melo's avatar
Leandro Melo committed
680 681
        const QList<AST *> &path = interface->path();
        QSharedPointer<Operation> op(new Operation(interface));
682 683 684 685 686 687 688 689 690 691 692

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

693
                    else if (! declarator->equal_token)
694 695 696 697 698
                        return noResult();

                    else if (! declarator->initializer)
                        return noResult();

Leandro Melo's avatar
Leandro Melo committed
699
                    if (interface->isCursorOn(op->core)) {
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
                        QList<CppQuickFixOperation::Ptr> result;
                        op->setPriority(index);
                        result.append(op);
                        return result;
                    }
                }
            }
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
716 717
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
718 719 720 721 722 723 724 725
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

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

726
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
727 728 729
        {
            ChangeSet changes;

730 731
            changes.insert(currentFile->startOf(condition), QLatin1String("("));
            changes.insert(currentFile->endOf(condition), QLatin1String(") != 0"));
732

733 734 735 736
            int insertPos = currentFile->startOf(pattern);
            const int conditionStart = currentFile->startOf(condition);
            changes.move(conditionStart, currentFile->startOf(core), insertPos);
            changes.copy(currentFile->range(core), insertPos);
737 738
            changes.insert(insertPos, QLatin1String(";\n"));

739 740 741
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
742 743 744 745
        }

        ASTMatcher matcher;
        ASTPatternBuilder mk;
746
        CPPEditorWidget *editor;
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
        ConditionAST *condition;
        WhileStatementAST *pattern;
        CoreDeclaratorAST *core;
    };
};

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

  with
     if (something) {
        if (something_else) {
        }
     }

  and
    if (something || something_else)
      x;

  with
    if (something)
      x;
    else if (something_else)
      x;
773 774

    Activates on: && or ||
775 776 777 778
*/
class SplitIfStatementOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
779
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
780 781
    {
        IfStatementAST *pattern = 0;
Leandro Melo's avatar
Leandro Melo committed
782
        const QList<AST *> &path = interface->path();
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

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

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

803
            Token binaryToken = interface->currentFile()->tokenAt(condition->binary_op_token);
804 805 806 807 808 809 810 811 812 813 814 815 816

            // 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 noResult();
                // we can't reliably split &&s in ifs with an else branch
                if (splitKind == T_AMPER_AMPER && pattern->else_statement)
                    return noResult();
            } else if (splitKind != binaryToken.kind()) {
                return noResult();
            }

Leandro Melo's avatar
Leandro Melo committed
817 818
            if (interface->isCursorOn(condition->binary_op_token))
                return singleResult(new Operation(interface, index, pattern, condition));
819 820 821 822 823 824 825 826 827
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
828
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority,
829
                  IfStatementAST *pattern, BinaryExpressionAST *condition)
Leandro Melo's avatar
Leandro Melo committed
830
            : CppQuickFixOperation(interface, priority)
831 832 833 834 835 836 837
            , pattern(pattern)
            , condition(condition)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split if Statement"));
        }

838
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
839
        {
840
            const Token binaryToken = currentFile->tokenAt(condition->binary_op_token);
841 842

            if (binaryToken.is(T_AMPER_AMPER))
843
                splitAndCondition(currentFile);
844
            else
845
                splitOrCondition(currentFile);
846 847
        }

848
        void splitAndCondition(CppRefactoringFilePtr currentFile)
849 850 851
        {
            ChangeSet changes;

852
            int startPos = currentFile->startOf(pattern);
853
            changes.insert(startPos, QLatin1String("if ("));
854
            changes.move(currentFile->range(condition->left_expression), startPos);
855 856
            changes.insert(startPos, QLatin1String(") {\n"));

857 858 859
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
            changes.insert(currentFile->endOf(pattern), QLatin1String("\n}"));
860

861 862 863
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
864 865
        }

866
        void splitOrCondition(CppRefactoringFilePtr currentFile)
867 868 869 870 871 872
        {
            ChangeSet changes;

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

873
            int insertPos = currentFile->endOf(ifTrueStatement);
874 875 876 877 878 879
            if (compoundStatement)
                changes.insert(insertPos, QLatin1String(" "));
            else
                changes.insert(insertPos, QLatin1String("\n"));
            changes.insert(insertPos, QLatin1String("else if ("));

880 881
            const int rExprStart = currentFile->startOf(condition->right_expression);
            changes.move(rExprStart, currentFile->startOf(pattern->rparen_token), insertPos);
882 883
            changes.insert(insertPos, QLatin1String(")"));

884 885
            const int rParenEnd = currentFile->endOf(pattern->rparen_token);
            changes.copy(rParenEnd, currentFile->endOf(pattern->statement), insertPos);
886

887 888
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
889

890 891 892
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
893 894 895 896 897 898 899 900 901 902
        }

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

/*
  Replace
903
    "abcd" -> QLatin1String("abcd")
904
    @"abcd" -> QLatin1String("abcd")
905 906 907 908
    'a' -> QLatin1Char('a')
  Except if they are already enclosed in
    QLatin1Char, QT_TRANSLATE_NOOP, tr,
    trUtf8, QLatin1Literal, QLatin1String
909 910

    Activates on: the string literal
911
*/
912 913 914 915 916 917 918

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

919 920 921 922 923
class WrapStringLiteral: public CppQuickFixFactory
{
public:
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

Leandro Melo's avatar
Leandro Melo committed
924
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
925 926 927
    {
        ExpressionAST *literal = 0;
        Type type = TypeNone;
Leandro Melo's avatar
Leandro Melo committed
928
        const QList<AST *> &path = interface->path();
929
        CppRefactoringFilePtr file = interface->currentFile();
930 931 932 933 934 935 936 937

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

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

        if (! literal) {
            literal = path.last()->asNumericLiteral();
938
            if (!literal || !file->tokenAt(literal->asNumericLiteral()->literal_token).is(T_CHAR_LITERAL))
939 940 941 942 943 944 945 946 947 948
                return noResult();
            else
                type = TypeChar;
        } else {
            type = TypeString;
        }

        if (path.size() > 1) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
Roberto Raggi's avatar
Roberto Raggi committed
949 950
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
951
                            const QByteArray id(file->tokenAt(functionName->identifier_token).identifier->chars());
Roberto Raggi's avatar
Roberto Raggi committed
952 953

                            if (id == "QT_TRANSLATE_NOOP" || id == "tr" || id == "trUtf8"
954
                                    || (type == TypeString && isQtStringLiteral(id))
Roberto Raggi's avatar
Roberto Raggi committed
955 956 957
                                    || (type == TypeChar && id == "QLatin1Char"))
                                return noResult(); // skip it
                        }
958 959 960 961 962 963
                    }
                }
            }
        }

        if (type == TypeString) {
964
            if (file->charAt(file->startOf(literal)) == QLatin1Char('@'))
965 966
                type = TypeObjCString;
        }
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

        QList<CppQuickFixOperation::Ptr> result;

        const int priority = path.size() - 1; // very high priority
        if (type == TypeChar) {
            const QString replacement = QLatin1String("QLatin1Char");
            const QString description =
                QApplication::translate("CppTools::QuickFix", "Enclose in %1(...)")
                           .arg(replacement);

            result.push_back(CppQuickFixOperation::Ptr(new Operation(interface, priority, type,
                                                       replacement, description, literal)));
        } else {
            QString replacement = QLatin1String("QLatin1String");
            result.push_back(CppQuickFixOperation::Ptr(new Operation(interface, priority, type,
                                                                     replacement, msgQtStringLiteralDescription(replacement, 4),
                                                                     literal)));
            replacement = QLatin1String("QStringLiteral");
            result.push_back(CppQuickFixOperation::Ptr(new Operation(interface, priority, type,
                                                                     replacement, msgQtStringLiteralDescription(replacement, 5),
                                                                     literal)));
        }
        return result;
990 991 992 993 994 995
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
996 997
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority,
                  Type type, const QString &replacement, const QString &description,
998
                  ExpressionAST *literal)
Leandro Melo's avatar
Leandro Melo committed
999
            : CppQuickFixOperation(interface, priority)
1000
            , type(type), replacement(replacement)
1001 1002
            , literal(literal)
        {
1003 1004
            setDescription(description);
       }
1005

1006
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
1007 1008 1009
        {
            ChangeSet changes;

1010
            const int startPos = currentFile->startOf(literal);
1011
            const QString fullReplacement = replacement + QLatin1Char('(');
1012
            if (type == TypeObjCString)
1013
                changes.replace(startPos, startPos + 1, fullReplacement);
1014
            else
1015
                changes.insert(startPos, fullReplacement);
1016

1017
            changes.insert(currentFile->endOf(literal), QLatin1String(")"));
1018

1019 1020
            currentFile->setChangeSet(changes);
            currentFile->apply();
1021 1022 1023
        }

    private:
1024 1025
        const Type type;
        const QString replacement;
1026 1027
        ExpressionAST *literal;
    };
1028

1029 1030 1031 1032 1033 1034 1035 1036 1037
};

/*
  Replace
    "abcd"
  With
    tr("abcd") or
    QCoreApplication::translate("CONTEXT", "abcd") or
    QT_TRANSLATE_NOOP("GLOBAL", "abcd")
1038
  depending on what is available.
1039 1040

    Activates on: the string literal
1041 1042 1043 1044 1045 1046
*/
class TranslateStringLiteral: public CppQuickFixFactory
{
public:
    enum TranslationOption { unknown, useTr, useQCoreApplicationTranslate, useMacro };

Leandro Melo's avatar
Leandro Melo committed
1047
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
1048
    {
Leandro Melo's avatar
Leandro Melo committed
1049
        const QList<AST *> &path = interface->path();
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        // Initialize
        ExpressionAST *literal = 0;
        QString trContext;

        if (path.isEmpty())
            return noResult();

        literal = path.last()->asStringLiteral();
        if (!literal)
            return noResult(); // No string, nothing to do

        // Do we already have a translation markup?
        if (path.size() >= 2) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
Roberto Raggi's avatar
Roberto Raggi committed
1065 1066
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
1067
                            const QByteArray id(interface->currentFile()->tokenAt(functionName->identifier_token).identifier->chars());
Roberto Raggi's avatar
Roberto Raggi committed
1068 1069 1070 1071

                            if (id == "tr" || id == "trUtf8"
                                    || id == "translate"
                                    || id == "QT_TRANSLATE_NOOP"
1072
                                    || isQtStringLiteral(id))
Roberto Raggi's avatar
Roberto Raggi committed
1073 1074
                                return noResult(); // skip it
                        }
1075 1076 1077 1078 1079
                    }
                }
            }
        }

Leandro Melo's avatar
Leandro Melo committed
1080
        QSharedPointer<Control> control = interface->context().control();
1081
        const Name *trName = control->identifier("tr");
1082 1083 1084 1085 1086 1087

        // 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;
Leandro Melo's avatar
Leandro Melo committed
1088
                ClassOrNamespace *b = interface->context().lookupType(function);
1089 1090 1091 1092 1093 1094
                if (b) {
                    // Do we have a tr method?
                    foreach(const LookupItem &r, b->find(trName)) {
                        Symbol *s = r.declaration();
                        if (s->type()->isFunctionType()) {
                            // no context required for tr
Leandro Melo's avatar
Leandro Melo committed
1095
                            return singleResult(new Operation(interface, path.size() - 1, literal, useTr, trContext));
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
                        }
                    }
                }
                // We need to do a QCA::translate, so we need a context.
                // Use fully qualified class name:
                Overview oo;
                foreach (const Name *n, LookupContext::path(function)) {
                    if (!trContext.isEmpty())
                        trContext.append(QLatin1String("::"));
                    trContext.append(oo.prettyName(n));
                }
                // ... or global if none available!
                if (trContext.isEmpty())
                    trContext = QLatin1String("GLOBAL");
Leandro Melo's avatar
Leandro Melo committed
1110
                return singleResult(new Operation(interface, path.size() - 1, literal, useQCoreApplicationTranslate, trContext));
1111 1112 1113 1114
            }
        }

        // We need to use Q_TRANSLATE_NOOP
Leandro Melo's avatar
Leandro Melo committed
1115
        return singleResult(new Operation(interface, path.size() - 1, literal, useMacro, QLatin1String("GLOBAL")));
1116 1117 1118 1119 1120 1121
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
1122 1123
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, ExpressionAST *literal, TranslationOption option, const QString &context)
            : CppQuickFixOperation(interface, priority)
1124 1125 1126 1127
            , m_literal(literal)
            , m_option(option)
            , m_context(context)
        {
1128
            setDescription(QApplication::translate("CppTools::QuickFix", "Mark as Translatable"));
1129 1130
        }

1131
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
1132 1133 1134
        {
            ChangeSet changes;

1135
            const int startPos = currentFile->startOf(m_literal);
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
            QString replacement(QLatin1String("tr("));
            if (m_option == useQCoreApplicationTranslate) {
                replacement = QLatin1String("QCoreApplication::translate(\"")
                        + m_context + QLatin1String("\", ");
            } else if (m_option == useMacro) {
                replacement = QLatin1String("QT_TRANSLATE_NOOP(\"")
                        + m_context + QLatin1String("\", ");
            }

            changes.insert(startPos, replacement);
1146
            changes.insert(currentFile->endOf(m_literal), QLatin1String(")"));