cppquickfixes.cpp 76.7 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 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 <cpptools/symbolfinder.h>
68
#include <extensionsystem/iplugin.h>
69
#include <extensionsystem/pluginmanager.h>
70

71 72
#include <utils/qtcassert.h>

Friedemann Kleint's avatar
Friedemann Kleint committed
73
#include <QtCore/QFileInfo>
74 75 76
#include <QtGui/QApplication>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
77 78
#include <cctype>

79 80
using namespace CppEditor;
using namespace CppEditor::Internal;
81
using namespace CppTools;
82 83 84 85
using namespace TextEditor;
using namespace CPlusPlus;
using namespace Utils;

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

91 92 93 94 95
static inline bool isQtStringTranslation(const QByteArray &id)
{
    return id == "tr" || id == "trUtf8" || id == "translate" || id == "QT_TRANSLATE_NOOP";
}

96 97 98 99 100 101 102
namespace {

/*
    Rewrite
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
103 104

    Activates on: <= < > >= == !=
105 106 107 108
*/
class UseInverseOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
109
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
110 111
    {
        QList<CppQuickFixOperation::Ptr> result;
112
        CppRefactoringFilePtr file = interface->currentFile();
113

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

        Kind invertToken;
123
        switch (file->tokenAt(binary->binary_op_token).kind()) {
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        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
146
        result.append(CppQuickFixOperation::Ptr(new Operation(interface, index, binary, invertToken)));
147 148 149 150 151 152 153 154 155 156 157 158 159
        return result;
    }

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

        QString replacement;

    public:
Leandro Melo's avatar
Leandro Melo committed
160 161 162
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
            int priority, BinaryExpressionAST *binary, Kind invertToken)
            : CppQuickFixOperation(interface, priority)
163
            , binary(binary), nested(0), negation(0)
164 165 166 167 168 169 170
        {
            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
171
                nested = interface->path()[priority - 1]->asNestedExpression();
172 173 174

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

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

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

/*
    Rewrite
    a op b

    As
    b flipop a
211 212

    Activates on: <= < > >= == != && ||
213 214 215 216
*/
class FlipBinaryOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
217
    virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
218 219
    {
        QList<QuickFixOperation::Ptr> result;
Leandro Melo's avatar
Leandro Melo committed
220
        const QList<AST *> &path = interface->path();
221
        CppRefactoringFilePtr file = interface->currentFile();
222 223 224 225 226

        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return result;
Leandro Melo's avatar
Leandro Melo committed
227
        if (! interface->isCursorOn(binary->binary_op_token))
228 229 230
            return result;

        Kind flipToken;
231
        switch (file->tokenAt(binary->binary_op_token).kind()) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        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
261
        result.append(QuickFixOperation::Ptr(new Operation(interface, index, binary, replacement)));
262 263 264 265 266 267 268
        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
269 270 271
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
                  int priority, BinaryExpressionAST *binary, QString replacement)
            : CppQuickFixOperation(interface)
272 273 274 275 276 277 278 279 280 281 282 283 284 285
            , 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);
        }

