cppquickfixes.cpp 60.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "cppeditor.h"
#include "cppquickfix.h"
#include "cppdeclfromdef.h"

#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>
#include <cplusplus/CppRewriter.h>
#include <cpptools/cpptoolsconstants.h>
#include <extensionsystem/iplugin.h>

#include <QtGui/QApplication>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>

using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace TextEditor;
using namespace CPlusPlus;
using namespace Utils;

namespace {

/*
    Rewrite
    a op b -> !(a invop b)
    (a op b) -> !(a invop b)
    !(a op b) -> (a invob b)
*/
class UseInverseOp: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        QList<CppQuickFixOperation::Ptr> result;
79
        const CppRefactoringFile &file = state.currentFile();
80
81
82
83
84
85
86
87
88
89

        const QList<AST *> &path = state.path();
        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return result;
        if (! state.isCursorOn(binary->binary_op_token))
            return result;

        Kind invertToken;
90
        switch (file.tokenAt(binary->binary_op_token).kind()) {
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        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;
        }

        result.append(CppQuickFixOperation::Ptr(new Operation(state, index, binary, invertToken)));
        return result;
    }

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

        QString replacement;

    public:
        Operation(const CppQuickFixState &state, int priority, BinaryExpressionAST *binary, Kind invertToken)
            : CppQuickFixOperation(state, priority)
            , binary(binary)
        {
            Token tok;
            tok.f.kind = invertToken;
            replacement = QLatin1String(tok.spell());

            // check for enclosing nested expression
            if (priority - 1 >= 0)
                nested = state.path()[priority - 1]->asNestedExpression();

            // check for ! before parentheses
            if (nested && priority - 2 >= 0) {
                negation = state.path()[priority - 2]->asUnaryExpression();
142
                if (negation && ! state.currentFile().tokenAt(negation->unary_op_token).is(T_EXCLAIM))
143
144
145
146
147
148
149
150
151
                    negation = 0;
            }
        }

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

152
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
153
154
155
156
        {
            ChangeSet changes;
            if (negation) {
                // can't remove parentheses since that might break precedence
157
                changes.remove(currentFile->range(negation->unary_op_token));
158
            } else if (nested) {
159
                changes.insert(currentFile->startOf(nested), "!");
160
            } else {
161
162
                changes.insert(currentFile->startOf(binary), "!(");
                changes.insert(currentFile->endOf(binary), ")");
163
            }
164
            changes.replace(currentFile->range(binary->binary_op_token), replacement);
165
            currentFile->change(changes);
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        }
    };
};

/*
    Rewrite
    a op b

    As
    b flipop a
*/
class FlipBinaryOp: public CppQuickFixFactory
{
public:
    virtual QList<QuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        QList<QuickFixOperation::Ptr> result;
        const QList<AST *> &path = state.path();
184
        const CppRefactoringFile &file = state.currentFile();
185
186
187
188
189
190
191
192
193

        int index = path.size() - 1;
        BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
        if (! binary)
            return result;
        if (! state.isCursorOn(binary->binary_op_token))
            return result;

        Kind flipToken;
194
        switch (file.tokenAt(binary->binary_op_token).kind()) {
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        case T_LESS_EQUAL:
            flipToken = T_GREATER_EQUAL;
            break;
        case T_LESS:
            flipToken = T_GREATER;
            break;
        case T_GREATER:
            flipToken = T_LESS;
            break;
        case T_GREATER_EQUAL:
            flipToken = T_LESS_EQUAL;
            break;
        case T_EQUAL_EQUAL:
        case T_EXCLAIM_EQUAL:
        case T_AMPER_AMPER:
        case T_PIPE_PIPE:
            flipToken = T_EOF_SYMBOL;
            break;
        default:
            return result;
        }

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

        result.append(QuickFixOperation::Ptr(new Operation(state, index, binary, replacement)));
        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, BinaryExpressionAST *binary, QString replacement)
            : CppQuickFixOperation(state)
            , 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);
        }

248
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
249
250
251
        {
            ChangeSet changes;

252
            changes.flip(currentFile->range(binary->left_expression), currentFile->range(binary->right_expression));
253
            if (! replacement.isEmpty())
254
                changes.replace(currentFile->range(binary->binary_op_token), replacement);
255

256
            currentFile->change(changes);
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        }

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

/*
    Rewrite
    !a && !b

    As
    !(a || b)
*/
class RewriteLogicalAndOp: public CppQuickFixFactory
{
public:
    virtual QList<QuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        QList<QuickFixOperation::Ptr> result;
        BinaryExpressionAST *expression = 0;
        const QList<AST *> &path = state.path();
280
        const CppRefactoringFile &file = state.currentFile();
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297

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

        if (! expression)
            return result;

        if (! state.isCursorOn(expression->binary_op_token))
            return result;

        QSharedPointer<Operation> op(new Operation(state));

