flatten.cxx 20.1 KB
Newer Older
Noel Grandin's avatar
Noel Grandin committed
1 2 3 4 5 6 7 8 9
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

10
#include "plugin.hxx"
Noel Grandin's avatar
Noel Grandin committed
11 12 13 14 15
#include <cassert>
#include <string>
#include <iostream>
#include <fstream>
#include <set>
16
#include <stack>
Noel Grandin's avatar
Noel Grandin committed
17 18

/**
19
  Look for places where we can flatten the control flow in a method by returning early.
Noel Grandin's avatar
Noel Grandin committed
20 21 22 23
 */
namespace {

class Flatten:
24
    public loplugin::FilteringRewritePlugin<Flatten>
Noel Grandin's avatar
Noel Grandin committed
25 26
{
public:
27
    explicit Flatten(loplugin::InstantiationData const & data):
28
        FilteringRewritePlugin(data) {}
Noel Grandin's avatar
Noel Grandin committed
29 30 31 32 33 34

    virtual void run() override
    {
        TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
    }

35
    bool TraverseIfStmt(IfStmt *);
Noel Grandin's avatar
Noel Grandin committed
36
    bool TraverseCXXCatchStmt(CXXCatchStmt * );
37
    bool TraverseCompoundStmt(CompoundStmt *);
38 39 40 41 42
    bool TraverseFunctionDecl(FunctionDecl *);
    bool TraverseCXXMethodDecl(CXXMethodDecl *);
    bool TraverseCXXConstructorDecl(CXXConstructorDecl *);
    bool TraverseCXXConversionDecl(CXXConversionDecl *);
    bool TraverseCXXDestructorDecl(CXXDestructorDecl *);
43
    bool VisitIfStmt(IfStmt const * );
Noel Grandin's avatar
Noel Grandin committed
44
private:
45 46
    bool rewrite1(IfStmt const * );
    bool rewrite2(IfStmt const * );
47
    bool rewriteLargeIf(IfStmt const * );
Noel Grandin's avatar
Noel Grandin committed
48
    SourceRange ignoreMacroExpansions(SourceRange range);
49
    SourceRange extendOverComments(SourceRange range);
Noel Grandin's avatar
Noel Grandin committed
50
    std::string getSourceAsString(SourceRange range);
51
    std::string invertCondition(Expr const * condExpr, SourceRange conditionRange);
52
    bool isLargeCompoundStmt(Stmt const *);
53

54
    Stmt const * lastStmtInCompoundStmt = nullptr;
55 56
    FunctionDecl const * functionDecl = nullptr;
    CompoundStmt const * functionDeclBody = nullptr;
57
    Stmt const * mElseBranch = nullptr;
Noel Grandin's avatar
Noel Grandin committed
58 59
};

60
static Stmt const * containsSingleThrowExpr(Stmt const * stmt)
Noel Grandin's avatar
Noel Grandin committed
61 62 63 64 65 66 67 68 69 70 71 72
{
    if (auto compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
        if (compoundStmt->size() != 1)
            return nullptr;
        stmt = *compoundStmt->body_begin();
    }
    if (auto exprWithCleanups = dyn_cast<ExprWithCleanups>(stmt)) {
        stmt = exprWithCleanups->getSubExpr();
    }
    return dyn_cast<CXXThrowExpr>(stmt);
}

73 74 75 76 77 78 79 80 81 82 83 84 85 86
static bool containsVarDecl(Stmt const * stmt)
{
    if (auto compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
        for (auto i = compoundStmt->body_begin(); i != compoundStmt->body_end(); ++i) {
            auto declStmt = dyn_cast<DeclStmt>(*i);
            if (declStmt && isa<VarDecl>(*declStmt->decl_begin()))
                return true;
        }
        return false;
    }
    auto declStmt = dyn_cast<DeclStmt>(stmt);
    return declStmt && isa<VarDecl>(*declStmt->decl_begin());
}

87
bool Flatten::TraverseCXXCatchStmt(CXXCatchStmt* )
88
{
89 90 91 92 93 94
    // ignore stuff inside catch statements, where doing a "if...else..throw" is more natural
    return true;
}

bool Flatten::TraverseIfStmt(IfStmt * ifStmt)
{
95 96 97 98 99 100 101 102 103 104 105 106 107 108
    if (!WalkUpFromIfStmt(ifStmt)) {
        return false;
    }
    auto const saved = mElseBranch;
    mElseBranch = ifStmt->getElse();
    auto ret = true;
    for (auto const sub: ifStmt->children()) {
        if (!TraverseStmt(sub)) {
            ret = false;
            break;
        }
    }
    mElseBranch = saved;
    return ret;
109 110
}

111
bool Flatten::TraverseCompoundStmt(CompoundStmt * compoundStmt)
Noel Grandin's avatar
Noel Grandin committed
112
{
113 114 115 116 117 118
    auto copy = lastStmtInCompoundStmt;
    if (compoundStmt->size() > 0)
        lastStmtInCompoundStmt = compoundStmt->body_back();
    else
        lastStmtInCompoundStmt = nullptr;

119
    bool rv = RecursiveASTVisitor<Flatten>::TraverseCompoundStmt(compoundStmt);
120 121 122

    lastStmtInCompoundStmt = copy;
    return rv;
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
}

bool Flatten::TraverseFunctionDecl(FunctionDecl * fd)
{
    auto copy1 = functionDeclBody;
    auto copy2 = fd;
    functionDeclBody = dyn_cast_or_null<CompoundStmt>(fd->getBody());
    functionDecl = fd;
    bool rv = RecursiveASTVisitor<Flatten>::TraverseFunctionDecl(fd);
    functionDeclBody = copy1;
    functionDecl = copy2;
    return rv;
}

bool Flatten::TraverseCXXMethodDecl(CXXMethodDecl * fd)
{
    auto copy1 = functionDeclBody;
    auto copy2 = fd;
    functionDeclBody = dyn_cast_or_null<CompoundStmt>(fd->getBody());
    functionDecl = fd;
    bool rv = RecursiveASTVisitor<Flatten>::TraverseCXXMethodDecl(fd);
    functionDeclBody = copy1;
    functionDecl = copy2;
    return rv;
}

bool Flatten::TraverseCXXConstructorDecl(CXXConstructorDecl * fd)
{
    auto copy1 = functionDeclBody;
    auto copy2 = fd;
    functionDeclBody = dyn_cast_or_null<CompoundStmt>(fd->getBody());
    functionDecl = fd;
    bool rv = RecursiveASTVisitor<Flatten>::TraverseCXXConstructorDecl(fd);
    functionDeclBody = copy1;
    functionDecl = copy2;
    return rv;
}

bool Flatten::TraverseCXXConversionDecl(CXXConversionDecl * fd)
{
    auto copy1 = functionDeclBody;
    auto copy2 = fd;
    functionDeclBody = dyn_cast_or_null<CompoundStmt>(fd->getBody());
    functionDecl = fd;
    bool rv = RecursiveASTVisitor<Flatten>::TraverseCXXConversionDecl(fd);
    functionDeclBody = copy1;
    functionDecl = copy2;
170
    return rv;
Noel Grandin's avatar
Noel Grandin committed
171 172
}

173 174 175 176 177 178 179 180 181 182 183 184 185
bool Flatten::TraverseCXXDestructorDecl(CXXDestructorDecl * fd)
{
    auto copy1 = functionDeclBody;
    auto copy2 = fd;
    functionDeclBody = dyn_cast_or_null<CompoundStmt>(fd->getBody());
    functionDecl = fd;
    bool rv = RecursiveASTVisitor<Flatten>::TraverseCXXDestructorDecl(fd);
    functionDeclBody = copy1;
    functionDecl = copy2;
    return rv;
}


186
bool Flatten::VisitIfStmt(IfStmt const * ifStmt)
Noel Grandin's avatar
Noel Grandin committed
187 188 189 190
{
    if (ignoreLocation(ifStmt))
        return true;

191 192
    // ignore if we are part of an if/then/else/if chain
    if (ifStmt == mElseBranch || (ifStmt->getElse() && isa<IfStmt>(ifStmt->getElse())))
Noel Grandin's avatar
Noel Grandin committed
193 194
        return true;

195 196 197 198 199 200 201 202 203 204 205 206
    // look for a large if(){} block at the end of a function
    if (!ifStmt->getElse()
        && (functionDecl->getReturnType().isNull() || functionDecl->getReturnType()->isVoidType())
        && functionDeclBody && functionDeclBody->size()
        && functionDeclBody->body_back() == ifStmt
        && isLargeCompoundStmt(ifStmt->getThen()))
    {
        if (!rewriteLargeIf(ifStmt))
        {
            report(
                DiagnosticsEngine::Warning,
                "large if statement at end of function, rather invert the condition and exit early, and flatten the function",
207
                compat::getBeginLoc(ifStmt))
208 209 210 211 212 213
              << ifStmt->getSourceRange();
        }
        return true;
    }

    if (!ifStmt->getElse())
214 215
        return true;

216 217 218 219 220 221 222 223
    auto const thenThrowExpr = containsSingleThrowExpr(ifStmt->getThen());
    auto const elseThrowExpr = containsSingleThrowExpr(ifStmt->getElse());
    // If neither contains a throw, nothing to do; if both contain throws, no
    // improvement:
    if ((thenThrowExpr == nullptr) == (elseThrowExpr == nullptr)) {
        return true;
    }

224 225 226 227
    if (containsPreprocessingConditionalInclusion(ifStmt->getSourceRange())) {
        return true;
    }

228
    if (elseThrowExpr)
229
    {
230 231
        // if the "if" statement is not the last statement in its block, and it contains
        // var decls in its then block, we cannot de-indent the then block without
232
        // extending the lifetime of some variables, which may be problematic
233
        if (ifStmt != lastStmtInCompoundStmt && containsVarDecl(ifStmt->getThen()))
234 235 236 237 238 239 240
            return true;

        if (!rewrite1(ifStmt))
        {
            report(
                DiagnosticsEngine::Warning,
                "unconditional throw in else branch, rather invert the condition, throw early, and flatten the normal case",
241
                compat::getBeginLoc(elseThrowExpr))
242
                << elseThrowExpr->getSourceRange();
243 244 245
            report(
                DiagnosticsEngine::Note,
                "if condition here",
246
                compat::getBeginLoc(ifStmt))
247 248 249
                << ifStmt->getSourceRange();
        }
    }
250
    if (thenThrowExpr)
Noel Grandin's avatar
Noel Grandin committed
251
    {
252 253 254
        // if the "if" statement is not the last statement in it's block, and it contains
        // var decls in it's else block, we cannot de-indent the else block without
        // extending the lifetime of some variables, which may be problematic
255
        if (ifStmt != lastStmtInCompoundStmt && containsVarDecl(ifStmt->getElse()))
256 257 258 259 260 261 262
            return true;

        if (!rewrite2(ifStmt))
        {
            report(
                DiagnosticsEngine::Warning,
                "unconditional throw in then branch, just flatten the else",
263
                compat::getBeginLoc(thenThrowExpr))
264
                << thenThrowExpr->getSourceRange();
265
        }
Noel Grandin's avatar
Noel Grandin committed
266 267 268 269 270
    }
    return true;
}

static std::string stripOpenAndCloseBrace(std::string s);
271
static std::string stripTrailingEmptyLines(std::string s);
272 273
static std::string deindent(std::string const & s);
static std::vector<std::string> split(std::string s);
274
static bool startswith(std::string const & rStr, char const * pSubStr);
275 276 277
static int countLeadingSpaces(std::string const &);
static std::string padSpace(int iNoSpaces);
static void replace(std::string & s, std::string const & from, std::string const & to);
Noel Grandin's avatar
Noel Grandin committed
278

279
bool Flatten::rewrite1(IfStmt const * ifStmt)
Noel Grandin's avatar
Noel Grandin committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
{
    if (!rewriter)
        return false;

    auto conditionRange = ignoreMacroExpansions(ifStmt->getCond()->getSourceRange());
    if (!conditionRange.isValid()) {
        return false;
    }
    auto thenRange = ignoreMacroExpansions(ifStmt->getThen()->getSourceRange());
    if (!thenRange.isValid()) {
        return false;
    }
    auto elseRange = ignoreMacroExpansions(ifStmt->getElse()->getSourceRange());
    if (!elseRange.isValid()) {
        return false;
    }
296 297 298 299 300
    SourceRange elseKeywordRange = ifStmt->getElseLoc();

    thenRange = extendOverComments(thenRange);
    elseRange = extendOverComments(elseRange);
    elseKeywordRange = extendOverComments(elseKeywordRange);
Noel Grandin's avatar
Noel Grandin committed
301 302 303

    // in adjusting the formatting I assume that "{" starts on a new line

304
    std::string conditionString = invertCondition(ifStmt->getCond(), conditionRange);
Noel Grandin's avatar
Noel Grandin committed
305 306 307 308 309 310 311

    std::string thenString = getSourceAsString(thenRange);
    if (auto compoundStmt = dyn_cast<CompoundStmt>(ifStmt->getThen())) {
        if (compoundStmt->getLBracLoc().isValid()) {
            thenString = stripOpenAndCloseBrace(thenString);
        }
    }
312
    thenString = deindent(thenString);
Noel Grandin's avatar
Noel Grandin committed
313 314 315 316 317 318

    std::string elseString = getSourceAsString(elseRange);

    if (!replaceText(elseRange, thenString)) {
        return false;
    }
319
    if (!removeText(elseKeywordRange)) {
Noel Grandin's avatar
Noel Grandin committed
320 321 322 323 324 325 326 327 328 329 330 331
        return false;
    }
    if (!replaceText(thenRange, elseString)) {
        return false;
    }
    if (!replaceText(conditionRange, conditionString)) {
        return false;
    }

    return true;
}

332 333 334 335 336 337 338 339 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
bool Flatten::rewrite2(IfStmt const * ifStmt)
{
    if (!rewriter)
        return false;

    auto conditionRange = ignoreMacroExpansions(ifStmt->getCond()->getSourceRange());
    if (!conditionRange.isValid()) {
        return false;
    }
    auto thenRange = ignoreMacroExpansions(ifStmt->getThen()->getSourceRange());
    if (!thenRange.isValid()) {
        return false;
    }
    auto elseRange = ignoreMacroExpansions(ifStmt->getElse()->getSourceRange());
    if (!elseRange.isValid()) {
        return false;
    }
    SourceRange elseKeywordRange = ifStmt->getElseLoc();

    elseRange = extendOverComments(elseRange);
    elseKeywordRange = extendOverComments(elseKeywordRange);

    // in adjusting the formatting I assume that "{" starts on a new line

    std::string elseString = getSourceAsString(elseRange);
    if (auto compoundStmt = dyn_cast<CompoundStmt>(ifStmt->getElse())) {
        if (compoundStmt->getLBracLoc().isValid()) {
            elseString = stripOpenAndCloseBrace(elseString);
        }
    }
    elseString = deindent(elseString);

    if (!replaceText(elseRange, elseString)) {
        return false;
    }
    if (!removeText(elseKeywordRange)) {
        return false;
    }

    return true;
}

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
bool Flatten::rewriteLargeIf(IfStmt const * ifStmt)
{
    if (!rewriter)
        return false;

    auto conditionRange = ignoreMacroExpansions(ifStmt->getCond()->getSourceRange());
    if (!conditionRange.isValid()) {
        return false;
    }
    auto thenRange = ignoreMacroExpansions(ifStmt->getThen()->getSourceRange());
    if (!thenRange.isValid()) {
        return false;
    }

    thenRange = extendOverComments(thenRange);

    // in adjusting the formatting I assume that "{" starts on a new line

    std::string conditionString = invertCondition(ifStmt->getCond(), conditionRange);

    std::string thenString = getSourceAsString(thenRange);
    if (auto compoundStmt = dyn_cast<CompoundStmt>(ifStmt->getThen())) {
        if (compoundStmt->getLBracLoc().isValid()) {
            thenString = stripOpenAndCloseBrace(thenString);
        }
    }
    int iNoSpaces = countLeadingSpaces(thenString);
    thenString = padSpace(iNoSpaces) + "return;\n\n" + deindent(thenString);
    thenString = stripTrailingEmptyLines(thenString);

    if (!replaceText(thenRange, thenString)) {
        return false;
    }
    if (!replaceText(conditionRange, conditionString)) {
        return false;
    }

    return true;
}

414 415 416 417 418 419 420 421 422
std::string Flatten::invertCondition(Expr const * condExpr, SourceRange conditionRange)
{
    std::string s = getSourceAsString(conditionRange);

    condExpr = condExpr->IgnoreImpCasts();

    if (auto exprWithCleanups = dyn_cast<ExprWithCleanups>(condExpr))
        condExpr = exprWithCleanups->getSubExpr()->IgnoreImpCasts();

423 424 425 426 427 428 429
    // an if statement will automatically invoke a bool-conversion method
    if (auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(condExpr))
    {
        if (isa<CXXConversionDecl>(memberCallExpr->getMethodDecl()))
            condExpr = memberCallExpr->getImplicitObjectArgument()->IgnoreImpCasts();
    }

430 431 432 433 434 435 436 437
    if (auto unaryOp = dyn_cast<UnaryOperator>(condExpr))
    {
        if (unaryOp->getOpcode() != UO_LNot)
            return "!(" + s + ")";
        auto i = s.find("!");
        assert (i != std::string::npos);
        s = s.substr(i+1);
    }
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 463 464 465
    else if (auto binaryOp = dyn_cast<BinaryOperator>(condExpr))
    {
        switch (binaryOp->getOpcode())
        {
            case BO_LT: replace(s, "<", ">="); break;
            case BO_GT: replace(s, ">", "<="); break;
            case BO_LE: replace(s, "<=", ">"); break;
            case BO_GE: replace(s, ">=", "<"); break;
            case BO_EQ: replace(s, "==", "!="); break;
            case BO_NE: replace(s, "!=", "=="); break;
            default:
                s = "!(" + s + ")";
        }
    }
    else if (auto opCallExpr = dyn_cast<CXXOperatorCallExpr>(condExpr))
    {
        switch (opCallExpr->getOperator())
        {
            case OO_Less: replace(s, "<", ">="); break;
            case OO_Greater: replace(s, ">", "<="); break;
            case OO_LessEqual: replace(s, "<=", ">"); break;
            case OO_GreaterEqual: replace(s, ">=", "<"); break;
            case OO_EqualEqual: replace(s, "==", "!="); break;
            case OO_ExclaimEqual: replace(s, "!=", "=="); break;
            default:
                s = "!(" + s + ")";
        }
    }
466 467 468 469 470 471 472
    else if (isa<DeclRefExpr>(condExpr) || isa<CallExpr>(condExpr) || isa<MemberExpr>(condExpr))
        s = "!" + s;
    else
        s = "!(" + s + ")";
    return s;
}

Noel Grandin's avatar
Noel Grandin committed
473 474
std::string stripOpenAndCloseBrace(std::string s)
{
475
    size_t i = s.find("{");
476 477 478 479 480 481
    if (i == std::string::npos)
        throw "did not find {";

    ++i;
    // strip to line end
    while (s[i] == ' ')
482
        ++i;
483 484 485 486
    if (s[i] == '\n')
         ++i;
    s = s.substr(i);

487
    i = s.rfind("}");
488 489 490 491
    if (i == std::string::npos)
        throw "did not find }";
    --i;
    while (s[i] == ' ')
492
        --i;
493
    s = s.substr(0,i);
Noel Grandin's avatar
Noel Grandin committed
494 495 496
    return s;
}

497
std::string deindent(std::string const & s)
Noel Grandin's avatar
Noel Grandin committed
498 499 500 501
{
    std::vector<std::string> lines = split(s);
    std::string rv;
    for (auto s : lines) {
502 503 504 505
        if (startswith(s, "    "))
            rv += s.substr(4);
        else
            rv += s;
Noel Grandin's avatar
Noel Grandin committed
506 507 508 509 510
        rv += "\n";
    }
    return rv;
}

511
std::vector<std::string> split(std::string s)
Noel Grandin's avatar
Noel Grandin committed
512
{
513 514
    if (s.back() == '\n')
        s = s.substr(0, s.size()-1);
Noel Grandin's avatar
Noel Grandin committed
515 516 517 518 519 520 521 522 523 524 525 526
    size_t next = -1;
    std::vector<std::string> rv;
    do
    {
        size_t current = next + 1;
        next = s.find_first_of( "\n", current );
        rv.push_back(s.substr( current, next - current ));
    }
    while (next != std::string::npos);
    return rv;
}

527
bool startswith(std::string const & rStr, char const * pSubStr)
528 529 530 531
{
    return rStr.compare(0, strlen(pSubStr), pSubStr) == 0;
}

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
int countLeadingSpaces(std::string const & s)
{
    int i = 0;
    while (i < (int)s.length() && s[i] == ' ')
        i++;
    return i;
}

std::string padSpace(int iNoSpaces)
{
    std::string s;
    for (int i = 0; i < iNoSpaces; ++i)
        s += " ";
    return s;
}

std::string stripTrailingEmptyLines(std::string s)
{
    while (s.back() == '\n')
        s.resize(s.length() - 1);
    return s;
}

void replace(std::string & s, std::string const & from, std::string const & to)
{
    auto i = s.find(from);
    assert (i != std::string::npos);
    s.replace(i, from.length(), to);
    // just in case we have something really weird, like the operator token is also present in the rest of the condition somehow
    assert (s.find(from) == std::string::npos);
}

Noel Grandin's avatar
Noel Grandin committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
SourceRange Flatten::ignoreMacroExpansions(SourceRange range) {
    while (compiler.getSourceManager().isMacroArgExpansion(range.getBegin())) {
        range.setBegin(
            compiler.getSourceManager().getImmediateMacroCallerLoc(
                range.getBegin()));
    }
    if (range.getBegin().isMacroID()) {
        SourceLocation loc;
        if (Lexer::isAtStartOfMacroExpansion(
                range.getBegin(), compiler.getSourceManager(),
                compiler.getLangOpts(), &loc))
        {
            range.setBegin(loc);
        }
    }
    while (compiler.getSourceManager().isMacroArgExpansion(range.getEnd())) {
        range.setEnd(
            compiler.getSourceManager().getImmediateMacroCallerLoc(
                range.getEnd()));
    }
    if (range.getEnd().isMacroID()) {
        SourceLocation loc;
        if (Lexer::isAtEndOfMacroExpansion(
                range.getEnd(), compiler.getSourceManager(),
                compiler.getLangOpts(), &loc))
        {
            range.setEnd(loc);
        }
    }
    return range.getBegin().isMacroID() || range.getEnd().isMacroID()
        ? SourceRange() : range;
}

597 598 599 600 601 602 603 604
/**
 * Extend the SourceRange to include any leading and trailing whitespace, and any comments.
 */
SourceRange Flatten::extendOverComments(SourceRange range)
{
    SourceManager& SM = compiler.getSourceManager();
    SourceLocation startLoc = range.getBegin();
    SourceLocation endLoc = range.getEnd();
605 606
    char const *p1 = SM.getCharacterData( startLoc );
    char const *p2 = SM.getCharacterData( endLoc );
607 608 609 610 611 612 613

    // scan backwards from the beginning to include any spaces on that line
    while (*(p1-1) == ' ')
        --p1;
    startLoc = startLoc.getLocWithOffset(p1 - SM.getCharacterData( startLoc ));

    // look for trailing ";"
614
    while (*(p2+1) == ';')
615 616
        ++p2;
    // look for trailing " "
617
    while (*(p2+1) == ' ')
618 619
        ++p2;
    // look for single line comments attached to the end of the statement
620
    if (*(p2+1) == '/' && *(p2+2) == '/')
621 622
    {
        p2 += 2;
623
        while (*(p2+1) && *(p2+1) != '\n')
624
            ++p2;
625
        if (*(p2+1) == '\n')
626 627 628 629 630
            ++p2;
    }
    else
    {
        // make the source code we extract include any trailing "\n"
631
        if (*(p2+1) == '\n')
632 633 634 635 636 637 638
            ++p2;
    }
    endLoc = endLoc.getLocWithOffset(p2 - SM.getCharacterData( endLoc ));

    return SourceRange(startLoc, endLoc);
}

Noel Grandin's avatar
Noel Grandin committed
639 640 641 642 643
std::string Flatten::getSourceAsString(SourceRange range)
{
    SourceManager& SM = compiler.getSourceManager();
    SourceLocation startLoc = range.getBegin();
    SourceLocation endLoc = range.getEnd();
644 645
    char const *p1 = SM.getCharacterData( startLoc );
    char const *p2 = SM.getCharacterData( endLoc );
646 647
    p2 += Lexer::MeasureTokenLength( endLoc, SM, compiler.getLangOpts());
    return std::string( p1, p2 - p1);
Noel Grandin's avatar
Noel Grandin committed
648 649
}

650 651 652 653 654 655 656 657
bool Flatten::isLargeCompoundStmt(Stmt const * stmt)
{
    auto stmtRange = stmt->getSourceRange();
    std::string s = getSourceAsString(stmtRange);
    return std::count(s.begin(), s.end(), '\n') > 10;
}

loplugin::Plugin::Registration< Flatten > X("flatten", false);
Noel Grandin's avatar
Noel Grandin committed
658 659 660 661

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */