cppquickfix.cpp 25.3 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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 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 "cppquickfix.h"
#include "cppeditor.h"
32
33
34

#include <cplusplus/CppDocument.h>

35
#include <TranslationUnit.h>
36
37
#include <ASTVisitor.h>
#include <AST.h>
38
39
#include <ASTPatternBuilder.h>
#include <ASTMatcher.h>
40
41
42
43
44
45
46
47
#include <Token.h>

#include <cpptools/cppmodelmanagerinterface.h>
#include <QtDebug>

using namespace CppEditor::Internal;
using namespace CPlusPlus;

48
49
namespace {

50
51
52
53
54
55
56
57
58
class ASTPath: public ASTVisitor
{
    Document::Ptr _doc;
    unsigned _line;
    unsigned _column;
    QList<AST *> _nodes;

public:
    ASTPath(Document::Ptr doc)
Roberto Raggi's avatar
Roberto Raggi committed
59
60
61
        : ASTVisitor(doc->translationUnit()),
          _doc(doc), _line(0), _column(0)
    {}
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

    QList<AST *> operator()(const QTextCursor &cursor)
    {
        _nodes.clear();
        _line = cursor.blockNumber() + 1;
        _column = cursor.columnNumber() + 1;
        accept(_doc->translationUnit()->ast());
        return _nodes;
    }

protected:
    virtual bool preVisit(AST *ast)
    {
        unsigned firstToken = ast->firstToken();
        unsigned lastToken = ast->lastToken();

        if (firstToken > 0 && lastToken > firstToken) {
            unsigned startLine, startColumn;
            getTokenStartPosition(firstToken, &startLine, &startColumn);

            if (_line > startLine || (_line == startLine && _column >= startColumn)) {

                unsigned endLine, endColumn;
                getTokenEndPosition(lastToken - 1, &endLine, &endColumn);

                if (_line < endLine || (_line == endLine && _column < endColumn)) {
                    _nodes.append(ast);
                    return true;
                }
            }
        }

        return false;
    }
};

98
99
100
class RewriteLogicalAndOp: public QuickFixOperation
{
public:
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
101
    RewriteLogicalAndOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
Roberto Raggi's avatar
Roberto Raggi committed
102
        : QuickFixOperation(doc, snapshot, editor),
103
104
105
106
107
108
109
110
           left(0), right(0), pattern(0)
    {}

    virtual QString description() const
    {
        return QLatin1String("Rewrite condition using ||"); // ### tr?
    }

111
    virtual int match(const QList<AST *> &path)
112
    {
113
114
115
116
117
118
119
120
121
122
123
124
        BinaryExpressionAST *expression = 0;

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

        if (! expression)
            return -1;

125
        if (! isCursorOn(expression->binary_op_token))
126
127
            return -1;

128
129
130
131
132
133
134
135
        left = mk.UnaryExpression();
        right = mk.UnaryExpression();
        pattern = mk.BinaryExpression(left, right);

        if (expression->match(pattern, &matcher) &&
                tokenAt(pattern->binary_op_token).is(T_AMPER_AMPER) &&
                tokenAt(left->unary_op_token).is(T_EXCLAIM) &&
                tokenAt(right->unary_op_token).is(T_EXCLAIM)) {
136
            return index;
137
138
        }

139
        return -1;
140
141
    }

Roberto Raggi's avatar
Roberto Raggi committed
142
    virtual void createChangeSet()
143
    {
Roberto Raggi's avatar
Roberto Raggi committed
144
        setTopLevelNode(pattern);
145
146
147
148
        replace(pattern->binary_op_token, QLatin1String("||"));
        replace(left->unary_op_token, QLatin1String("!("));
        replace(right->unary_op_token, QLatin1String(""));
        insert(endOf(pattern), QLatin1String(")"));
149
150
151
152
153
154
155
156
157
158
    }

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

159
160
161
162
class SplitSimpleDeclarationOp: public QuickFixOperation
{
public:
    SplitSimpleDeclarationOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
163
        : QuickFixOperation(doc, snapshot, editor), declaration(0)
164
165
166
167
168
169
170
171
172
    {}