        if (expression->match(op->pattern, &matcher) &&
298
299
300
                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)) {
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
            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;

        Operation(const CppQuickFixState &state)
            : CppQuickFixOperation(state)
            , mk(new ASTPatternBuilder)
        {
            left = mk->UnaryExpression();
            right = mk->UnaryExpression();
            pattern = mk->BinaryExpression(left, right);
        }

327
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
328
329
        {
            ChangeSet changes;
330
331
332
333
334
            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);
335
336
337
            changes.insert(start, QLatin1String("!("));
            changes.insert(end, QLatin1String(")"));

338
            currentFile->change(changes);
339
            currentFile->indent(currentFile->range(pattern));
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        }
    };

private:
    ASTMatcher matcher;
};

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:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        QList<CppQuickFixOperation::Ptr> result;
        CoreDeclaratorAST *core_declarator = 0;
        const QList<AST *> &path = state.path();
382
        const CppRefactoringFile &file = state.currentFile();
383
384
385
386
387
388
389
390
391
392
393

        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;

394
                    const int cursorPosition = file.cursor().selectionStart();
395

396
397
                    const int startOfDeclSpecifier = file.startOf(declaration->decl_specifier_list->firstToken());
                    const int endOfDeclSpecifier = file.endOf(declaration->decl_specifier_list->lastToken() - 1);
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

                    if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier) {
                        // the AST node under cursor is a specifier.
                        return singleResult(new Operation(state, index, declaration));
                    }

                    if (core_declarator && state.isCursorOn(core_declarator)) {
                        // got a core-declarator under the text cursor.
                        return singleResult(new Operation(state, index, declaration));
                    }
                }

                break;
            }
        }

        return result;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, SimpleDeclarationAST *decl)
            : CppQuickFixOperation(state, priority)
            , declaration(decl)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split Declaration"));
        }

429
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
430
431
432
433
        {
            ChangeSet changes;

            SpecifierListAST *specifiers = declaration->decl_specifier_list;
434
435
436
            int declSpecifiersStart = currentFile->startOf(specifiers->firstToken());
            int declSpecifiersEnd = currentFile->endOf(specifiers->lastToken() - 1);
            int insertPos = currentFile->endOf(declaration->semicolon_token);
437
438
439
440
441
442
443
444
445

            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(" "));
446
                changes.move(currentFile->range(declarator), insertPos);
447
448
                changes.insert(insertPos, QLatin1String(";"));

449
450
                const int prevDeclEnd = currentFile->endOf(prevDeclarator);
                changes.remove(prevDeclEnd, currentFile->startOf(declarator));
451
452
453
454

                prevDeclarator = declarator;
            }

455
            currentFile->change(changes);
456
            currentFile->indent(currentFile->range(declaration));
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
    compound statement.
*/
class AddBracesToIfOp: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();

        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
        if (ifStatement && state.isCursorOn(ifStatement->if_token) && ifStatement->statement
            && ! ifStatement->statement->asCompoundStatement()) {
            return singleResult(new Operation(state, index, ifStatement->statement));
        }

        // 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
                && state.isCursorOn(ifStatement->statement)
                && ! ifStatement->statement->asCompoundStatement()) {
                return singleResult(new Operation(state, index, ifStatement->statement));
            }
        }

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

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, StatementAST *statement)
            : CppQuickFixOperation(state, priority)
            , _statement(statement)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Add Curly Braces"));
        }

512
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
513
514
515
        {
            ChangeSet changes;

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

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

522
            currentFile->change(changes);
523
            currentFile->indent(Range(start, end));
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
        }

    private:
        StatementAST *_statement;
    };
};

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

    With
    Type name = foo;
    if (name) {...}
*/
class MoveDeclarationOutOfIfOp: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();
        QSharedPointer<Operation> op(new Operation(state));

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

                    if (state.isCursorOn(op->core)) {
                        QList<CppQuickFixOperation::Ptr> result;
                        op->setPriority(index);
                        result.append(op);
                        return result;
                    }
                }
            }
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state)
            : CppQuickFixOperation(state)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

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

583
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
584
585
586
        {
            ChangeSet changes;

587
            changes.copy(currentFile->range(core), currentFile->startOf(condition));
588

589
590
            int insertPos = currentFile->startOf(pattern);
            changes.move(currentFile->range(condition), insertPos);
591
592
            changes.insert(insertPos, QLatin1String(";\n"));

593
            currentFile->change(changes);
594
            currentFile->indent(currentFile->range(pattern));
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
        }

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

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

    With
    Type name;
    while ((name = foo()) != 0) {...}
*/
class MoveDeclarationOutOfWhileOp: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();
        QSharedPointer<Operation> op(new Operation(state));

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

632
                    else if (! declarator->equal_token)
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
                        return noResult();

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

                    if (state.isCursorOn(op->core)) {
                        QList<CppQuickFixOperation::Ptr> result;
                        op->setPriority(index);
                        result.append(op);
                        return result;
                    }
                }
            }
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state)
            : CppQuickFixOperation(state)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Move Declaration out of Condition"));

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