286
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
287 288 289
        {
            ChangeSet changes;

290
            changes.flip(currentFile->range(binary->left_expression), currentFile->range(binary->right_expression));
291
            if (! replacement.isEmpty())
292
                changes.replace(currentFile->range(binary->binary_op_token), replacement);
293

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

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

/*
    Rewrite
    !a && !b

    As
    !(a || b)
310 311

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

        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
333
        if (! interface->isCursorOn(expression->binary_op_token))
334 335
            return result;

Leandro Melo's avatar
Leandro Melo committed
336
        QSharedPointer<Operation> op(new Operation(interface));
337 338

        if (expression->match(op->pattern, &matcher) &&
339 340 341
                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)) {
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
            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
359 360
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
361 362 363 364 365 366 367
            , mk(new ASTPatternBuilder)
        {
            left = mk->UnaryExpression();
            right = mk->UnaryExpression();
            pattern = mk->BinaryExpression(left, right);
        }

368
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
369 370
        {
            ChangeSet changes;
371 372 373 374 375
            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);
376 377 378
            changes.insert(start, QLatin1String("!("));
            changes.insert(end, QLatin1String(")"));

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

private:
    ASTMatcher matcher;
};

389 390 391 392 393 394 395
/*
    Rewrite
    int *a, b;

    As
    int *a;
    int b;
396 397

    Activates on: the type or the variable names.
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 427 428
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
429
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
430 431 432
    {
        QList<CppQuickFixOperation::Ptr> result;
        CoreDeclaratorAST *core_declarator = 0;
Leandro Melo's avatar
Leandro Melo committed
433
        const QList<AST *> &path = interface->path();
434
        CppRefactoringFilePtr file = interface->currentFile();
435 436 437 438 439 440 441 442 443 444 445

        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;

446
                    const int cursorPosition = file->cursor().selectionStart();
447

448 449
                    const int startOfDeclSpecifier = file->startOf(declaration->decl_specifier_list->firstToken());
                    const int endOfDeclSpecifier = file->endOf(declaration->decl_specifier_list->lastToken() - 1);
450 451 452

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

Leandro Melo's avatar
Leandro Melo committed
456
                    if (core_declarator && interface->isCursorOn(core_declarator)) {
457
                        // got a core-declarator under the text cursor.
Leandro Melo's avatar
Leandro Melo committed
458
                        return singleResult(new Operation(interface, index, declaration));
459 460 461 462 463 464 465 466 467 468 469 470 471 472
                    }
                }

                break;
            }
        }

        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
473 474
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, SimpleDeclarationAST *decl)
            : CppQuickFixOperation(interface, priority)
475 476 477 478 479 480
            , declaration(decl)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split Declaration"));
        }

481
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
482 483 484 485
        {
            ChangeSet changes;

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

            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(" "));
498
                changes.move(currentFile->range(declarator), insertPos);
499 500
                changes.insert(insertPos, QLatin1String(";"));

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

                prevDeclarator = declarator;
            }

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

    private:
        SimpleDeclarationAST *declaration;
    };
};

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

    if (a)
        b;
    becomes
    if (a) {
        b;
    }
527 528

    Activates on: the if
529 530 531 532
*/
class AddBracesToIfOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
533
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
534
    {
Leandro Melo's avatar
Leandro Melo committed
535
        const QList<AST *> &path = interface->path();
536 537 538 539

        // 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
540
        if (ifStatement && interface->isCursorOn(ifStatement->if_token) && ifStatement->statement
541
            && ! ifStatement->statement->asCompoundStatement()) {
Leandro Melo's avatar
Leandro Melo committed
542
            return singleResult(new Operation(interface, index, ifStatement->statement));
543 544 545 546 547 548 549
        }

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

        // ### 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
566 567
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, StatementAST *statement)
            : CppQuickFixOperation(interface, priority)
568 569 570 571 572 573
            , _statement(statement)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Add Curly Braces"));
        }

574
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
575 576 577
        {
            ChangeSet changes;

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

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

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

    private:
        StatementAST *_statement;
    };
};

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

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

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

        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