    virtual QString description() const
    {
        return QLatin1String("Split declaration"); // ### tr?
    }

    bool checkDeclaration(SimpleDeclarationAST *declaration) const
    {
173
174
175
        if (! declaration->semicolon_token)
            return false;

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        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;
    }

198
    virtual int match(const QList<AST *> &path)
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    {
        CoreDeclaratorAST *core_declarator = 0;

        int index = path.size() - 1;
        for (; index != -1; --index) {
            AST *node = path.at(index);

            if (CoreDeclaratorAST *coreDecl = node->asCoreDeclarator())
                core_declarator = coreDecl;

            else if (SimpleDeclarationAST *simpleDecl = node->asSimpleDeclaration()) {
                if (checkDeclaration(simpleDecl)) {
                    declaration = simpleDecl;

213
                    const int cursorPosition = selectionStart();
214
215
216
217
218
219
220

                    const int startOfDeclSpecifier = startOf(declaration->decl_specifier_list->firstToken());
                    const int endOfDeclSpecifier = endOf(declaration->decl_specifier_list->lastToken() - 1);

                    if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier)
                        return index; // the AST node under cursor is a specifier.

221
                    if (core_declarator && isCursorOn(core_declarator))
222
                        return index; // got a core-declarator under the text cursor.
223
224
225
226
227
228
229
230
231
                }

                break;
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
232
    virtual void createChangeSet()
233
    {
Roberto Raggi's avatar
Roberto Raggi committed
234
        setTopLevelNode(declaration);
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
        SpecifierListAST *specifiers = declaration->decl_specifier_list;
        const QString declSpecifiers = textOf(startOf(specifiers->firstToken()), endOf(specifiers->lastToken() - 1));

        DeclaratorAST *declarator = declaration->declarator_list->value;
        replace(endOf(declarator), startOf(declaration->semicolon_token), QString());

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

            text += QLatin1Char('\n');
            text += declSpecifiers;
            text += QLatin1Char(' ');
            text += textOf(declarator);
            text += QLatin1String(";");
        }

        insert(endOf(declaration->semicolon_token), text);
    }

private:
    SimpleDeclarationAST *declaration;
};

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
    Add curly braces to a if statement that doesn't already contain a
    compound statement.
*/
class AddBracesToIfOp: public QuickFixOperation
{
public:
    AddBracesToIfOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
        : QuickFixOperation(doc, snapshot, editor),
           _statement(0)
    {}

    virtual QString description() const
    {
        return QLatin1String("Add curly braces"); // ### tr?
    }

276
    virtual int match(const QList<AST *> &path)
277
278
279
280
    {
        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
281
        if (ifStatement && isCursorOn(ifStatement->if_token)
282
283
284
285
286
287
288
289
290
            && ! ifStatement->statement->asCompoundStatement()) {
            _statement = ifStatement->statement;
            return index;
        }

        // or if we're on the statement contained in the if
        // ### This may not be such a good idea, consider nested ifs...
        for (; index != -1; --index) {
            IfStatementAST *ifStatement = path.at(index)->asIfStatement();
291
            if (ifStatement && isCursorOn(ifStatement->statement)
292
293
294
295
296
297
298
299
300
301
302
303
                && ! ifStatement->statement->asCompoundStatement()) {
                _statement = ifStatement->statement;
                return index;
            }
        }

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

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
304
    virtual void createChangeSet()
305
    {
Roberto Raggi's avatar
Roberto Raggi committed
306
        setTopLevelNode(_statement);
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        insert(endOf(_statement->firstToken() - 1), QLatin1String(" {"));
        insert(endOf(_statement->lastToken() - 1), "\n}");
    }

private:
    StatementAST *_statement;
};

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