665
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
666
667
668
        {
            ChangeSet changes;

669
670
            changes.insert(currentFile->startOf(condition), QLatin1String("("));
            changes.insert(currentFile->endOf(condition), QLatin1String(") != 0"));
671

672
673
674
675
            int insertPos = currentFile->startOf(pattern);
            const int conditionStart = currentFile->startOf(condition);
            changes.move(conditionStart, currentFile->startOf(core), insertPos);
            changes.copy(currentFile->range(core), insertPos);
676
677
            changes.insert(insertPos, QLatin1String(";\n"));

678
            currentFile->change(changes);
679
            currentFile->indent(currentFile->range(pattern));
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
        }

        ASTMatcher matcher;
        ASTPatternBuilder mk;
        CPPEditor *editor;
        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;
*/
class SplitIfStatementOp: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        IfStatementAST *pattern = 0;
        const QList<AST *> &path = state.path();

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

739
            Token binaryToken = state.currentFile().tokenAt(condition->binary_op_token);
740
741
742
743
744
745
746
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
773

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

            if (state.isCursorOn(condition->binary_op_token))
                return singleResult(new Operation(state, index, pattern, condition));
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority,
                  IfStatementAST *pattern, BinaryExpressionAST *condition)
            : CppQuickFixOperation(state, priority)
            , pattern(pattern)
            , condition(condition)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Split if Statement"));
        }

774
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
775
        {
776
            const Token binaryToken = currentFile->tokenAt(condition->binary_op_token);
777
778

            if (binaryToken.is(T_AMPER_AMPER))
779
                splitAndCondition(currentFile);
780
            else
781
                splitOrCondition(currentFile);
782
783
        }

784
        void splitAndCondition(CppRefactoringFile *currentFile)
785
786
787
        {
            ChangeSet changes;

788
            int startPos = currentFile->startOf(pattern);
789
            changes.insert(startPos, QLatin1String("if ("));
790
            changes.move(currentFile->range(condition->left_expression), startPos);
791
792
            changes.insert(startPos, QLatin1String(") {\n"));

793
794
795
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
            changes.insert(currentFile->endOf(pattern), QLatin1String("\n}"));
796

797
            currentFile->change(changes);
798
            currentFile->indent(currentFile->range(pattern));
799
800
        }

801
        void splitOrCondition(CppRefactoringFile *currentFile)
802
803
804
805
806
807
        {
            ChangeSet changes;

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

808
            int insertPos = currentFile->endOf(ifTrueStatement);
809
810
811
812
813
814
            if (compoundStatement)
                changes.insert(insertPos, QLatin1String(" "));
            else
                changes.insert(insertPos, QLatin1String("\n"));
            changes.insert(insertPos, QLatin1String("else if ("));

815
816
            const int rExprStart = currentFile->startOf(condition->right_expression);
            changes.move(rExprStart, currentFile->startOf(pattern->rparen_token), insertPos);
817
818
            changes.insert(insertPos, QLatin1String(")"));

819
820
            const int rParenEnd = currentFile->endOf(pattern->rparen_token);
            changes.copy(rParenEnd, currentFile->endOf(pattern->statement), insertPos);
821

822
823
            const int lExprEnd = currentFile->endOf(condition->left_expression);
            changes.remove(lExprEnd, currentFile->startOf(condition->right_expression));
824

825
            currentFile->change(changes);
826
            currentFile->indent(currentFile->range(pattern));
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
        }

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

/*
  Replace
    "abcd"
  With
    QLatin1String("abcd")
*/
class WrapStringLiteral: public CppQuickFixFactory
{
public:
    enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };

    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        ExpressionAST *literal = 0;
        Type type = TypeNone;
        const QList<AST *> &path = state.path();
851
        const CppRefactoringFile &file = state.currentFile();
852
853
854
855
856
857
858
859

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

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

        if (! literal) {
            literal = path.last()->asNumericLiteral();
860
            if (!literal || !file.tokenAt(literal->asNumericLiteral()->literal_token).is(T_CHAR_LITERAL))
861
862
863
864
865
866
867
868
869
870
                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
871
872
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
873
                            const QByteArray id(file.tokenAt(functionName->identifier_token).identifier->chars());
Roberto Raggi's avatar
Roberto Raggi committed
874
875
876
877
878
879

                            if (id == "QT_TRANSLATE_NOOP" || id == "tr" || id == "trUtf8"
                                    || (type == TypeString && (id == "QLatin1String" || id == "QLatin1Literal"))
                                    || (type == TypeChar && id == "QLatin1Char"))
                                return noResult(); // skip it
                        }
880
881
882
883
884
885
                    }
                }
            }
        }

        if (type == TypeString) {
886
            if (file.charAt(file.startOf(literal)) == QLatin1Char('@'))
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
                type = TypeObjCString;
        }
        return singleResult(new Operation(state,
                                          path.size() - 1, // very high priority
                                          type,
                                          literal));
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, Type type,
                  ExpressionAST *literal)
            : CppQuickFixOperation(state, priority)
            , type(type)
            , literal(literal)
        {
            if (type == TypeChar)
                setDescription(QApplication::translate("CppTools::QuickFix",
                                                       "Enclose in QLatin1Char(...)"));
            else
                setDescription(QApplication::translate("CppTools::QuickFix",
                                                       "Enclose in QLatin1String(...)"));
        }