621
                    if (interface->isCursorOn(op->core)) {
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
                        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
638 639
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
640 641 642 643 644 645 646 647
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

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

648
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
649 650 651
        {
            ChangeSet changes;

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

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

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

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

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

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

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

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

700
                    else if (! declarator->equal_token)
701 702 703 704 705
                        return noResult();

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

Leandro Melo's avatar
Leandro Melo committed
706
                    if (interface->isCursorOn(op->core)) {
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
                        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
723 724
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
            : CppQuickFixOperation(interface)
725 726 727 728 729 730 731 732
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

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

733
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
734 735 736
        {
            ChangeSet changes;

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

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

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

        ASTMatcher matcher;
        ASTPatternBuilder mk;
753
        CPPEditorWidget *editor;
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        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;
780 781

    Activates on: && or ||
782 783 784 785
*/
class SplitIfStatementOp: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
786
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
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 801 802 803 804 805 806 807 808 809

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

810
            Token binaryToken = interface->currentFile()->tokenAt(condition->binary_op_token);
811 812 813 814 815 816 817 818 819 820 821 822 823

            // 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
824 825
            if (interface->isCursorOn(condition->binary_op_token))
                return singleResult(new Operation(interface, index, pattern, condition));
826 827 828 829 830 831 832 833 834
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
Leandro Melo's avatar
Leandro Melo committed
835
        Operation(const QSharedPointer<const CppQuickFixAssistInterface> &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
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
846
        {
847
            const Token binaryToken = currentFile->tokenAt(condition->binary_op_token);
848 849

            if (binaryToken.is(T_AMPER_AMPER))
850
                splitAndCondition(currentFile);
851
            else
852
                splitOrCondition(currentFile);
853 854
        }

855
        void splitAndCondition(CppRefactoringFilePtr currentFile)
856 857 858
        {
            ChangeSet changes;

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

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

868 869 870
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
871 872
        }

873
        void splitOrCondition(CppRefactoringFilePtr currentFile)
874 875 876 877 878 879
        {
            ChangeSet changes;

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

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

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

891 892
            const int rParenEnd = currentFile->endOf(pattern->rparen_token);
            changes.copy(rParenEnd, currentFile->endOf(pattern->statement), insertPos);
893

894 895
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
896

897 898 899
            currentFile->setChangeSet(changes);
            currentFile->appendIndentRange(currentFile->range(pattern));
            currentFile->apply();
900 901 902 903 904 905 906 907 908 909
        }

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

/*
  Replace
910 911 912 913 914 915
    "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')
916 917 918
  Except if they are already enclosed in
    QLatin1Char, QT_TRANSLATE_NOOP, tr,
    trUtf8, QLatin1Literal, QLatin1String
919

920
    Activates on: the string or character literal
921
*/
922 923 924 925 926 927 928

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

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

934 935 936
class WrapStringLiteral: public CppQuickFixFactory
{
public:
937 938 939 940 941 942 943 944 945 946 947 948 949
    typedef const QSharedPointer<const CppQuickFixAssistInterface> AssistInterfacePtr;

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

950 951
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

952 953 954 955 956 957 958 959 960 961 962 963
    virtual QList<CppQuickFixOperation::Ptr> match(const AssistInterfacePtr &interface);
    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
964
    {
965 966 967 968
    public:
        Operation(const AssistInterfacePtr &interface, int priority,
                  unsigned actions, const QString &description, ExpressionAST *literal,
                  const QString &translationContext = QString());
969

970 971 972 973 974 975 976
        virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &);
    private:
        const unsigned m_actions;
        ExpressionAST *m_literal;
        const QString m_translationContext;
    };
};
977

978 979 980
/* 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...) */
981

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
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;
1007
        }
1008
    }
1009

1010 1011 1012 1013 1014 1015 1016 1017
    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;
1018 1019 1020 1021
                    }
                }
            }
        }
1022 1023 1024
    }
    return literal;
}
1025

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
QList<CppQuickFixOperation::Ptr> WrapStringLiteral::match(const AssistInterfacePtr &interface)
{
    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)
        return noResult();
    if ((type == TypeChar && enclosingFunction == "QLatin1Char")
        || isQtStringLiteral(enclosingFunction)
        || isQtStringTranslation(enclosingFunction))
        return noResult();
1041

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    QList<CppQuickFixOperation::Ptr> result;
    const int priority = path.size() - 1; // very high priority
    if (type == TypeChar) {
        unsigned actions = EncloseInQLatin1CharAction;
        QString description =
            msgQtStringLiteralDescription(WrapStringLiteral::replacement(actions));
        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));
            }
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
    } 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,
                                                     actions, description, literal));
            }
        }
        actions = EncloseInQLatin1StringAction | objectiveCActions;
        result << OperationPtr(new Operation(interface, priority, actions,
                                             msgQtStringLiteralDescription(WrapStringLiteral::replacement(actions), 4),
                                             literal));
        actions = EncloseInQStringLiteralAction | objectiveCActions;
        result << OperationPtr(new Operation(interface, priority, actions,
                                             msgQtStringLiteralDescription(WrapStringLiteral::replacement(actions), 5),
                                             literal));
1088
    }
1089 1090
    return result;
}
1091

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
QString WrapStringLiteral::replacement(unsigned actions)
{
    if (actions & EncloseInQLatin1CharAction)
        return QLatin1String("QLatin1Char");
    if (actions & EncloseInQLatin1StringAction)
        return QLatin1String("QLatin1String");
    if (actions & EncloseInQStringLiteralAction)
        return QLatin1String("QStringLiteral");
    if (actions & TranslateTrAction)
        return QLatin1String("tr");
    if (actions & TranslateQCoreApplicationAction)
        return QLatin1String("QCoreApplication::translate");
    if (actions & TranslateNoopAction)
        return QLatin1String("QT_TRANSLATE_NOOP");
    return QString();
}
1108

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
/* Convert single-character string literals into character literals with some
 * special cases "a" --> 'a', "'" --> '\'', "\n" --> '\n', "\"" --> '"'. */
