cppquickfix.cpp 25.5 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
102
    RewriteLogicalAndOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
        : QuickFixOperation(doc, snapshot, editor), matcher(doc->translationUnit()),
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
        if (path.size() == 0)
            return -1;        

281
282
283
        // show when we're on the 'if' of an if statement
        int index = path.size() - 1;
        IfStatementAST *ifStatement = path.at(index)->asIfStatement();
284
        if (ifStatement && isCursorOn(ifStatement->if_token)
285
286
287
288
289
290
291
292
293
            && ! 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();
294
            if (ifStatement && isCursorOn(ifStatement->statement)
295
296
297
298
299
300
301
302
303
304
305
306
                && ! 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
307
    virtual void createChangeSet()
308
    {
Roberto Raggi's avatar
Roberto Raggi committed
309
        setTopLevelNode(_statement);
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        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) {...}
*/
326
class MoveDeclarationOutOfIfOp: public QuickFixOperation
327
328
{
public:
329
    MoveDeclarationOutOfIfOp(Document::Ptr doc, const Snapshot &snapshot, CPPEditor *editor)
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
330
        : QuickFixOperation(doc, snapshot, editor), matcher(doc->translationUnit()),
331
332
333
334
335
           condition(0), pattern(0), core(0)
    {}

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

339
    virtual int match(const QList<AST *> &path)
340
341
342
343
344
345
346
347
348
349
350
351
352
    {
        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;

353
                    if (isCursorOn(core))
354
355
356
357
358
359
360
361
                        return index;
                }
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
362
    virtual void createChangeSet()
363
    {
Roberto Raggi's avatar
Roberto Raggi committed
364
        setTopLevelNode(pattern);
365
366
        const QString name = textOf(core);
        QString declaration = textOf(condition);
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
        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;
};

383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
    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)
        : QuickFixOperation(doc, snapshot, editor), matcher(doc->translationUnit()),
           condition(0), pattern(0), core(0)
    {}

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

404
    virtual int match(const QList<AST *> &path)
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    {
        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;

425
                    if (isCursorOn(core))
426
427
428
429
430
431
432
433
                        return index;
                }
            }
        }

        return -1;
    }

Roberto Raggi's avatar
Roberto Raggi committed
434
    virtual void createChangeSet()