913
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
914
915
916
        {
            ChangeSet changes;

917
            const int startPos = currentFile->startOf(literal);
918
919
920
921
922
923
924
925
            QLatin1String replacement = (type == TypeChar ? QLatin1String("QLatin1Char(")
                                                          : QLatin1String("QLatin1String("));

            if (type == TypeObjCString)
                changes.replace(startPos, startPos + 1, replacement);
            else
                changes.insert(startPos, replacement);

926
            changes.insert(currentFile->endOf(literal), ")");
927

928
            currentFile->change(changes);
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
        }

    private:
        Type type;
        ExpressionAST *literal;
    };
};

/*
  Replace
    "abcd"
  With
    tr("abcd") or
    QCoreApplication::translate("CONTEXT", "abcd") or
    QT_TRANSLATE_NOOP("GLOBAL", "abcd")
*/
class TranslateStringLiteral: public CppQuickFixFactory
{
public:
    enum TranslationOption { unknown, useTr, useQCoreApplicationTranslate, useMacro };

    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();
        // 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
968
969
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
970
                            const QByteArray id(state.currentFile().tokenAt(functionName->identifier_token).identifier->chars());
Roberto Raggi's avatar
Roberto Raggi committed
971
972
973
974
975
976
977

                            if (id == "tr" || id == "trUtf8"
                                    || id == "translate"
                                    || id == "QT_TRANSLATE_NOOP"
                                    || id == "QLatin1String" || id == "QLatin1Literal")
                                return noResult(); // skip it
                        }
978
979
980
981
982
983
                    }
                }
            }
        }

        QSharedPointer<Control> control = state.context().control();
984
        const Name *trName = control->identifier("tr");
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030

        // Check whether we are in a method:
        for (int i = path.size() - 1; i >= 0; --i)
        {
            if (FunctionDefinitionAST *definition = path.at(i)->asFunctionDefinition()) {
                Function *function = definition->symbol;
                ClassOrNamespace *b = state.context().lookupType(function);
                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
                            return singleResult(new Operation(state, path.size() - 1, literal, useTr, trContext));
                        }
                    }
                }
                // 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");
                return singleResult(new Operation(state, path.size() - 1, literal, useQCoreApplicationTranslate, trContext));
            }
        }

        // We need to use Q_TRANSLATE_NOOP
        return singleResult(new Operation(state, path.size() - 1, literal, useMacro, QLatin1String("GLOBAL")));
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, ExpressionAST *literal, TranslationOption option, const QString &context)
            : CppQuickFixOperation(state, priority)
            , m_literal(literal)
            , m_option(option)
            , m_context(context)
        {
Jarek Kobus's avatar
Jarek Kobus committed
1031
            setDescription(QApplication::translate("CppTools::QuickFix", "Mark as translatable"));
1032
1033
        }

1034
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1035
1036
1037
        {
            ChangeSet changes;

1038
            const int startPos = currentFile->startOf(m_literal);
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
            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);
1049
            changes.insert(currentFile->endOf(m_literal), QLatin1String(")"));
1050

1051
            currentFile->change(changes);
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
        }

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

class CStringToNSString: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
1066
1067
        const CppRefactoringFile &file = state.currentFile();

1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
        if (state.editor()->mimeType() != CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)
            return noResult();

        StringLiteralAST *stringLiteral = 0;
        CallAST *qlatin1Call = 0;
        const QList<AST *> &path = state.path();

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

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

        if (! stringLiteral)
            return noResult();

1083
        else if (file.charAt(file.startOf(stringLiteral)) == QLatin1Char('@'))
1084
1085
1086
1087
1088
            return noResult(); // it's already an objc string literal.

        else if (path.size() > 1) {
            if (CallAST *call = path.at(path.size() - 2)->asCall()) {
                if (call->base_expression) {
Roberto Raggi's avatar
Roberto Raggi committed
1089
1090
                    if (IdExpressionAST *idExpr = call->base_expression->asIdExpression()) {
                        if (SimpleNameAST *functionName = idExpr->name->asSimpleName()) {
1091
                            const QByteArray id(state.currentFile().tokenAt(functionName->identifier_token).identifier->chars());
1092

Roberto Raggi's avatar
Roberto Raggi committed
1093
1094
1095
                            if (id == "QLatin1String" || id == "QLatin1Literal")
                                qlatin1Call = call;
                        }
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
                    }
                }
            }
        }

        return singleResult(new Operation(state, path.size() - 1, stringLiteral, qlatin1Call));
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, StringLiteralAST *stringLiteral, CallAST *qlatin1Call)
            : CppQuickFixOperation(state, priority)
            , stringLiteral(stringLiteral)
            , qlatin1Call(qlatin1Call)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Convert to Objective-C String Literal"));
        }

1117
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1118
1119
1120
1121
        {
            ChangeSet changes;

            if (qlatin1Call) {
1122
1123
                changes.replace(currentFile->startOf(qlatin1Call), currentFile->startOf(stringLiteral), QLatin1String("@"));
                changes.remove(currentFile->endOf(stringLiteral), currentFile->endOf(qlatin1Call));
1124
            } else {
1125
                changes.insert(currentFile->startOf(stringLiteral), "@");
1126
1127
            }

1128
            currentFile->change(changes);
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
        }

    private:
        StringLiteralAST *stringLiteral;
        CallAST *qlatin1Call;
    };
};

/*
  Base class for converting numeric literals between decimal, octal and hex.
  Does the base check for the specific ones and parses the number.
  Test cases:
    0xFA0Bu;
    0X856A;
    298.3;
    199;
    074;
    199L;
    074L;
    -199;
    -017;
    0783; // invalid octal
    0; // border case, allow only hex<->decimal
*/
class ConvertNumericLiteral: public CppQuickFixFactory
{
public:
    virtual QList<QuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        QList<QuickFixOperation::Ptr> result;

        const QList<AST *> &path = state.path();
1161
        const CppRefactoringFile &file = state.currentFile();
1162
1163
1164
1165
1166
1167
1168
1169
1170

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

        NumericLiteralAST *literal = path.last()->asNumericLiteral();

        if (! literal)
            return result;

1171
        Token token = file.tokenAt(literal->asNumericLiteral()->literal_token);
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
        if (!token.is(T_NUMERIC_LITERAL))
            return result;
        const NumericLiteral *numeric = token.number;
        if (numeric->isDouble() || numeric->isFloat())
            return result;

        // remove trailing L or U and stuff
        const char * const spell = numeric->chars();
        int numberLength = numeric->size();
        while (numberLength > 0 && (spell[numberLength-1] < '0' || spell[numberLength-1] > 'F'))
            --numberLength;
        if (numberLength < 1)
            return result;

        // convert to number
        bool valid;
        ulong value = QString::fromUtf8(spell).left(numberLength).toULong(&valid, 0);
        if (!valid) // e.g. octal with digit > 7
            return result;

        const int priority = path.size() - 1; // very high priority
1193
        const int start = file.startOf(literal);
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
        const char * const str = numeric->chars();

        if (!numeric->isHex()) {
            /*
              Convert integer literal to hex representation.
              Replace
                32
                040
              With
                0x20

            */
            QString replacement;
            replacement.sprintf("0x%lX", value);
            QuickFixOperation::Ptr op(new ConvertNumeric(state, start, start + numberLength, replacement));
            op->setDescription(QApplication::translate("CppTools::QuickFix", "Convert to Hexadecimal"));
            op->setPriority(priority);
            result.append(op);
        }

        if (value != 0) {
            if (!(numberLength > 1 && str[0] == '0' && str[1] != 'x' && str[1] != 'X')) {
                /*
                  Convert integer literal to octal representation.
                  Replace
                    32
                    0x20
                  With
                    040
                */
                QString replacement;
                replacement.sprintf("0%lo", value);
                QuickFixOperation::Ptr op(new ConvertNumeric(state, start, start + numberLength, replacement));
                op->setDescription(QApplication::translate("CppTools::QuickFix", "Convert to Octal"));
                op->setPriority(priority);
                result.append(op);
            }
        }

        if (value != 0 || numeric->isHex()) {
            if (!(numberLength > 1 && str[0] != '0')) {
                /*
                  Convert integer literal to decimal representation.
                  Replace
                    0x20
                    040
                  With
                    32
                */
                QString replacement;
                replacement.sprintf("%lu", value);
                QuickFixOperation::Ptr op(new ConvertNumeric(state, start, start + numberLength, replacement));
                op->setDescription(QApplication::translate("CppTools::QuickFix", "Convert to Decimal"));
                op->setPriority(priority);
                result.append(op);
            }
        }

        return result;
    }

private:
    class ConvertNumeric: public CppQuickFixOperation
    {
    public:
        ConvertNumeric(const CppQuickFixState &state, int start, int end, const QString &replacement)
            : CppQuickFixOperation(state)
            , start(start)
            , end(end)
            , replacement(replacement)
        {}

1266
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1267
1268
1269
        {
            ChangeSet changes;
            changes.replace(start, end, replacement);
1270
            currentFile->change(changes);
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
        }

    protected:
        int start, end;
        QString replacement;
    };
};