QByteArray WrapStringLiteral::stringToCharEscapeSequences(const QByteArray &content)
{
    if (content.size() == 1)
        return content.at(0) == '\'' ? QByteArray("\\'") : content;
    if (content.size() == 2 && content.at(0) == '\\')
        return content == "\\\"" ? QByteArray(1, '"') : content;
    return QByteArray();
}
1119

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
/* Convert character literal into a string literal with some special cases
 * 'a' -> "a", '\n' -> "\n", '\'' --> "'", '"' --> "\"". */
QByteArray WrapStringLiteral::charToStringEscapeSequences(const QByteArray &content)
{
    if (content.size() == 1)
        return content.at(0) == '"' ? QByteArray("\\\"") : content;
    if (content.size() == 2)
        return content == "\\'" ? QByteArray("'") : content;
    return QByteArray();
}
1130

1131 1132 1133 1134 1135 1136 1137 1138
WrapStringLiteral::Operation::Operation(const AssistInterfacePtr &interface, int priority,
                                        unsigned actions, const QString &description, ExpressionAST *literal,
                                        const QString &translationContext)
    : CppQuickFixOperation(interface, priority), m_actions(actions), m_literal(literal),
      m_translationContext(translationContext)
{
    setDescription(description);
}
1139

1140 1141 1142
void WrapStringLiteral::Operation::performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
{
    ChangeSet changes;
1143

1144 1145
    const int startPos = currentFile->startOf(m_literal);
    const int endPos = currentFile->endOf(m_literal);
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
    // kill leading '@'. No need to adapt endPos, that is done by ChangeSet
    if (m_actions & RemoveObjectiveCAction)
        changes.remove(startPos, startPos + 1);

    // Fix quotes
    if (m_actions & (SingleQuoteAction | DoubleQuoteAction)) {
        const QString newQuote((m_actions & SingleQuoteAction) ? QLatin1Char('\'') : QLatin1Char('"'));
        changes.replace(startPos, startPos + 1, newQuote);
        changes.replace(endPos - 1, endPos, newQuote);
    }

    // Convert single character strings into character constants
    if (m_actions & ConvertEscapeSequencesToCharAction) {
        StringLiteralAST *stringLiteral = m_literal->asStringLiteral();
        QTC_ASSERT(stringLiteral, return ;);
        const QByteArray oldContents(currentFile->tokenAt(stringLiteral->literal_token).identifier->chars());
        const QByteArray newContents = stringToCharEscapeSequences(oldContents);
        QTC_ASSERT(!newContents.isEmpty(), return ;);
        if (oldContents != newContents)
            changes.replace(startPos + 1, endPos -1, QString::fromLatin1(newContents));
    }

    // Convert character constants into strings constants
    if (m_actions & ConvertEscapeSequencesToStringAction) {
        NumericLiteralAST *charLiteral = m_literal->asNumericLiteral(); // char 'c' constants are numerical.
        QTC_ASSERT(charLiteral, return ;);
        const QByteArray oldContents(currentFile->tokenAt(charLiteral->literal_token).identifier->chars());
        const QByteArray newContents = charToStringEscapeSequences(oldContents);
        QTC_ASSERT(!newContents.isEmpty(), return ;);
        if (oldContents != newContents)
            changes.replace(startPos + 1, endPos -1, QString::fromLatin1(newContents));
    }

    // Enclose in literal or translation function, macro.
    if (m_actions & (EncloseActionMask | TranslationMask)) {
        changes.insert(endPos, QString(QLatin1Char(')')));
        QString leading = WrapStringLiteral::replacement(m_actions);
        leading += QLatin1Char('(');
        if (m_actions & (TranslateQCoreApplicationAction | TranslateNoopAction)) {
            leading += QLatin1Char('"');
            leading += m_translationContext;
            leading += QLatin1String("\", ");
        }
        changes.insert(startPos, leading);
    }

    currentFile->setChangeSet(changes);
    currentFile->apply();
}
1196 1197 1198 1199 1200 1201 1202 1203

/*
  Replace
    "abcd"
  With
    tr("abcd") or
    QCoreApplication::translate("CONTEXT", "abcd") or
    QT_TRANSLATE_NOOP("GLOBAL", "abcd")
1204
  depending on what is available.
1205 1206

    Activates on: the string literal
1207 1208 1209 1210
*/
class TranslateStringLiteral: public CppQuickFixFactory
{
public:
Leandro Melo's avatar
Leandro Melo committed
1211
    virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
1212 1213
    {
        // Initialize
1214 1215 1216 1217 1218 1219