435
    {
Roberto Raggi's avatar
Roberto Raggi committed
436
        setTopLevelNode(pattern);
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
        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
463
464
465
466
467
468
469
470
471
472
/*
  Replace
     if (something && something_else) {
     }

  with
     if (something) {
        if (something_else) {
        }
     }
Roberto Raggi's avatar
Roberto Raggi committed
473
474
475
476
477
478
479
480
481
482

  and
    if (something || something_else)
      x;

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

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

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

501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
        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)) {
521
                if (isCursorOn(condition->binary_op_token))
522
523
524
525
526
527
528
                    return index;
            } else {
                return -1;
            }
        }

        return -1;
Roberto Raggi's avatar
Roberto Raggi committed
529
530
    }

Roberto Raggi's avatar
Roberto Raggi committed
531
    virtual void createChangeSet()
Roberto Raggi's avatar
Roberto Raggi committed
532
    {
533
        Token binaryToken = tokenAt(condition->binary_op_token);
Roberto Raggi's avatar
Roberto Raggi committed
534

535
        if (binaryToken.is(T_AMPER_AMPER))
Roberto Raggi's avatar
Roberto Raggi committed
536
537
538
539
540
541
542
            splitAndCondition();
        else
            splitOrCondition();
    }

    void splitAndCondition()
    {
Roberto Raggi's avatar
Roberto Raggi committed
543
        setTopLevelNode(pattern);
Roberto Raggi's avatar
Roberto Raggi committed
544
545
        StatementAST *ifTrueStatement = pattern->statement;

Roberto Raggi's avatar
Roberto Raggi committed
546
        // take the right-expression from the condition.
547
548
549
550
        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
551
552
553
554
        replace(endOf(condition->left_expression), startOf(pattern->rparen_token), QString());

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

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

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

        // take the right-expression from the condition.
570
571
572
573
        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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
        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
596
597
598
599
private:
    BinaryExpressionAST *condition;
    IfStatementAST *pattern;
};
600

601
602
603
} // end of anonymous namespace


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

QuickFixOperation::~QuickFixOperation()
{ }

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
614
615
616
CPPEditor *QuickFixOperation::editor() const
{ return _editor; }

Roberto Raggi's avatar
Roberto Raggi committed
617
618
619
620
621
622
CPlusPlus::AST *QuickFixOperation::topLevelNode() const
{ return _topLevelNode; }

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

Roberto Raggi's avatar
Roberto Raggi committed
623
624
625
const Utils::ChangeSet &QuickFixOperation::changeSet() const
{ return _changeSet; }

626
627
628
QTextCursor QuickFixOperation::textCursor() const
{ return _textCursor; }

629
630
631
void QuickFixOperation::setTextCursor(const QTextCursor &cursor)
{ _textCursor = cursor; }

632
633
634
635
636
637
int QuickFixOperation::selectionStart() const
{ return _textCursor.selectionStart(); }

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

638
639
640
const CPlusPlus::Token &QuickFixOperation::tokenAt(unsigned index) const
{ return _doc->translationUnit()->tokenAt(index); }

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

648
649
650
651
652
653
int QuickFixOperation::startOf(const CPlusPlus::AST *ast) const
{
    return startOf(ast->firstToken());
}

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

660
661
662
663
664
int QuickFixOperation::endOf(const CPlusPlus::AST *ast) const
{
    return endOf(ast->lastToken() - 1);
}

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

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

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

    return false;
}

679
bool QuickFixOperation::isCursorOn(const CPlusPlus::AST *ast) const
680
681
682
683
684
685
686
687
688
689
690
691
692
{
    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
693
694
695
696
697
698
699
700
701
702
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)
703
{
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
704
705
706
    QTextCursor tc = range.begin;
    tc.setPosition(range.end.position(), QTextCursor::KeepAnchor);
    _editor->indentInsertedText(tc);
707
708
}

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

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)
728
        _changeSet.replace(start, end-start, replacement);
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
}

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

746
747
748
749
750
751
752
753
754
755
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
{
756
    return textOf(startOf(ast), endOf(ast));
757
758
}

Roberto Raggi's avatar
Roberto Raggi committed
759
void QuickFixOperation::applyChangeSet()
760
{
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
761
    Range range;
762

Roberto Raggi's avatar
Roberto Raggi committed
763
764
    if (_topLevelNode)
        range = createRange(_topLevelNode);
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
765
766

    _textCursor.beginEditBlock();
767
768
769

    _changeSet.write(&_textCursor);

Roberto Raggi's avatar
Roberto Raggi committed
770
    if (_topLevelNode)
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
771
        reindent(range);
772

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
773
    _textCursor.endEditBlock();
774
775
}

776
777
778
779
780
781
782
783
784
785
786
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 *)
787
{ return false; }
788
789
790
791

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

793
    _editor = qobject_cast<CPPEditor *>(editable->widget());
794
795
796
797
    Q_ASSERT(_editor != 0);

    const SemanticInfo info = _editor->semanticInfo();

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

804
    if (info.doc) {
805
806
807
808
809
        ASTPath astPath(info.doc);

        const QList<AST *> path = astPath(_editor->textCursor());
        // ### build the list of the quick fix ops by scanning path.

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

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

825
        QMap<int, QList<QuickFixOperationPtr> > matchedOps;
Roberto Raggi's avatar
Roberto Raggi committed
826

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

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

839
            _quickFixes = it.value();
840
841
        }

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

846
847
848
    return -1;
}

849
void CPPQuickFixCollector::completions(QList<TextEditor::CompletionItem> *quickFixItems)
850
{
851
852
853
854
855
856
857
858
    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);
    }
859
860
861
862
863
864
}

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

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

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

878
879
void CPPQuickFixCollector::cleanup()
{
880
    _quickFixes.clear();
881
}