/*
  Adds missing case statements for "switch (enumVariable)"
*/
class CompleteSwitchCaseStatement: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();

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

        // look for switch statement
        for (int depth = path.size() - 1; depth >= 0; --depth) {
            AST *ast = path.at(depth);
            SwitchStatementAST *switchStatement = ast->asSwitchStatement();
            if (switchStatement) {
                if (!state.isCursorOn(switchStatement->switch_token) || !switchStatement->statement)
                    return noResult();
                CompoundStatementAST *compoundStatement = switchStatement->statement->asCompoundStatement();
                if (!compoundStatement) // we ignore pathologic case "switch (t) case A: ;"
                    return noResult();
                // look if the condition's type is an enum
                if (Enum *e = conditionEnum(state, switchStatement)) {
                    // check the possible enum values
                    QStringList values;
                    Overview prettyPrint;
                    for (unsigned i = 0; i < e->memberCount(); ++i) {
                        if (Declaration *decl = e->memberAt(i)->asDeclaration()) {
                            values << prettyPrint(LookupContext::fullyQualifiedName(decl));
                        }
                    }
                    // Get the used values
                    Block *block = switchStatement->symbol;
                    CaseStatementCollector caseValues(state.document(), state.snapshot(),
                        state.document()->scopeAt(block->line(), block->column()));
                    QStringList usedValues = caseValues(switchStatement);
                    // save the values that would be added
                    foreach (const QString &usedValue, usedValues)
                        values.removeAll(usedValue);
                    if (values.isEmpty())
                        return noResult();
                    return singleResult(new Operation(state, depth, compoundStatement, values));
                }
                return noResult();
            }
        }

        return noResult();
    }

protected:
    Enum *conditionEnum(const CppQuickFixState &state, SwitchStatementAST *statement)
    {
        Block *block = statement->symbol;
        Scope *scope = state.document()->scopeAt(block->line(), block->column());
        TypeOfExpression typeOfExpression;
        typeOfExpression.init(state.document(), state.snapshot());
        const QList<LookupItem> results = typeOfExpression(statement->condition,
                                                           state.document(),
                                                           scope);
        foreach (LookupItem result, results) {
            FullySpecifiedType fst = result.type();
Roberto Raggi's avatar
Roberto Raggi committed
1343
1344
            if (! result.declaration())
                continue;
1345
1346
1347
1348
1349
1350
            if (Enum *e = result.declaration()->type()->asEnumType())
                return e;
            if (NamedType *namedType = fst->asNamedType()) {
                QList<LookupItem> candidates =
                        typeOfExpression.context().lookup(namedType->name(), scope);
                foreach (const LookupItem &r, candidates) {
Roberto Raggi's avatar
Roberto Raggi committed
1351
1352
1353
1354
                    if (Symbol *candidate = r.declaration()) {
                        if (Enum *e = candidate->asEnum()) {
                            return e;
                        }
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
                    }
                }
            }
        }
        return 0;
    }

    class CaseStatementCollector : public ASTVisitor
    {
    public:
        CaseStatementCollector(Document::Ptr document, const Snapshot &snapshot,
                               Scope *scope)
            : ASTVisitor(document->translationUnit()),
            document(document),
            scope(scope)
        {
            typeOfExpression.init(document, snapshot);
        }

        QStringList operator ()(AST *ast)
        {
            values.clear();
            foundCaseStatementLevel = false;
            accept(ast);
            return values;
        }

        bool preVisit(AST *ast) {
            if (CaseStatementAST *cs = ast->asCaseStatement()) {
                foundCaseStatementLevel = true;
Roberto Raggi's avatar
Roberto Raggi committed
1385
1386
1387
1388
1389
1390
1391
1392
                if (ExpressionAST *expression = cs->expression->asIdExpression()) {
                    QList<LookupItem> candidates = typeOfExpression(expression,
                                                                    document,
                                                                    scope);
                    if (!candidates .isEmpty() && candidates.first().declaration()) {
                        Symbol *decl = candidates.first().declaration();
                        values << prettyPrint(LookupContext::fullyQualifiedName(decl));
                    }
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
                }
                return true;
            } else if (foundCaseStatementLevel) {
                return false;
            }
            return true;
        }

        Overview prettyPrint;
        bool foundCaseStatementLevel;
        QStringList values;
        TypeOfExpression typeOfExpression;
        Document::Ptr document;
        Scope *scope;
    };

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, CompoundStatementAST *compoundStatement, const QStringList &values)
            : CppQuickFixOperation(state, priority)
            , compoundStatement(compoundStatement)
            , values(values)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Complete Switch Statement"));
        }


1423
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1424
1425
        {
            ChangeSet changes;
1426
            int start = currentFile->endOf(compoundStatement->lbrace_token);
1427
1428
1429
            changes.insert(start, QLatin1String("\ncase ")
                           + values.join(QLatin1String(":\nbreak;\ncase "))
                           + QLatin1String(":\nbreak;"));
1430
            currentFile->change(changes);
1431
            currentFile->indent(currentFile->range(compoundStatement));
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
        }

        CompoundStatementAST *compoundStatement;
        QStringList values;
    };
};


class FixForwardDeclarationOp: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();

        for (int index = path.size() - 1; index != -1; --index) {
            AST *ast = path.at(index);
            if (NamedTypeSpecifierAST *namedTy = ast->asNamedTypeSpecifier()) {
                if (Symbol *fwdClass = checkName(state, namedTy->name))
                    return singleResult(new Operation(state, index, fwdClass));
            } else if (ElaboratedTypeSpecifierAST *eTy = ast->asElaboratedTypeSpecifier()) {
                if (Symbol *fwdClass = checkName(state, eTy->name))
                    return singleResult(new Operation(state, index, fwdClass));
            }
        }

        return noResult();
    }

