/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins Copyright (C) 2015 Sergio Martins This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "LoopUtils.h" #include "StringUtils.h" #include "clazy_stl.h" #include #include #include #include #include using namespace std; using namespace clang; Stmt *clazy::bodyFromLoop(Stmt *loop) { if (!loop) return nullptr; if (auto forstm = dyn_cast(loop)) return forstm->getBody(); if (auto rangeLoop = dyn_cast(loop)) return rangeLoop->getBody(); if (auto whilestm = dyn_cast(loop)) return whilestm->getBody(); if (auto dostm = dyn_cast(loop)) return dostm->getBody(); return nullptr; } bool clazy::loopCanBeInterrupted(clang::Stmt *stmt, const clang::SourceManager &sm, clang::SourceLocation onlyBeforeThisLoc) { if (!stmt) return false; if (isa(stmt) || isa(stmt) || isa(stmt)) { if (onlyBeforeThisLoc.isValid()) { FullSourceLoc sourceLoc(getLocStart(stmt), sm); FullSourceLoc otherSourceLoc(onlyBeforeThisLoc, sm); if (sourceLoc.isBeforeInTranslationUnitThan(otherSourceLoc)) return true; } else { return true; } } return clazy::any_of(stmt->children(), [&sm, onlyBeforeThisLoc](Stmt *s) { return clazy::loopCanBeInterrupted(s, sm, onlyBeforeThisLoc); }); } clang::Expr *clazy::containerExprForLoop(Stmt *loop) { if (!loop) return nullptr; if (auto rangeLoop = dyn_cast(loop)) return rangeLoop->getRangeInit(); if (auto constructExpr = dyn_cast(loop)) { if (constructExpr->getNumArgs() < 1) return nullptr; CXXConstructorDecl *constructorDecl = constructExpr->getConstructor(); if (!constructorDecl || clazy::name(constructorDecl) != "QForeachContainer") return nullptr; return constructExpr; } return nullptr; } VarDecl* clazy::containerDeclForLoop(clang::Stmt *loop) { Expr *expr = containerExprForLoop(loop); if (!expr) return nullptr; auto declRef = dyn_cast(expr); if (!declRef) return nullptr; ValueDecl *valueDecl = declRef->getDecl(); return valueDecl ? dyn_cast(valueDecl) : nullptr; } Stmt* clazy::isInLoop(clang::ParentMap *pmap, clang::Stmt *stmt) { if (!stmt) return nullptr; Stmt *p = pmap->getParent(stmt); while (p) { if (clazy::isLoop(p)) return p; p = pmap->getParent(p); } return nullptr; }