xref: /llvm-project/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp (revision db898d43b08e13f5c1fda92b8341cd1709f5af21)
1 #include "TestingSupport.h"
2 #include "clang/AST/ASTContext.h"
3 #include "clang/AST/Decl.h"
4 #include "clang/AST/Stmt.h"
5 #include "clang/ASTMatchers/ASTMatchFinder.h"
6 #include "clang/ASTMatchers/ASTMatchers.h"
7 #include "clang/Analysis/CFG.h"
8 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
9 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
10 #include "clang/Basic/LLVM.h"
11 #include "clang/Basic/LangOptions.h"
12 #include "clang/Basic/SourceManager.h"
13 #include "clang/Basic/TokenKinds.h"
14 #include "clang/Lex/Lexer.h"
15 #include "clang/Serialization/PCHContainerOperations.h"
16 #include "clang/Tooling/ArgumentsAdjusters.h"
17 #include "clang/Tooling/Tooling.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Testing/Support/Annotations.h"
24 #include <cassert>
25 #include <functional>
26 #include <memory>
27 #include <string>
28 #include <system_error>
29 #include <utility>
30 #include <vector>
31 
32 using namespace clang;
33 using namespace dataflow;
34 using namespace ast_matchers;
35 
36 static bool
37 isAnnotationDirectlyAfterStatement(const Stmt *Stmt, unsigned AnnotationBegin,
38                                    const SourceManager &SourceManager,
39                                    const LangOptions &LangOptions) {
40   auto NextToken =
41       Lexer::findNextToken(Stmt->getEndLoc(), SourceManager, LangOptions);
42 
43   while (NextToken && SourceManager.getFileOffset(NextToken->getLocation()) <
44                           AnnotationBegin) {
45     if (NextToken->isNot(tok::semi))
46       return false;
47 
48     NextToken = Lexer::findNextToken(NextToken->getEndLoc(), SourceManager,
49                                      LangOptions);
50   }
51 
52   return true;
53 }
54 
55 llvm::DenseMap<unsigned, std::string>
56 test::getAnnotationLinesAndContent(const AnalysisOutputs &AO) {
57   llvm::DenseMap<unsigned, std::string> LineNumberToContent;
58   auto Code = AO.Code.code();
59   auto Annotations = AO.Code.ranges();
60   auto &SM = AO.ASTCtx.getSourceManager();
61   for (auto &AnnotationRange : Annotations) {
62     auto LineNumber =
63         SM.getPresumedLineNumber(SM.getLocForStartOfFile(SM.getMainFileID())
64                                      .getLocWithOffset(AnnotationRange.Begin));
65     auto Content = Code.slice(AnnotationRange.Begin, AnnotationRange.End).str();
66     LineNumberToContent[LineNumber] = Content;
67   }
68   return LineNumberToContent;
69 }
70 
71 llvm::Expected<llvm::DenseMap<const Stmt *, std::string>>
72 test::buildStatementToAnnotationMapping(const FunctionDecl *Func,
73                                         llvm::Annotations AnnotatedCode) {
74   llvm::DenseMap<const Stmt *, std::string> Result;
75 
76   auto StmtMatcher =
77       findAll(stmt(unless(anyOf(hasParent(expr()), hasParent(returnStmt()))))
78                   .bind("stmt"));
79 
80   // This map should stay sorted because the binding algorithm relies on the
81   // ordering of statement offsets
82   std::map<unsigned, const Stmt *> Stmts;
83   auto &Context = Func->getASTContext();
84   auto &SourceManager = Context.getSourceManager();
85 
86   for (auto &Match : match(StmtMatcher, *Func->getBody(), Context)) {
87     const auto *S = Match.getNodeAs<Stmt>("stmt");
88     unsigned Offset = SourceManager.getFileOffset(S->getEndLoc());
89     Stmts[Offset] = S;
90   }
91 
92   unsigned I = 0;
93   auto Annotations = AnnotatedCode.ranges();
94   std::reverse(Annotations.begin(), Annotations.end());
95   auto Code = AnnotatedCode.code();
96 
97   for (auto OffsetAndStmt = Stmts.rbegin(); OffsetAndStmt != Stmts.rend();
98        OffsetAndStmt++) {
99     unsigned Offset = OffsetAndStmt->first;
100     const Stmt *Stmt = OffsetAndStmt->second;
101 
102     if (I < Annotations.size() && Annotations[I].Begin >= Offset) {
103       auto Range = Annotations[I];
104 
105       if (!isAnnotationDirectlyAfterStatement(Stmt, Range.Begin, SourceManager,
106                                               Context.getLangOpts())) {
107         return llvm::createStringError(
108             std::make_error_code(std::errc::invalid_argument),
109             "Annotation is not placed after a statement: %s",
110             SourceManager.getLocForStartOfFile(SourceManager.getMainFileID())
111                 .getLocWithOffset(Offset)
112                 .printToString(SourceManager)
113                 .data());
114       }
115 
116       Result[Stmt] = Code.slice(Range.Begin, Range.End).str();
117       I++;
118 
119       if (I < Annotations.size() && Annotations[I].Begin >= Offset) {
120         return llvm::createStringError(
121             std::make_error_code(std::errc::invalid_argument),
122             "Multiple annotations bound to the statement at the location: %s",
123             Stmt->getBeginLoc().printToString(SourceManager).data());
124       }
125     }
126   }
127 
128   if (I < Annotations.size()) {
129     return llvm::createStringError(
130         std::make_error_code(std::errc::invalid_argument),
131         "Not all annotations were bound to statements. Unbound annotation at: "
132         "%s",
133         SourceManager.getLocForStartOfFile(SourceManager.getMainFileID())
134             .getLocWithOffset(Annotations[I].Begin)
135             .printToString(SourceManager)
136             .data());
137   }
138 
139   return Result;
140 }
141 
142 const ValueDecl *test::findValueDecl(ASTContext &ASTCtx, llvm::StringRef Name) {
143   auto TargetNodes = match(valueDecl(hasName(Name)).bind("v"), ASTCtx);
144   assert(TargetNodes.size() == 1 && "Name must be unique");
145   auto *const Result = selectFirst<ValueDecl>("v", TargetNodes);
146   assert(Result != nullptr);
147   return Result;
148 }
149