protected:
    static Symbol *checkName(const CppQuickFixState &state, NameAST *ast)
    {
        if (ast && state.isCursorOn(ast)) {
            if (const Name *name = ast->name) {
                unsigned line, column;
                state.document()->translationUnit()->getTokenStartPosition(ast->firstToken(), &line, &column);

                Symbol *fwdClass = 0;

                foreach (const LookupItem &r, state.context().lookup(name, state.document()->scopeAt(line, column))) {
                    if (! r.declaration())
                        continue;
                    else if (ForwardClassDeclaration *fwd = r.declaration()->asForwardClassDeclaration())
                        fwdClass = fwd;
                    else if (r.declaration()->isClass())
                        return 0; // nothing to do.
                }

                return fwdClass;
            }
        }

        return 0;
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, Symbol *fwdClass)
            : CppQuickFixOperation(state, priority)
            , fwdClass(fwdClass)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "#include header file"));
        }

1499
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
        {
            Q_ASSERT(fwdClass != 0);

            if (Class *k = state().snapshot().findMatchingClassDeclaration(fwdClass)) {
                const QString headerFile = QString::fromUtf8(k->fileName(), k->fileNameLength());

                // collect the fwd headers
                Snapshot fwdHeaders;
                fwdHeaders.insert(state().snapshot().document(headerFile));
                foreach (Document::Ptr doc, state().snapshot()) {
                    QFileInfo headerFileInfo(doc->fileName());
                    if (doc->globalSymbolCount() == 0 && doc->includes().size() == 1)
                        fwdHeaders.insert(doc);
                    else if (headerFileInfo.suffix().isEmpty())
                        fwdHeaders.insert(doc);
                }


                DependencyTable dep;
                dep.build(fwdHeaders);
                QStringList candidates = dep.dependencyTable().value(headerFile);

                const QString className = QString::fromUtf8(k->identifier()->chars());

                QString best;
                foreach (const QString &c, candidates) {
                    QFileInfo headerFileInfo(c);
                    if (headerFileInfo.fileName() == className) {
                        best = c;
                        break;
                    } else if (headerFileInfo.fileName().at(0).isUpper()) {
                        best = c;
                        // and continue
                    } else if (! best.isEmpty()) {
                        if (c.count(QLatin1Char('/')) < best.count(QLatin1Char('/')))
                            best = c;
                    }
                }

                if (best.isEmpty())
                    best = headerFile;

1542
                int pos = currentFile->startOf(1);
1543

1544
                unsigned currentLine = currentFile->cursor().blockNumber() + 1;
1545
1546
1547
1548
1549
1550
1551
                unsigned bestLine = 0;
                foreach (const Document::Include &incl, state().document()->includes()) {
                    if (incl.line() < currentLine)
                        bestLine = incl.line();
                }

                if (bestLine)
1552
                    pos = currentFile->document()->findBlockByNumber(bestLine).position();
1553
1554
1555

                Utils::ChangeSet changes;
                changes.insert(pos, QString("#include <%1>\n").arg(QFileInfo(best).fileName()));
1556
                currentFile->change(changes);
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
            }
        }

    private:
        Symbol *fwdClass;
    };
};

class AddLocalDeclarationOp: public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();
1571
        const CppRefactoringFile &file = state.currentFile();
1572
1573
1574

        for (int index = path.size() - 1; index != -1; --index) {
            if (BinaryExpressionAST *binary = path.at(index)->asBinaryExpression()) {
1575
                if (binary->left_expression && binary->right_expression && file.tokenAt(binary->binary_op_token).is(T_EQUAL)) {
Roberto Raggi's avatar
Roberto Raggi committed
1576
1577
1578
                    IdExpressionAST *idExpr = binary->left_expression->asIdExpression();
                    if (state.isCursorOn(binary->left_expression) && idExpr && idExpr->name->asSimpleName() != 0) {
                        SimpleNameAST *nameAST = idExpr->name->asSimpleName();
1579
                        const QList<LookupItem> results = state.context().lookup(nameAST->name, file.scopeAt(nameAST->firstToken()));
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
                        Declaration *decl = 0;
                        foreach (const LookupItem &r, results) {
                            if (! r.declaration())
                                continue;
                            else if (Declaration *d = r.declaration()->asDeclaration()) {
                                if (! d->type()->isFunctionType()) {
                                    decl = d;
                                    break;
                                }
                            }
                        }

                        if (! decl) {
                            return singleResult(new Operation(state, index, binary));
                        }
                    }
                }
            }
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, BinaryExpressionAST *binaryAST)
            : CppQuickFixOperation(state, priority)
            , binaryAST(binaryAST)
        {
            setDescription(QApplication::translate("CppTools::QuickFix", "Add local declaration"));
        }

1614
        virtual void performChanges(CppRefactoringFile *currentFile, CppRefactoringChanges *)
