Index: include/clang/Tooling/Analysis/ExprMutationAnalyzer.h =================================================================== --- /dev/null +++ include/clang/Tooling/Analysis/ExprMutationAnalyzer.h @@ -0,0 +1,98 @@ +//===---------- ExprMutationAnalyzer.h ------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#ifndef LLVM_CLANG_TOOLING_ANALYSIS_EXPRMUTATIONANALYZER_H +#define LLVM_CLANG_TOOLING_ANALYSIS_EXPRMUTATIONANALYZER_H + +#include + +#include "clang/AST/AST.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "llvm/ADT/DenseMap.h" + +namespace clang { +namespace tooling { + +class FunctionParmMutationAnalyzer; + +/// Analyzes whether any mutative operations are applied to an expression within +/// a given statement. +class ExprMutationAnalyzer { +public: + ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context) + : Stm(Stm), Context(Context) {} + + bool isMutated(const Expr *Exp) { return findMutation(Exp) != nullptr; } + bool isMutated(const Decl *Dec) { return findMutation(Dec) != nullptr; } + const Stmt *findMutation(const Expr *Exp); + const Stmt *findMutation(const Decl *Dec); + + bool isPointeeMutated(const Expr *Exp) { + return findPointeeMutation(Exp) != nullptr; + } + bool isPointeeMutated(const Decl *Dec) { + return findPointeeMutation(Dec) != nullptr; + } + const Stmt *findPointeeMutation(const Expr *Exp); + const Stmt *findPointeeMutation(const Decl *Dec); + +private: + using MutationFinder = const Stmt *(ExprMutationAnalyzer::*)(const Expr *); + using ResultMap = llvm::DenseMap; + + const Stmt *findMutationMemoized(const Expr *Exp, + llvm::ArrayRef Finders, + ResultMap &MemoizedResults); + const Stmt *tryEachDeclRef(const Decl *Dec, MutationFinder Finder); + + bool isUnevaluated(const Expr *Exp); + + const Stmt *findExprMutation(ArrayRef Matches); + const Stmt *findDeclMutation(ArrayRef Matches); + const Stmt * + findExprPointeeMutation(ArrayRef Matches); + const Stmt * + findDeclPointeeMutation(ArrayRef Matches); + + const Stmt *findDirectMutation(const Expr *Exp); + const Stmt *findMemberMutation(const Expr *Exp); + const Stmt *findArrayElementMutation(const Expr *Exp); + const Stmt *findCastMutation(const Expr *Exp); + const Stmt *findRangeLoopMutation(const Expr *Exp); + const Stmt *findReferenceMutation(const Expr *Exp); + const Stmt *findFunctionArgMutation(const Expr *Exp); + + const Stmt &Stm; + ASTContext &Context; + llvm::DenseMap> + FuncParmAnalyzer; + ResultMap Results; + ResultMap PointeeResults; +}; + +// A convenient wrapper around ExprMutationAnalyzer for analyzing function +// params. +class FunctionParmMutationAnalyzer { +public: + FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context); + + bool isMutated(const ParmVarDecl *Parm) { + return findMutation(Parm) != nullptr; + } + const Stmt *findMutation(const ParmVarDecl *Parm); + +private: + ExprMutationAnalyzer BodyAnalyzer; + llvm::DenseMap Results; +}; + +} // namespace tooling +} // namespace clang + +#endif // LLVM_CLANG_TOOLING_ANALYSIS_EXPRMUTATIONANALYZER_H Index: lib/Tooling/Analysis/CMakeLists.txt =================================================================== --- /dev/null +++ lib/Tooling/Analysis/CMakeLists.txt @@ -0,0 +1,10 @@ +set(LLVM_LINK_COMPONENTS support) + +add_clang_library(clangToolingAnalysis + ExprMutationAnalyzer.cpp + + LINK_LIBS + clangAST + clangASTMatchers + clangBasic + ) Index: lib/Tooling/Analysis/ExprMutationAnalyzer.cpp =================================================================== --- /dev/null +++ lib/Tooling/Analysis/ExprMutationAnalyzer.cpp @@ -0,0 +1,447 @@ +//===---------- ExprMutationAnalyzer.cpp ----------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#include "clang/Tooling/Analysis/ExprMutationAnalyzer.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "llvm/ADT/STLExtras.h" + +namespace clang { +namespace tooling { +using namespace ::clang::ast_matchers; + +namespace { + +AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) { + return llvm::is_contained(Node.capture_inits(), E); +} + +AST_MATCHER_P(CXXForRangeStmt, hasRangeStmt, + ast_matchers::internal::Matcher, InnerMatcher) { + const DeclStmt *const Range = Node.getRangeStmt(); + return InnerMatcher.matches(*Range, Finder, Builder); +} + +const ast_matchers::internal::VariadicDynCastAllOfMatcher + cxxTypeidExpr; + +AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) { + return Node.isPotentiallyEvaluated(); +} + +const ast_matchers::internal::VariadicDynCastAllOfMatcher + cxxNoexceptExpr; + +const ast_matchers::internal::VariadicDynCastAllOfMatcher + genericSelectionExpr; + +AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr, + ast_matchers::internal::Matcher, InnerMatcher) { + return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder); +} + +const auto nonConstReferenceType = [] { + return hasUnqualifiedDesugaredType( + referenceType(pointee(unless(isConstQualified())))); +}; + +const auto nonConstPointerType = [] { + return hasUnqualifiedDesugaredType( + pointerType(pointee(unless(isConstQualified())))); +}; + +const auto isMoveOnly = [] { + return cxxRecordDecl( + hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))), + hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))), + unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(), + unless(isDeleted()))), + hasMethod(cxxMethodDecl(isCopyAssignmentOperator(), + unless(isDeleted())))))); +}; + +template struct NodeID; +template <> struct NodeID { static const std::string value; }; +template <> struct NodeID { static const std::string value; }; +const std::string NodeID::value = "expr"; +const std::string NodeID::value = "decl"; + +template +const Stmt *tryEachMatch(ArrayRef Matches, + ExprMutationAnalyzer *Analyzer, F Finder) { + const StringRef ID = NodeID::value; + for (const auto &Nodes : Matches) { + if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs(ID))) + return S; + } + return nullptr; +} + +} // namespace + +const Stmt *ExprMutationAnalyzer::findMutation(const Expr *Exp) { + return findMutationMemoized(Exp, + {&ExprMutationAnalyzer::findDirectMutation, + &ExprMutationAnalyzer::findMemberMutation, + &ExprMutationAnalyzer::findArrayElementMutation, + &ExprMutationAnalyzer::findCastMutation, + &ExprMutationAnalyzer::findRangeLoopMutation, + &ExprMutationAnalyzer::findReferenceMutation, + &ExprMutationAnalyzer::findFunctionArgMutation}, + Results); +} + +const Stmt *ExprMutationAnalyzer::findMutation(const Decl *Dec) { + return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findMutation); +} + +const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Expr *Exp) { + return findMutationMemoized(Exp, {/*TODO*/}, PointeeResults); +} + +const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Decl *Dec) { + return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findPointeeMutation); +} + +const Stmt *ExprMutationAnalyzer::findMutationMemoized( + const Expr *Exp, llvm::ArrayRef Finders, + ResultMap &MemoizedResults) { + const auto Memoized = MemoizedResults.find(Exp); + if (Memoized != MemoizedResults.end()) + return Memoized->second; + + if (isUnevaluated(Exp)) + return MemoizedResults[Exp] = nullptr; + + for (const auto &Finder : Finders) { + if (const Stmt *S = (this->*Finder)(Exp)) + return MemoizedResults[Exp] = S; + } + + return MemoizedResults[Exp] = nullptr; +} + +const Stmt *ExprMutationAnalyzer::tryEachDeclRef(const Decl *Dec, + MutationFinder Finder) { + const auto Refs = + match(findAll(declRefExpr(to(equalsNode(Dec))).bind(NodeID::value)), + Stm, Context); + for (const auto &RefNodes : Refs) { + const auto *E = RefNodes.getNodeAs(NodeID::value); + if ((this->*Finder)(E)) + return E; + } + return nullptr; +} + +bool ExprMutationAnalyzer::isUnevaluated(const Expr *Exp) { + return selectFirst( + NodeID::value, + match( + findAll( + expr(equalsNode(Exp), + anyOf( + // `Exp` is part of the underlying expression of + // decltype/typeof if it has an ancestor of + // typeLoc. + hasAncestor(typeLoc(unless( + hasAncestor(unaryExprOrTypeTraitExpr())))), + hasAncestor(expr(anyOf( + // `UnaryExprOrTypeTraitExpr` is unevaluated + // unless it's sizeof on VLA. + unaryExprOrTypeTraitExpr(unless(sizeOfExpr( + hasArgumentOfType(variableArrayType())))), + // `CXXTypeidExpr` is unevaluated unless it's + // applied to an expression of glvalue of + // polymorphic class type. + cxxTypeidExpr( + unless(isPotentiallyEvaluated())), + // The controlling expression of + // `GenericSelectionExpr` is unevaluated. + genericSelectionExpr(hasControllingExpr( + hasDescendant(equalsNode(Exp)))), + cxxNoexceptExpr()))))) + .bind(NodeID::value)), + Stm, Context)) != nullptr; +} + +const Stmt * +ExprMutationAnalyzer::findExprMutation(ArrayRef Matches) { + return tryEachMatch(Matches, this, &ExprMutationAnalyzer::findMutation); +} + +const Stmt * +ExprMutationAnalyzer::findDeclMutation(ArrayRef Matches) { + return tryEachMatch(Matches, this, &ExprMutationAnalyzer::findMutation); +} + +const Stmt *ExprMutationAnalyzer::findExprPointeeMutation( + ArrayRef Matches) { + return tryEachMatch(Matches, this, + &ExprMutationAnalyzer::findPointeeMutation); +} + +const Stmt *ExprMutationAnalyzer::findDeclPointeeMutation( + ArrayRef Matches) { + return tryEachMatch(Matches, this, + &ExprMutationAnalyzer::findPointeeMutation); +} + +const Stmt *ExprMutationAnalyzer::findDirectMutation(const Expr *Exp) { + // LHS of any assignment operators. + const auto AsAssignmentLhs = + binaryOperator(isAssignmentOperator(), hasLHS(equalsNode(Exp))); + + // Operand of increment/decrement operators. + const auto AsIncDecOperand = + unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")), + hasUnaryOperand(equalsNode(Exp))); + + // Invoking non-const member function. + // A member function is assumed to be non-const when it is unresolved. + const auto NonConstMethod = cxxMethodDecl(unless(isConst())); + const auto AsNonConstThis = + expr(anyOf(cxxMemberCallExpr(callee(NonConstMethod), on(equalsNode(Exp))), + cxxOperatorCallExpr(callee(NonConstMethod), + hasArgument(0, equalsNode(Exp))), + callExpr(callee(expr(anyOf( + unresolvedMemberExpr(hasObjectExpression(equalsNode(Exp))), + cxxDependentScopeMemberExpr( + hasObjectExpression(equalsNode(Exp))))))))); + + // Taking address of 'Exp'. + // We're assuming 'Exp' is mutated as soon as its address is taken, though in + // theory we can follow the pointer and see whether it escaped `Stm` or is + // dereferenced and then mutated. This is left for future improvements. + const auto AsAmpersandOperand = + unaryOperator(hasOperatorName("&"), + // A NoOp implicit cast is adding const. + unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))), + hasUnaryOperand(equalsNode(Exp))); + const auto AsPointerFromArrayDecay = + castExpr(hasCastKind(CK_ArrayToPointerDecay), + unless(hasParent(arraySubscriptExpr())), has(equalsNode(Exp))); + // Treat calling `operator->()` of move-only classes as taking address. + // These are typically smart pointers with unique ownership so we treat + // mutation of pointee as mutation of the smart pointer itself. + const auto AsOperatorArrowThis = + cxxOperatorCallExpr(hasOverloadedOperatorName("->"), + callee(cxxMethodDecl(ofClass(isMoveOnly()), + returns(nonConstPointerType()))), + argumentCountIs(1), hasArgument(0, equalsNode(Exp))); + + // Used as non-const-ref argument when calling a function. + // An argument is assumed to be non-const-ref when the function is unresolved. + // Instantiated template functions are not handled here but in + // findFunctionArgMutation which has additional smarts for handling forwarding + // references. + const auto NonConstRefParam = forEachArgumentWithParam( + equalsNode(Exp), parmVarDecl(hasType(nonConstReferenceType()))); + const auto NotInstantiated = unless(hasDeclaration(isInstantiated())); + const auto AsNonConstRefArg = anyOf( + callExpr(NonConstRefParam, NotInstantiated), + cxxConstructExpr(NonConstRefParam, NotInstantiated), + callExpr(callee(expr(anyOf(unresolvedLookupExpr(), unresolvedMemberExpr(), + cxxDependentScopeMemberExpr(), + hasType(templateTypeParmType())))), + hasAnyArgument(equalsNode(Exp))), + cxxUnresolvedConstructExpr(hasAnyArgument(equalsNode(Exp)))); + + // Captured by a lambda by reference. + // If we're initializing a capture with 'Exp' directly then we're initializing + // a reference capture. + // For value captures there will be an ImplicitCastExpr . + const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp)); + + // Returned as non-const-ref. + // If we're returning 'Exp' directly then it's returned as non-const-ref. + // For returning by value there will be an ImplicitCastExpr . + // For returning by const-ref there will be an ImplicitCastExpr (for + // adding const.) + const auto AsNonConstRefReturn = returnStmt(hasReturnValue(equalsNode(Exp))); + + const auto Matches = + match(findAll(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand, AsNonConstThis, + AsAmpersandOperand, AsPointerFromArrayDecay, + AsOperatorArrowThis, AsNonConstRefArg, + AsLambdaRefCaptureInit, AsNonConstRefReturn)) + .bind("stmt")), + Stm, Context); + return selectFirst("stmt", Matches); +} + +const Stmt *ExprMutationAnalyzer::findMemberMutation(const Expr *Exp) { + // Check whether any member of 'Exp' is mutated. + const auto MemberExprs = + match(findAll(expr(anyOf(memberExpr(hasObjectExpression(equalsNode(Exp))), + cxxDependentScopeMemberExpr( + hasObjectExpression(equalsNode(Exp))))) + .bind(NodeID::value)), + Stm, Context); + return findExprMutation(MemberExprs); +} + +const Stmt *ExprMutationAnalyzer::findArrayElementMutation(const Expr *Exp) { + // Check whether any element of an array is mutated. + const auto SubscriptExprs = match( + findAll(arraySubscriptExpr(hasBase(ignoringImpCasts(equalsNode(Exp)))) + .bind(NodeID::value)), + Stm, Context); + return findExprMutation(SubscriptExprs); +} + +const Stmt *ExprMutationAnalyzer::findCastMutation(const Expr *Exp) { + // If 'Exp' is casted to any non-const reference type, check the castExpr. + const auto Casts = + match(findAll(castExpr(hasSourceExpression(equalsNode(Exp)), + anyOf(explicitCastExpr(hasDestinationType( + nonConstReferenceType())), + implicitCastExpr(hasImplicitDestinationType( + nonConstReferenceType())))) + .bind(NodeID::value)), + Stm, Context); + if (const Stmt *S = findExprMutation(Casts)) + return S; + // Treat std::{move,forward} as cast. + const auto Calls = + match(findAll(callExpr(callee(namedDecl( + hasAnyName("::std::move", "::std::forward"))), + hasArgument(0, equalsNode(Exp))) + .bind("expr")), + Stm, Context); + return findExprMutation(Calls); +} + +const Stmt *ExprMutationAnalyzer::findRangeLoopMutation(const Expr *Exp) { + // If range for looping over 'Exp' with a non-const reference loop variable, + // check all declRefExpr of the loop variable. + const auto LoopVars = + match(findAll(cxxForRangeStmt( + hasLoopVariable(varDecl(hasType(nonConstReferenceType())) + .bind(NodeID::value)), + hasRangeInit(equalsNode(Exp)))), + Stm, Context); + return findDeclMutation(LoopVars); +} + +const Stmt *ExprMutationAnalyzer::findReferenceMutation(const Expr *Exp) { + // Follow non-const reference returned by `operator*()` of move-only classes. + // These are typically smart pointers with unique ownership so we treat + // mutation of pointee as mutation of the smart pointer itself. + const auto Ref = + match(findAll(cxxOperatorCallExpr( + hasOverloadedOperatorName("*"), + callee(cxxMethodDecl(ofClass(isMoveOnly()), + returns(nonConstReferenceType()))), + argumentCountIs(1), hasArgument(0, equalsNode(Exp))) + .bind(NodeID::value)), + Stm, Context); + if (const Stmt *S = findExprMutation(Ref)) + return S; + + // If 'Exp' is bound to a non-const reference, check all declRefExpr to that. + const auto Refs = match( + stmt(forEachDescendant( + varDecl( + hasType(nonConstReferenceType()), + hasInitializer(anyOf(equalsNode(Exp), + conditionalOperator(anyOf( + hasTrueExpression(equalsNode(Exp)), + hasFalseExpression(equalsNode(Exp)))))), + hasParent(declStmt().bind("stmt")), + // Don't follow the reference in range statement, we've handled + // that separately. + unless(hasParent(declStmt(hasParent( + cxxForRangeStmt(hasRangeStmt(equalsBoundNode("stmt")))))))) + .bind(NodeID::value))), + Stm, Context); + return findDeclMutation(Refs); +} + +const Stmt *ExprMutationAnalyzer::findFunctionArgMutation(const Expr *Exp) { + const auto NonConstRefParam = forEachArgumentWithParam( + equalsNode(Exp), + parmVarDecl(hasType(nonConstReferenceType())).bind("parm")); + const auto IsInstantiated = hasDeclaration(isInstantiated()); + const auto FuncDecl = hasDeclaration(functionDecl().bind("func")); + const auto Matches = match( + findAll(expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl, + unless(callee(namedDecl(hasAnyName( + "::std::move", "::std::forward"))))), + cxxConstructExpr(NonConstRefParam, IsInstantiated, + FuncDecl))) + .bind(NodeID::value)), + Stm, Context); + for (const auto &Nodes : Matches) { + const auto *Exp = Nodes.getNodeAs(NodeID::value); + const auto *Func = Nodes.getNodeAs("func"); + if (!Func->getBody() || !Func->getPrimaryTemplate()) + return Exp; + + const auto *Parm = Nodes.getNodeAs("parm"); + const ArrayRef AllParams = + Func->getPrimaryTemplate()->getTemplatedDecl()->parameters(); + QualType ParmType = + AllParams[std::min(Parm->getFunctionScopeIndex(), + AllParams.size() - 1)] + ->getType(); + if (const auto *T = ParmType->getAs()) + ParmType = T->getPattern(); + + // If param type is forwarding reference, follow into the function + // definition and see whether the param is mutated inside. + if (const auto *RefType = ParmType->getAs()) { + if (!RefType->getPointeeType().getQualifiers() && + RefType->getPointeeType()->getAs()) { + std::unique_ptr &Analyzer = + FuncParmAnalyzer[Func]; + if (!Analyzer) + Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context)); + if (Analyzer->findMutation(Parm)) + return Exp; + continue; + } + } + // Not forwarding reference. + return Exp; + } + return nullptr; +} + +FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer( + const FunctionDecl &Func, ASTContext &Context) + : BodyAnalyzer(*Func.getBody(), Context) { + if (const auto *Ctor = dyn_cast(&Func)) { + // CXXCtorInitializer might also mutate Param but they're not part of + // function body, check them eagerly here since they're typically trivial. + for (const CXXCtorInitializer *Init : Ctor->inits()) { + ExprMutationAnalyzer InitAnalyzer(*Init->getInit(), Context); + for (const ParmVarDecl *Parm : Ctor->parameters()) { + if (Results.find(Parm) != Results.end()) + continue; + if (const Stmt *S = InitAnalyzer.findMutation(Parm)) + Results[Parm] = S; + } + } + } +} + +const Stmt * +FunctionParmMutationAnalyzer::findMutation(const ParmVarDecl *Parm) { + const auto Memoized = Results.find(Parm); + if (Memoized != Results.end()) + return Memoized->second; + + if (const Stmt *S = BodyAnalyzer.findMutation(Parm)) + return Results[Parm] = S; + + return Results[Parm] = nullptr; +} + +} // namespace tooling +} // namespace clang Index: lib/Tooling/CMakeLists.txt =================================================================== --- lib/Tooling/CMakeLists.txt +++ lib/Tooling/CMakeLists.txt @@ -7,6 +7,7 @@ add_subdirectory(Inclusions) add_subdirectory(Refactoring) add_subdirectory(ASTDiff) +add_subdirectory(Analysis) add_clang_library(clangTooling AllTUsExecution.cpp Index: unittests/Tooling/CMakeLists.txt =================================================================== --- unittests/Tooling/CMakeLists.txt +++ unittests/Tooling/CMakeLists.txt @@ -17,6 +17,7 @@ CompilationDatabaseTest.cpp DiagnosticsYamlTest.cpp ExecutionTest.cpp + ExprMutationAnalyzerTest.cpp FixItTest.cpp HeaderIncludesTest.cpp LexicallyOrderedRecursiveASTVisitorTest.cpp @@ -61,6 +62,7 @@ clangLex clangRewrite clangTooling + clangToolingAnalysis clangToolingCore clangToolingInclusions clangToolingRefactor Index: unittests/Tooling/ExprMutationAnalyzerTest.cpp =================================================================== --- /dev/null +++ unittests/Tooling/ExprMutationAnalyzerTest.cpp @@ -0,0 +1,1107 @@ +//===---------- ExprMutationAnalyzerTest.cpp ------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Tooling/Analysis/ExprMutationAnalyzer.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Tooling/Tooling.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include + +namespace clang { +namespace { + +using namespace ::clang::ast_matchers; +using ::testing::ElementsAre; +using ::testing::IsEmpty; +using ::testing::ResultOf; +using ::testing::StartsWith; +using ::testing::Values; + +using ExprMatcher = internal::Matcher; +using StmtMatcher = internal::Matcher; + +std::unique_ptr +buildASTFromCodeWithArgs(const Twine &Code, + const std::vector &Args) { + auto AST = tooling::buildASTFromCodeWithArgs(Code, Args); + EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); + return AST; +} + +std::unique_ptr buildASTFromCode(const Twine &Code) { + return buildASTFromCodeWithArgs(Code, {}); +} + +ExprMatcher declRefTo(StringRef Name) { + return declRefExpr(to(namedDecl(hasName(Name)))); +} + +StmtMatcher withEnclosingCompound(ExprMatcher Matcher) { + return expr(Matcher, hasAncestor(compoundStmt().bind("stmt"))).bind("expr"); +} + +bool isMutated(const SmallVectorImpl &Results, ASTUnit *AST) { + const auto *const S = selectFirst("stmt", Results); + const auto *const E = selectFirst("expr", Results); + return tooling::ExprMutationAnalyzer(*S, AST->getASTContext()).isMutated(E); +} + +SmallVector +mutatedBy(const SmallVectorImpl &Results, ASTUnit *AST) { + const auto *const S = selectFirst("stmt", Results); + SmallVector Chain; + tooling::ExprMutationAnalyzer Analyzer(*S, AST->getASTContext()); + for (const auto *E = selectFirst("expr", Results); E != nullptr;) { + const Stmt *By = Analyzer.findMutation(E); + std::string buffer; + llvm::raw_string_ostream stream(buffer); + By->printPretty(stream, nullptr, AST->getASTContext().getPrintingPolicy()); + Chain.push_back(StringRef(stream.str()).trim().str()); + E = dyn_cast(By); + } + return Chain; +} + +std::string removeSpace(std::string s) { + s.erase(std::remove_if(s.begin(), s.end(), + [](char c) { return std::isspace(c); }), + s.end()); + return s; +} + +const std::string StdRemoveReference = + "namespace std {" + "template struct remove_reference { typedef T type; };" + "template struct remove_reference { typedef T type; };" + "template struct remove_reference { typedef T type; }; }"; + +const std::string StdMove = + "namespace std {" + "template typename remove_reference::type&& " + "move(T&& t) noexcept {" + "return static_cast::type&&>(t); } }"; + +const std::string StdForward = + "namespace std {" + "template T&& " + "forward(typename remove_reference::type& t) noexcept { return t; }" + "template T&& " + "forward(typename remove_reference::type&& t) noexcept { return t; } }"; + +TEST(ExprMutationAnalyzerTest, Trivial) { + const auto AST = buildASTFromCode("void f() { int x; x; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +class AssignmentTest : public ::testing::TestWithParam {}; + +TEST_P(AssignmentTest, AssignmentModifies) { + const std::string ModExpr = "x " + GetParam() + " 10"; + const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr)); +} + +INSTANTIATE_TEST_CASE_P(AllAssignmentOperators, AssignmentTest, + Values("=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", + "^=", "<<=", ">>="), ); + +class IncDecTest : public ::testing::TestWithParam {}; + +TEST_P(IncDecTest, IncDecModifies) { + const std::string ModExpr = GetParam(); + const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr)); +} + +INSTANTIATE_TEST_CASE_P(AllIncDecOperators, IncDecTest, + Values("++x", "--x", "x++", "x--"), ); + +TEST(ExprMutationAnalyzerTest, NonConstMemberFunc) { + const auto AST = buildASTFromCode( + "void f() { struct Foo { void mf(); }; Foo x; x.mf(); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.mf()")); +} + +TEST(ExprMutationAnalyzerTest, AssumedNonConstMemberFunc) { + auto AST = buildASTFromCodeWithArgs( + "struct X { template void mf(); };" + "template void f() { X x; x.mf(); }", + {"-fno-delayed-template-parsing"}); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.mf()")); + + AST = buildASTFromCodeWithArgs("template void f() { T x; x.mf(); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.mf()")); + + AST = buildASTFromCodeWithArgs( + "template struct X;" + "template void f() { X x; x.mf(); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.mf()")); +} + +TEST(ExprMutationAnalyzerTest, ConstMemberFunc) { + const auto AST = buildASTFromCode( + "void f() { struct Foo { void mf() const; }; Foo x; x.mf(); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, NonConstOperator) { + const auto AST = buildASTFromCode( + "void f() { struct Foo { Foo& operator=(int); }; Foo x; x = 10; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x = 10")); +} + +TEST(ExprMutationAnalyzerTest, ConstOperator) { + const auto AST = buildASTFromCode( + "void f() { struct Foo { int operator()() const; }; Foo x; x(); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, ByValueArgument) { + auto AST = buildASTFromCode("void g(int); void f() { int x; g(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void g(int*); void f() { int* x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("typedef int* IntPtr;" + "void g(IntPtr); void f() { int* x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "struct A {}; A operator+(A, int); void f() { A x; x + 1; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { struct A { A(int); }; int x; A y(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("struct A { A(); A& operator=(A); };" + "void f() { A x, y; y = x; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "template struct A { A(); A(const A&); static void mf(A) {} };" + "void f() { A<0> x; A<0>::mf(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, ByConstValueArgument) { + auto AST = buildASTFromCode("void g(const int); void f() { int x; g(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void g(int* const); void f() { int* x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("typedef int* const CIntPtr;" + "void g(CIntPtr); void f() { int* x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "struct A {}; A operator+(const A, int); void f() { A x; x + 1; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "void f() { struct A { A(const int); }; int x; A y(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("template struct A { A(); A(const A&);" + "static void mf(const A&) {} };" + "void f() { A<0> x; A<0>::mf(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, ByNonConstRefArgument) { + auto AST = buildASTFromCode("void g(int&); void f() { int x; g(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode("typedef int& IntRef;" + "void g(IntRef); void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode("template using TRef = T&;" + "void g(TRef); void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode( + "template struct identity { using type = T; };" + "template void g(typename identity::type);" + "void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode("typedef int* IntPtr;" + "void g(IntPtr&); void f() { int* x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode("typedef int* IntPtr; typedef IntPtr& IntPtrRef;" + "void g(IntPtrRef); void f() { int* x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode( + "struct A {}; A operator+(A&, int); void f() { A x; x + 1; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x + 1")); + + AST = buildASTFromCode("void f() { struct A { A(int&); }; int x; A y(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); + + AST = buildASTFromCode("void f() { struct A { A(); A(A&); }; A x; A y(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); + + AST = buildASTFromCode( + "template struct A { A(); A(const A&); static void mf(A&) {} };" + "void f() { A<0> x; A<0>::mf(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("A<0>::mf(x)")); +} + +TEST(ExprMutationAnalyzerTest, ByConstRefArgument) { + auto AST = buildASTFromCode("void g(const int&); void f() { int x; g(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("typedef const int& CIntRef;" + "void g(CIntRef); void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("template using CTRef = const T&;" + "void g(CTRef); void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = + buildASTFromCode("template struct identity { using type = T; };" + "template " + "void g(typename identity::type);" + "void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "struct A {}; A operator+(const A&, int); void f() { A x; x + 1; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "void f() { struct A { A(const int&); }; int x; A y(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "void f() { struct A { A(); A(const A&); }; A x; A y(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, ByNonConstRRefArgument) { + auto AST = buildASTFromCode( + "void g(int&&); void f() { int x; g(static_cast(x)); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("g(static_cast(x))")); + + AST = buildASTFromCode("struct A {}; A operator+(A&&, int);" + "void f() { A x; static_cast(x) + 1; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("static_cast(x) + 1")); + + AST = buildASTFromCode("void f() { struct A { A(int&&); }; " + "int x; A y(static_cast(x)); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("static_cast(x)")); + + AST = buildASTFromCode("void f() { struct A { A(); A(A&&); }; " + "A x; A y(static_cast(x)); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("static_cast(x)")); +} + +TEST(ExprMutationAnalyzerTest, ByConstRRefArgument) { + auto AST = buildASTFromCode( + "void g(const int&&); void f() { int x; g(static_cast(x)); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("struct A {}; A operator+(const A&&, int);" + "void f() { A x; static_cast(x) + 1; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { struct A { A(const int&&); }; " + "int x; A y(static_cast(x)); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { struct A { A(); A(const A&&); }; " + "A x; A y(static_cast(x)); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, Move) { + auto AST = buildASTFromCode(StdRemoveReference + StdMove + + "void f() { struct A {}; A x; std::move(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode(StdRemoveReference + StdMove + + "void f() { struct A {}; A x, y; std::move(x) = y; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("std::move(x) = y")); + + AST = buildASTFromCode(StdRemoveReference + StdMove + + "void f() { int x, y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = + buildASTFromCode(StdRemoveReference + StdMove + + "struct S { S(); S(const S&); S& operator=(const S&); };" + "void f() { S x, y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode(StdRemoveReference + StdMove + + "struct S { S(); S(S&&); S& operator=(S&&); };" + "void f() { S x, y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("y = std::move(x)")); + + AST = buildASTFromCode(StdRemoveReference + StdMove + + "struct S { S(); S(const S&); S(S&&);" + "S& operator=(const S&); S& operator=(S&&); };" + "void f() { S x, y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("y = std::move(x)")); + + AST = buildASTFromCode(StdRemoveReference + StdMove + + "struct S { S(); S(const S&); S(S&&);" + "S& operator=(const S&); S& operator=(S&&); };" + "void f() { const S x; S y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode(StdRemoveReference + StdMove + + "struct S { S(); S& operator=(S); };" + "void f() { S x, y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode(StdRemoveReference + StdMove + + "struct S{}; void f() { S x, y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("y = std::move(x)")); + + AST = buildASTFromCode( + StdRemoveReference + StdMove + + "struct S{}; void f() { const S x; S y; y = std::move(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, Forward) { + auto AST = + buildASTFromCode(StdRemoveReference + StdForward + + "void f() { struct A {}; A x; std::forward(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + StdRemoveReference + StdForward + + "void f() { struct A {}; A x, y; std::forward(x) = y; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("std::forward(x) = y")); +} + +TEST(ExprMutationAnalyzerTest, CallUnresolved) { + auto AST = + buildASTFromCodeWithArgs("template void f() { T x; g(x); }", + {"-fno-delayed-template-parsing"}); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = + buildASTFromCodeWithArgs("template void f() { char x[N]; g(x); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCodeWithArgs( + "template void f(T t) { int x; g(t, x); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(t, x)")); + + AST = buildASTFromCodeWithArgs( + "template void f(T t) { int x; t.mf(x); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("t.mf(x)")); + + AST = buildASTFromCodeWithArgs( + "template struct S;" + "template void f() { S s; int x; s.mf(x); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("s.mf(x)")); + + AST = buildASTFromCodeWithArgs( + "struct S { template void mf(); };" + "template void f(S s) { int x; s.mf(x); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("s.mf(x)")); + + AST = buildASTFromCodeWithArgs("template " + "void g(F f) { int x; f(x); } ", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("f(x)")); + + AST = buildASTFromCodeWithArgs( + "template void f() { int x; (void)T(x); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("T(x)")); +} + +TEST(ExprMutationAnalyzerTest, ReturnAsValue) { + auto AST = buildASTFromCode("int f() { int x; return x; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("int* f() { int* x; return x; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("typedef int* IntPtr;" + "IntPtr f() { int* x; return x; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, ReturnAsNonConstRef) { + const auto AST = buildASTFromCode("int& f() { int x; return x; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("return x;")); +} + +TEST(ExprMutationAnalyzerTest, ReturnAsConstRef) { + const auto AST = buildASTFromCode("const int& f() { int x; return x; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, ReturnAsNonConstRRef) { + const auto AST = + buildASTFromCode("int&& f() { int x; return static_cast(x); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("return static_cast(x);")); +} + +TEST(ExprMutationAnalyzerTest, ReturnAsConstRRef) { + const auto AST = buildASTFromCode( + "const int&& f() { int x; return static_cast(x); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, TakeAddress) { + const auto AST = buildASTFromCode("void g(int*); void f() { int x; g(&x); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("&x")); +} + +TEST(ExprMutationAnalyzerTest, ArrayToPointerDecay) { + const auto AST = + buildASTFromCode("void g(int*); void f() { int x[2]; g(x); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); +} + +TEST(ExprMutationAnalyzerTest, TemplateWithArrayToPointerDecay) { + const auto AST = buildASTFromCodeWithArgs( + "template struct S { static constexpr int v = 8; };" + "template <> struct S { static constexpr int v = 4; };" + "void g(char*);" + "template void f() { char x[S::v]; g(x); }" + "template <> void f() { char y[S::v]; g(y); }", + {"-fno-delayed-template-parsing"}); + const auto ResultsX = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(ResultsX, AST.get()), ElementsAre("g(x)")); + const auto ResultsY = + match(withEnclosingCompound(declRefTo("y")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(ResultsY, AST.get()), ElementsAre("y")); +} + +TEST(ExprMutationAnalyzerTest, FollowRefModified) { + auto AST = buildASTFromCode( + "void f() { int x; int& r0 = x; int& r1 = r0; int& r2 = r1; " + "int& r3 = r2; r3 = 10; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("r0", "r1", "r2", "r3", "r3 = 10")); + + AST = buildASTFromCode("typedef int& IntRefX;" + "using IntRefY = int&;" + "void f() { int x; IntRefX r0 = x; IntRefY r1 = r0;" + "decltype((x)) r2 = r1; r2 = 10; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("r0", "r1", "r2", "r2 = 10")); +} + +TEST(ExprMutationAnalyzerTest, FollowRefNotModified) { + auto AST = buildASTFromCode( + "void f() { int x; int& r0 = x; int& r1 = r0; int& r2 = r1; " + "int& r3 = r2; int& r4 = r3; int& r5 = r4;}"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { int x; int& r0 = x; const int& r1 = r0;}"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("typedef const int& CIntRefX;" + "using CIntRefY = const int&;" + "void f() { int x; int& r0 = x; CIntRefX r1 = r0;" + "CIntRefY r2 = r1; decltype((r1)) r3 = r2;}"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, FollowConditionalRefModified) { + const auto AST = buildASTFromCode( + "void f() { int x, y; bool b; int &r = b ? x : y; r = 10; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("r", "r = 10")); +} + +TEST(ExprMutationAnalyzerTest, FollowConditionalRefNotModified) { + const auto AST = + buildASTFromCode("void f() { int x, y; bool b; int& r = b ? x : y; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, FollowFuncArgModified) { + auto AST = buildASTFromCode("template void g(T&& t) { t = 10; }" + "void f() { int x; g(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode( + "void h(int&);" + "template void g(Args&&... args) { h(args...); }" + "void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); + + AST = buildASTFromCode( + "void h(int&, int);" + "template void g(Args&&... args) { h(args...); }" + "void f() { int x, y; g(x, y); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x, y)")); + Results = match(withEnclosingCompound(declRefTo("y")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "void h(int, int&);" + "template void g(Args&&... args) { h(args...); }" + "void f() { int x, y; g(y, x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(y, x)")); + Results = match(withEnclosingCompound(declRefTo("y")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("struct S { template S(T&& t) { t = 10; } };" + "void f() { int x; S s(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); + + AST = buildASTFromCode( + "struct S { template S(T&& t) : m(++t) { } int m; };" + "void f() { int x; S s(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); + + AST = buildASTFromCode("template struct S {" + "template S(T&& t) : m(++t) { } U m; };" + "void f() { int x; S s(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); + + AST = buildASTFromCode(StdRemoveReference + StdForward + + "template void u(Args&...);" + "template void h(Args&&... args)" + "{ u(std::forward(args)...); }" + "template void g(Args&&... args)" + "{ h(std::forward(args)...); }" + "void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("g(x)")); +} + +TEST(ExprMutationAnalyzerTest, FollowFuncArgNotModified) { + auto AST = buildASTFromCode("template void g(T&&) {}" + "void f() { int x; g(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("template void g(T&& t) { t; }" + "void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("template void g(Args&&...) {}" + "void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("template void g(Args&&...) {}" + "void f() { int y, x; g(y, x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "void h(int, int&);" + "template void g(Args&&... args) { h(args...); }" + "void f() { int x, y; g(x, y); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("struct S { template S(T&& t) { t; } };" + "void f() { int x; S s(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "struct S { template S(T&& t) : m(t) { } int m; };" + "void f() { int x; S s(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("template struct S {" + "template S(T&& t) : m(t) { } U m; };" + "void f() { int x; S s(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode(StdRemoveReference + StdForward + + "template void u(Args...);" + "template void h(Args&&... args)" + "{ u(std::forward(args)...); }" + "template void g(Args&&... args)" + "{ h(std::forward(args)...); }" + "void f() { int x; g(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, ArrayElementModified) { + const auto AST = buildASTFromCode("void f() { int x[2]; x[0] = 10; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x[0] = 10")); +} + +TEST(ExprMutationAnalyzerTest, ArrayElementNotModified) { + const auto AST = buildASTFromCode("void f() { int x[2]; x[0]; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, NestedMemberModified) { + auto AST = + buildASTFromCode("void f() { struct A { int vi; }; struct B { A va; }; " + "struct C { B vb; }; C x; x.vb.va.vi = 10; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.vb.va.vi = 10")); + + AST = buildASTFromCodeWithArgs( + "template void f() { T x; x.y.z = 10; }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.y.z = 10")); + + AST = buildASTFromCodeWithArgs( + "template struct S;" + "template void f() { S x; x.y.z = 10; }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.y.z = 10")); +} + +TEST(ExprMutationAnalyzerTest, NestedMemberNotModified) { + auto AST = + buildASTFromCode("void f() { struct A { int vi; }; struct B { A va; }; " + "struct C { B vb; }; C x; x.vb.va.vi; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCodeWithArgs("template void f() { T x; x.y.z; }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = + buildASTFromCodeWithArgs("template struct S;" + "template void f() { S x; x.y.z; }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, CastToValue) { + const auto AST = + buildASTFromCode("void f() { int x; static_cast(x); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, CastToRefModified) { + auto AST = + buildASTFromCode("void f() { int x; static_cast(x) = 10; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("static_cast(x) = 10")); + + AST = buildASTFromCode("typedef int& IntRef;" + "void f() { int x; static_cast(x) = 10; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre("static_cast(x) = 10")); +} + +TEST(ExprMutationAnalyzerTest, CastToRefNotModified) { + const auto AST = + buildASTFromCode("void f() { int x; static_cast(x); }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, CastToConstRef) { + auto AST = + buildASTFromCode("void f() { int x; static_cast(x); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("typedef const int& CIntRef;" + "void f() { int x; static_cast(x); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, LambdaDefaultCaptureByValue) { + const auto AST = buildASTFromCode("void f() { int x; [=]() { x; }; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, LambdaExplicitCaptureByValue) { + const auto AST = buildASTFromCode("void f() { int x; [x]() { x; }; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, LambdaDefaultCaptureByRef) { + const auto AST = buildASTFromCode("void f() { int x; [&]() { x = 10; }; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre(ResultOf(removeSpace, "[&](){x=10;}"))); +} + +TEST(ExprMutationAnalyzerTest, LambdaExplicitCaptureByRef) { + const auto AST = buildASTFromCode("void f() { int x; [&x]() { x = 10; }; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), + ElementsAre(ResultOf(removeSpace, "[&x](){x=10;}"))); +} + +TEST(ExprMutationAnalyzerTest, RangeForArrayByRefModified) { + auto AST = + buildASTFromCode("void f() { int x[2]; for (int& e : x) e = 10; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("e", "e = 10")); + + AST = buildASTFromCode("typedef int& IntRef;" + "void f() { int x[2]; for (IntRef e : x) e = 10; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("e", "e = 10")); +} + +TEST(ExprMutationAnalyzerTest, RangeForArrayByRefNotModified) { + const auto AST = + buildASTFromCode("void f() { int x[2]; for (int& e : x) e; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, RangeForArrayByValue) { + auto AST = buildASTFromCode("void f() { int x[2]; for (int e : x) e = 10; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = + buildASTFromCode("void f() { int* x[2]; for (int* e : x) e = nullptr; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "typedef int* IntPtr;" + "void f() { int* x[2]; for (IntPtr e : x) e = nullptr; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, RangeForArrayByConstRef) { + auto AST = + buildASTFromCode("void f() { int x[2]; for (const int& e : x) e; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("typedef const int& CIntRef;" + "void f() { int x[2]; for (CIntRef e : x) e; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, RangeForNonArrayByRefModified) { + const auto AST = + buildASTFromCode("struct V { int* begin(); int* end(); };" + "void f() { V x; for (int& e : x) e = 10; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("e", "e = 10")); +} + +TEST(ExprMutationAnalyzerTest, RangeForNonArrayByRefNotModified) { + const auto AST = buildASTFromCode("struct V { int* begin(); int* end(); };" + "void f() { V x; for (int& e : x) e; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, RangeForNonArrayByValue) { + const auto AST = buildASTFromCode( + "struct V { const int* begin() const; const int* end() const; };" + "void f() { V x; for (int e : x) e; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, RangeForNonArrayByConstRef) { + const auto AST = buildASTFromCode( + "struct V { const int* begin() const; const int* end() const; };" + "void f() { V x; for (const int& e : x) e; }"); + const auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, UnevaluatedExpressions) { + auto AST = buildASTFromCode("void f() { int x, y; decltype(x = 10) z = y; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { int x, y; __typeof(x = 10) z = y; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { int x, y; __typeof__(x = 10) z = y; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { int x; sizeof(x = 10); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { int x; alignof(x = 10); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode("void f() { int x; noexcept(x = 10); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCodeWithArgs("namespace std { class type_info; }" + "void f() { int x; typeid(x = 10); }", + {"-frtti"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode( + "void f() { int x; _Generic(x = 10, int: 0, default: 1); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); +} + +TEST(ExprMutationAnalyzerTest, NotUnevaluatedExpressions) { + auto AST = buildASTFromCode("void f() { int x; sizeof(int[x++]); }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x++")); + + AST = buildASTFromCodeWithArgs( + "namespace std { class type_info; }" + "struct A { virtual ~A(); }; struct B : A {};" + "struct X { A& f(); }; void f() { X x; typeid(x.f()); }", + {"-frtti"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.f()")); +} + +TEST(ExprMutationAnalyzerTest, UniquePtr) { + const std::string UniquePtrDef = + "template struct UniquePtr {" + " UniquePtr();" + " UniquePtr(const UniquePtr&) = delete;" + " UniquePtr(UniquePtr&&);" + " UniquePtr& operator=(const UniquePtr&) = delete;" + " UniquePtr& operator=(UniquePtr&&);" + " T& operator*() const;" + " T* operator->() const;" + "};"; + + auto AST = buildASTFromCode(UniquePtrDef + + "void f() { UniquePtr x; *x = 10; }"); + auto Results = + match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("* x = 10")); + + AST = buildASTFromCode(UniquePtrDef + "void f() { UniquePtr x; *x; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode(UniquePtrDef + + "void f() { UniquePtr x; *x; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCode(UniquePtrDef + "struct S { int v; };" + "void f() { UniquePtr x; x->v; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); + + AST = buildASTFromCode(UniquePtrDef + + "struct S { int v; };" + "void f() { UniquePtr x; x->v; }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = + buildASTFromCode(UniquePtrDef + "struct S { void mf(); };" + "void f() { UniquePtr x; x->mf(); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x")); + + AST = buildASTFromCode(UniquePtrDef + + "struct S { void mf() const; };" + "void f() { UniquePtr x; x->mf(); }"); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_FALSE(isMutated(Results, AST.get())); + + AST = buildASTFromCodeWithArgs( + UniquePtrDef + "template void f() { UniquePtr x; x->mf(); }", + {"-fno-delayed-template-parsing"}); + Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext()); + EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x->mf()")); +} + +} // namespace +} // namespace clang