    With
    Type name = foo;
    if (name) {...}
*/
323
class MoveDeclarationOutOfIfOp: public QuickFixOperation
324
325
{
public:
326
    MoveDeclarationOutOfIfOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
Roberto Raggi's avatar
Roberto Raggi committed
327
        : QuickFixOperation(doc, snapshot, editor),
328
329
330
331
332
           condition(0), pattern(0), core(0)
    {}

    virtual QString description() const
    {
333
        return QLatin1String("Move declaration out of condition"); // ### tr?
334
335
    }

336
    virtual int match(const QList<AST *> &path)
337
338
339
340
341
342
343
344
345
346
347
348
349
    {
        condition = mk.Condition();
        pattern = mk.IfStatement(condition);

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

350
                    if (isCursorOn(core))
351
352
353
354
355
356
357
358
                        return index;
                }
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
359
    virtual void createChangeSet()
360
    {
Roberto Raggi's avatar
Roberto Raggi committed
361
        setTopLevelNode(pattern);
362
363
        const QString name = textOf(core);
        QString declaration = textOf(condition);
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
        declaration += QLatin1String(";\n");

        insert(startOf(pattern), declaration);
        insert(endOf(pattern->lparen_token), name);
        replace(condition, name);
    }

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

380
381
382
383
384
385
386
387
388
389
390
391
/*
    Replace
    while (Type name = foo()) {...}

    With
    Type name;
    while ((name = foo()) != 0) {...}
*/
class MoveDeclarationOutOfWhileOp: public QuickFixOperation
{
public:
    MoveDeclarationOutOfWhileOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
Roberto Raggi's avatar
Roberto Raggi committed
392
        : QuickFixOperation(doc, snapshot, editor),
393
394
395
396
397
398
399
400
           condition(0), pattern(0), core(0)
    {}

    virtual QString description() const
    {
        return QLatin1String("Move declaration out of condition"); // ### tr?
    }

401
    virtual int match(const QList<AST *> &path)
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
    {
        condition = mk.Condition();
        pattern = mk.WhileStatement(condition);

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

                    if (! core)
                        return -1;

                    else if (! declarator->equals_token)
                        return -1;

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

422
                    if (isCursorOn(core))
423
424
425
426
427
428
429
430
                        return index;
                }
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
431
    virtual void createChangeSet()
432
    {
Roberto Raggi's avatar
Roberto Raggi committed
433
        setTopLevelNode(pattern);
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
        const QString name = textOf(core);
        const QString initializer = textOf(condition->declarator->initializer);
        QString declaration = textOf(startOf(condition), endOf(condition->declarator->equals_token - 1));
        declaration += QLatin1String(";\n");

        QString newCondition;
        newCondition += QLatin1String("(");
        newCondition += name;
        newCondition += QLatin1String(" = ");
        newCondition += initializer;
        newCondition += QLatin1String(") != 0");
        
        insert(startOf(pattern), declaration);
        insert(endOf(pattern->lparen_token), name);
        replace(condition, newCondition);
    }

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

Roberto Raggi's avatar
Roberto Raggi committed
460
461
462
463
464
465
466
467
468
469
/*
  Replace
     if (something && something_else) {
     }

  with
     if (something) {
        if (something_else) {
        }
     }
Roberto Raggi's avatar
Roberto Raggi committed
470
471
472
473
474
475
476
477
478
479

  and
    if (something || something_else)
      x;

  with
    if (something)
      x;
    else if (something_else)
      x;
Roberto Raggi's avatar
Roberto Raggi committed
480
481
482
483
484
*/
class SplitIfStatementOp: public QuickFixOperation
{
public:
    SplitIfStatementOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
485
486
        : QuickFixOperation(doc, snapshot, editor),
          condition(0), pattern(0)
Roberto Raggi's avatar
Roberto Raggi committed
487
488
489
490
491
492
493
    {}

    virtual QString description() const
    {
        return QLatin1String("Split if statement"); // ### tr?
    }

494
    virtual int match(const QList<AST *> &path)
Roberto Raggi's avatar
Roberto Raggi committed
495
    {
496
        pattern = 0;
Roberto Raggi's avatar
Roberto Raggi committed
497

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
        int index = path.size() - 1;
        for (; index != -1; --index) {
            AST *node = path.at(index);
            if (IfStatementAST *stmt = node->asIfStatement()) {
                pattern = stmt;
                break;
            }
        }

        if (! pattern)
            return -1;

        for (++index; index < path.size(); ++index) {
            AST *node = path.at(index);
            condition = node->asBinaryExpression();
            if (! condition)
                return -1;

            Token binaryToken = tokenAt(condition->binary_op_token);
            if (binaryToken.is(T_AMPER_AMPER) || binaryToken.is(T_PIPE_PIPE)) {
518
                if (isCursorOn(condition->binary_op_token))
519
520
521
522
523
524
525
                    return index;
            } else {
                return -1;
            }
        }

        return -1;
Roberto Raggi's avatar
Roberto Raggi committed
526
527
    }

Roberto Raggi's avatar
Roberto Raggi committed
528
    virtual void createChangeSet()
Roberto Raggi's avatar
Roberto Raggi committed
529
    {
530
        Token binaryToken = tokenAt(condition->binary_op_token);
Roberto Raggi's avatar
Roberto Raggi committed
531

532
        if (binaryToken.is(T_AMPER_AMPER))
Roberto Raggi's avatar
Roberto Raggi committed
533
534
535
536
537
538
539
            splitAndCondition();
        else
            splitOrCondition();
    }

    void splitAndCondition()
    {
Roberto Raggi's avatar
Roberto Raggi committed
540
        setTopLevelNode(pattern);
Roberto Raggi's avatar
Roberto Raggi committed
541
542
        StatementAST *ifTrueStatement = pattern->statement;

Roberto Raggi's avatar
Roberto Raggi committed
543
        // take the right-expression from the condition.
544
545
546
547
        QTextCursor rightCursor = textCursor();
        rightCursor.setPosition(startOf(condition->right_expression));
        rightCursor.setPosition(endOf(pattern->rparen_token - 1), QTextCursor::KeepAnchor);
        const QString rightCondition = rightCursor.selectedText();
Roberto Raggi's avatar
Roberto Raggi committed
548
549
550
551
        replace(endOf(condition->left_expression), startOf(pattern->rparen_token), QString());

        // create the nested if statement
        QString nestedIfStatement;
552
        nestedIfStatement += QLatin1String(" {\nif ("); // open new compound statement for outer
Roberto Raggi's avatar
Roberto Raggi committed
553
        nestedIfStatement += rightCondition;
554
        nestedIfStatement += QLatin1String(")");
Roberto Raggi's avatar
Roberto Raggi committed
555

556
557
        insert(endOf(pattern->rparen_token), nestedIfStatement);
        insert(endOf(ifTrueStatement), "\n}"); // finish the compound statement
Roberto Raggi's avatar
Roberto Raggi committed
558
559
    }

Roberto Raggi's avatar
Roberto Raggi committed
560
561
    void splitOrCondition()
    {
Roberto Raggi's avatar
Roberto Raggi committed
562
        setTopLevelNode(pattern);
Roberto Raggi's avatar
Roberto Raggi committed
563
564
565
566
        StatementAST *ifTrueStatement = pattern->statement;
        CompoundStatementAST *compoundStatement = ifTrueStatement->asCompoundStatement();

        // take the right-expression from the condition.
567
568
569
570
        QTextCursor rightCursor = textCursor();
        rightCursor.setPosition(startOf(condition->right_expression));
        rightCursor.setPosition(endOf(pattern->rparen_token - 1), QTextCursor::KeepAnchor);
        const QString rightCondition = rightCursor.selectedText();
Roberto Raggi's avatar
Roberto Raggi committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
        replace(endOf(condition->left_expression), startOf(pattern->rparen_token), QString());

        // copy the if-body
        QTextCursor bodyCursor = textCursor();
        bodyCursor.setPosition(endOf(pattern->rparen_token));
        bodyCursor.setPosition(endOf(pattern->statement), QTextCursor::KeepAnchor);
        const QString body = bodyCursor.selectedText();

        QString elseIfStatement;
        if (compoundStatement)
            elseIfStatement += QLatin1String(" ");
        else
            elseIfStatement += QLatin1String("\n");

        elseIfStatement += QLatin1String("else if (");
        elseIfStatement += rightCondition;
        elseIfStatement += QLatin1String(")");
        elseIfStatement += body;

        insert(endOf(pattern), elseIfStatement);
    }

Roberto Raggi's avatar
Roberto Raggi committed
593
594
595
596
private:
    BinaryExpressionAST *condition;
    IfStatementAST *pattern;
};
597

598
599
600
} // end of anonymous namespace


601
QuickFixOperation::QuickFixOperation(CPlusPlus::Document::Ptr doc,
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
602
603
                                     const CPlusPlus::Snapshot &snapshot,
                                     CPPEditor *editor)
Roberto Raggi's avatar
Roberto Raggi committed
604
605
    : _doc(doc), _snapshot(snapshot),
      _editor(editor), _topLevelNode(0)
606
607
608
609
610
{ }

QuickFixOperation::~QuickFixOperation()
{ }

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
611
612
613
CPPEditor *QuickFixOperation::editor() const
{ return _editor; }

Roberto Raggi's avatar
Roberto Raggi committed
614
615
616
617
618
619
CPlusPlus::AST *QuickFixOperation::topLevelNode() const
{ return _topLevelNode; }

void QuickFixOperation::setTopLevelNode(CPlusPlus::AST *topLevelNode)
{ _topLevelNode = topLevelNode; }

Roberto Raggi's avatar
Roberto Raggi committed
620
621
622
const Utils::ChangeSet &QuickFixOperation::changeSet() const
{ return _changeSet; }

623
624
625
QTextCursor QuickFixOperation::textCursor() const
{ return _textCursor; }

626
627
628
void QuickFixOperation::setTextCursor(const QTextCursor &cursor)
{ _textCursor = cursor; }

629
630
631
632
633
634
int QuickFixOperation::selectionStart() const
{ return _textCursor.selectionStart(); }

int QuickFixOperation::selectionEnd() const
{ return _textCursor.selectionEnd(); }

635
636
637
const CPlusPlus::Token &QuickFixOperation::tokenAt(unsigned index) const
{ return _doc->translationUnit()->tokenAt(index); }

638
int QuickFixOperation::startOf(unsigned index) const
639
{
640
641
642
643
    unsigned line, column;
    _doc->translationUnit()->getPosition(tokenAt(index).begin(), &line, &column);
    return _textCursor.document()->findBlockByNumber(line - 1).position() + column - 1;
}
644

645
646
647
648
649
650
int QuickFixOperation::startOf(const CPlusPlus::AST *ast) const
{
    return startOf(ast->firstToken());
}

int QuickFixOperation::endOf(unsigned index) const
651
652
653
654
{
    unsigned line, column;
    _doc->translationUnit()->getPosition(tokenAt(index).end(), &line, &column);
    return _textCursor.document()->findBlockByNumber(line - 1).position() + column - 1;
655
656
}

657
658
659
660
661
int QuickFixOperation::endOf(const CPlusPlus::AST *ast) const
{
    return endOf(ast->lastToken() - 1);
}

662
bool QuickFixOperation::isCursorOn(unsigned tokenIndex) const
663
664
665
666
667
668
669
670
671
672
673
674
675
{
    QTextCursor tc = textCursor();
    int cursorBegin = tc.selectionStart();

    int start = startOf(tokenIndex);
    int end = endOf(tokenIndex);

    if (cursorBegin >= start && cursorBegin <= end)
        return true;

    return false;
}

676
bool QuickFixOperation::isCursorOn(const CPlusPlus::AST *ast) const
677
678
679
680
681
682
683
684
685
686
687
688
689
{
    QTextCursor tc = textCursor();
    int cursorBegin = tc.selectionStart();

    int start = startOf(ast);
    int end = endOf(ast);

    if (cursorBegin >= start && cursorBegin <= end)
        return true;

    return false;
}

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
690
691
692
693
694
695
696
697
698
699
QuickFixOperation::Range QuickFixOperation::createRange(AST *ast) const
{    
    QTextCursor tc = _textCursor;
    Range r(tc);
    r.begin.setPosition(startOf(ast));
    r.end.setPosition(endOf(ast));
    return r;
}

void QuickFixOperation::reindent(const Range &range)
700
{
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
701
702
703
    QTextCursor tc = range.begin;
    tc.setPosition(range.end.position(), QTextCursor::KeepAnchor);
    _editor->indentInsertedText(tc);
704
705
}

706
707
708
void QuickFixOperation::move(int start, int end, int to)
{
    if (end > start)
709
        _changeSet.move(start, end-start, to);
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
}

void QuickFixOperation::move(unsigned tokenIndex, int to)
{
    move(startOf(tokenIndex), endOf(tokenIndex), to);
}

void QuickFixOperation::move(const CPlusPlus::AST *ast, int to)
{
    move(startOf(ast), endOf(ast), to);
}

void QuickFixOperation::replace(int start, int end, const QString &replacement)
{
    if (end >= start)
725
        _changeSet.replace(start, end-start, replacement);
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
}

void QuickFixOperation::replace(unsigned tokenIndex, const QString &replacement)
{
    replace(startOf(tokenIndex), endOf(tokenIndex), replacement);
}

void QuickFixOperation::replace(const CPlusPlus::AST *ast, const QString &replacement)
{
    replace(startOf(ast), endOf(ast), replacement);
}

void QuickFixOperation::insert(int at, const QString &text)
{
    replace(at, at, text);
}

743
744
745
746
747
748
749
750
751
752
QString QuickFixOperation::textOf(int firstOffset, int lastOffset) const
{
    QTextCursor tc = _textCursor;
    tc.setPosition(firstOffset);
    tc.setPosition(lastOffset, QTextCursor::KeepAnchor);
    return tc.selectedText();
}

QString QuickFixOperation::textOf(AST *ast) const
{
753
    return textOf(startOf(ast), endOf(ast));
754
755
}

Roberto Raggi's avatar
Roberto Raggi committed
756
void QuickFixOperation::applyChangeSet()
757
{
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
758
    Range range;
759

Roberto Raggi's avatar
Roberto Raggi committed
760
761
    if (_topLevelNode)
        range = createRange(_topLevelNode);
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
762
763

    _textCursor.beginEditBlock();
764
765
766

    _changeSet.write(&_textCursor);

Roberto Raggi's avatar
Roberto Raggi committed
767
    if (_topLevelNode)
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
768
        reindent(range);
769

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
770
    _textCursor.endEditBlock();
771
772
}

773
774
775
776
777
778
779
780
781
782
783
CPPQuickFixCollector::CPPQuickFixCollector()
    : _modelManager(CppTools::CppModelManagerInterface::instance()), _editor(0)
{ }

CPPQuickFixCollector::~CPPQuickFixCollector()
{ }

bool CPPQuickFixCollector::supportsEditor(TextEditor::ITextEditable *editor)
{ return qobject_cast<CPPEditorEditable *>(editor) != 0; }

bool CPPQuickFixCollector::triggersCompletion(TextEditor::ITextEditable *)
784
{ return false; }
785
786
787
788

int CPPQuickFixCollector::startCompletion(TextEditor::ITextEditable *editable)
{
    Q_ASSERT(editable != 0);
789

790
    _editor = qobject_cast<CPPEditor *>(editable->widget());
791
792
793
794
    Q_ASSERT(_editor != 0);

    const SemanticInfo info = _editor->semanticInfo();

795
796
797
798
799
800
    if (info.revision != _editor->document()->revision()) {
        // outdated
        qWarning() << "TODO: outdated semantic info, force a reparse.";
        return -1;
    }

801
    if (info.doc) {
802
803
804
        ASTPath astPath(info.doc);

        const QList<AST *> path = astPath(_editor->textCursor());
Roberto Raggi's avatar
Roberto Raggi committed
805
806
        if (path.isEmpty())
            return -1;
807

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
808
        QSharedPointer<RewriteLogicalAndOp> rewriteLogicalAndOp(new RewriteLogicalAndOp(info.doc, info.snapshot, _editor));
809
        QSharedPointer<SplitIfStatementOp> splitIfStatementOp(new SplitIfStatementOp(info.doc, info.snapshot, _editor));
810
811
        QSharedPointer<MoveDeclarationOutOfIfOp> moveDeclarationOutOfIfOp(new MoveDeclarationOutOfIfOp(info.doc, info.snapshot, _editor));
        QSharedPointer<MoveDeclarationOutOfWhileOp> moveDeclarationOutOfWhileOp(new MoveDeclarationOutOfWhileOp(info.doc, info.snapshot, _editor));
812
        QSharedPointer<SplitSimpleDeclarationOp> splitSimpleDeclarationOp(new SplitSimpleDeclarationOp(info.doc, info.snapshot, _editor));
813
        QSharedPointer<AddBracesToIfOp> addBracesToIfOp(new AddBracesToIfOp(info.doc, info.snapshot, _editor));
814

815
816
        QList<QuickFixOperationPtr> candidates;
        candidates.append(rewriteLogicalAndOp);
817
        candidates.append(splitIfStatementOp);
818
819
        candidates.append(moveDeclarationOutOfIfOp);
        candidates.append(moveDeclarationOutOfWhileOp);
820
        candidates.append(splitSimpleDeclarationOp);
821
        candidates.append(addBracesToIfOp);
Roberto Raggi's avatar
Roberto Raggi committed
822

823
        QMap<int, QList<QuickFixOperationPtr> > matchedOps;
Roberto Raggi's avatar
Roberto Raggi committed
824

825
        foreach (QuickFixOperationPtr op, candidates) {
826
827
            op->setTextCursor(_editor->textCursor());
            int priority = op->match(path);
828
            if (priority != -1)
829
                matchedOps[priority].append(op);
830
        }
Roberto Raggi's avatar
Roberto Raggi committed
831

832
        QMapIterator<int, QList<QuickFixOperationPtr> > it(matchedOps);
833
834
835
836
        it.toBack();
        if (it.hasPrevious()) {
            it.previous();

837
            _quickFixes = it.value();
838
839
        }

840
841
        if (! _quickFixes.isEmpty())
            return editable->position();
842
843
    }

844
845
846
    return -1;
}

847
void CPPQuickFixCollector::completions(QList<TextEditor::CompletionItem> *quickFixItems)
848
{
849
850
851
852
853
854
855
856
    for (int i = 0; i < _quickFixes.size(); ++i) {
        QuickFixOperationPtr op = _quickFixes.at(i);

        TextEditor::CompletionItem item(this);
        item.text = op->description();
        item.data = QVariant::fromValue(i);
        quickFixItems->append(item);
    }
857
858
859
860
861
862
}

void CPPQuickFixCollector::complete(const TextEditor::CompletionItem &item)
{
    const int index = item.data.toInt();

863
864
    if (index < _quickFixes.size()) {
        QuickFixOperationPtr quickFix = _quickFixes.at(index);
865
        perform(quickFix);
866
867
868
    }
}

869
870
871
void CPPQuickFixCollector::perform(QuickFixOperationPtr op)
{
    op->setTextCursor(_editor->textCursor());
Roberto Raggi's avatar
Roberto Raggi committed
872
873
    op->createChangeSet();
    op->applyChangeSet();
874
875
}

876
877
void CPPQuickFixCollector::cleanup()
{
878
    _quickFixes.clear();
879
}