1615
1616
1617
        {
            TypeOfExpression typeOfExpression;
            typeOfExpression.init(state().document(), state().snapshot(), state().context().bindings());
1618
1619
            const QList<LookupItem> result = typeOfExpression(currentFile->textOf(binaryAST->right_expression),
                                                              currentFile->scopeAt(binaryAST->firstToken()),
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
                                                              TypeOfExpression::Preprocess);

            if (! result.isEmpty()) {

                SubstitutionEnvironment env;
                env.setContext(state().context());
                env.switchScope(result.first().scope());
                UseQualifiedNames q;
                env.enter(&q);

                Control *control = state().context().control().data();
                FullySpecifiedType tn = rewriteType(result.first().type(), &env, control);

                Overview oo;
                QString ty = oo(tn);
                if (! ty.isEmpty()) {
                    const QChar ch = ty.at(ty.size() - 1);

                    if (ch.isLetterOrNumber() || ch == QLatin1Char(' ') || ch == QLatin1Char('>'))
                        ty += QLatin1Char(' ');

                    Utils::ChangeSet changes;
1642
                    changes.insert(currentFile->startOf(binaryAST), ty);
1643
                    currentFile->change(changes);
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
                }
            }
        }

    private:
        BinaryExpressionAST *binaryAST;
    };
};

/*
 * Turns "an_example_symbol" into "anExampleSymbol" and
 * "AN_EXAMPLE_SYMBOL" into "AnExampleSymbol".
 */
class ToCamelCaseConverter : public CppQuickFixFactory
{
public:
    virtual QList<CppQuickFixOperation::Ptr> match(const CppQuickFixState &state)
    {
        const QList<AST *> &path = state.path();

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

        AST * const ast = path.last();
        const Name *name = 0;
        if (const NameAST * const nameAst = ast->asName()) {
            if (nameAst->name && nameAst->name->asNameId())
                name = nameAst->name;
        } else if (const NamespaceAST * const namespaceAst = ast->asNamespace()) {
            name = namespaceAst->symbol->name();
        }

        if (!name)
            return noResult();

        QString newName = QString::fromUtf8(name->identifier()->chars());
        if (newName.length() < 3)
            return noResult();
        for (int i = 1; i < newName.length() - 1; ++i) {
            if (Operation::isConvertibleUnderscore(newName, i))
                return singleResult(new Operation(state, path.size() - 1, newName));
        }

        return noResult();
    }

private:
    class Operation: public CppQuickFixOperation
    {
    public:
        Operation(const CppQuickFixState &state, int priority, const QString &newName)
            : CppQuickFixOperation(state, priority)
            , m_name(newName)
        {
            setDescription(QApplication::translate("CppTools::QuickFix",
                                                   "Convert to Camel Case ..."));
        }

1702
        virtual void performChanges(CppRefactoringFile *, CppRefactoringChanges *)
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
        {
            for (int i = 1; i < m_name.length(); ++i) {
                QCharRef c = m_name[i];
                if (c.isUpper()) {
                    c = c.toLower();
                } else if (i < m_name.length() - 1
                           && isConvertibleUnderscore(m_name, i)) {
                    m_name.remove(i, 1);
                    m_name[i] = m_name.at(i).toUpper();
                }
            }
            static_cast<CppEditor::Internal::CPPEditor*>(state().editor())->renameUsagesNow(m_name);
        }

        static bool isConvertibleUnderscore(const QString &name, int pos)
        {
            return name.at(pos) == QLatin1Char('_') && name.at(pos+1).isLetter()
                    && !(pos == 1 && name.at(0) == QLatin1Char('m'));
        }

    private:
        QString m_name;
    };
};

} // end of anonymous namespace

void CppQuickFixCollector::registerQuickFixes(ExtensionSystem::IPlugin *plugIn)
{
    plugIn->addAutoReleasedObject(new UseInverseOp);
    plugIn->addAutoReleasedObject(new FlipBinaryOp);
    plugIn->addAutoReleasedObject(new RewriteLogicalAndOp);
    plugIn->addAutoReleasedObject(new SplitSimpleDeclarationOp);
    plugIn->addAutoReleasedObject(new AddBracesToIfOp);
    plugIn->addAutoReleasedObject(new MoveDeclarationOutOfIfOp);
    plugIn->addAutoReleasedObject(new MoveDeclarationOutOfWhileOp);
    plugIn->addAutoReleasedObject(new SplitIfStatementOp);
    plugIn->addAutoReleasedObject(new WrapStringLiteral);
    plugIn->addAutoReleasedObject(new TranslateStringLiteral);
    plugIn->addAutoReleasedObject(new CStringToNSString);
    plugIn->addAutoReleasedObject(new ConvertNumericLiteral);
    plugIn->addAutoReleasedObject(new CompleteSwitchCaseStatement);
    plugIn->addAutoReleasedObject(new FixForwardDeclarationOp);
    plugIn->addAutoReleasedObject(new AddLocalDeclarationOp);
    plugIn->addAutoReleasedObject(new ToCamelCaseConverter);
    plugIn->addAutoReleasedObject(new Internal::DeclFromDef);
}