1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
10 | #include "clang/Analysis/CFG.h" |
11 | #include "clang/Tooling/Tooling.h" |
12 | #include "gtest/gtest.h" |
13 | #include <string> |
14 | #include <vector> |
15 | |
16 | namespace clang { |
17 | namespace analysis { |
18 | namespace { |
19 | |
20 | enum BuildResult { |
21 | ToolFailed, |
22 | ToolRan, |
23 | SawFunctionBody, |
24 | BuiltCFG, |
25 | }; |
26 | |
27 | class CFGCallback : public ast_matchers::MatchFinder::MatchCallback { |
28 | public: |
29 | BuildResult TheBuildResult = ToolRan; |
30 | |
31 | void run(const ast_matchers::MatchFinder::MatchResult &Result) override { |
32 | const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func"); |
33 | Stmt *Body = Func->getBody(); |
34 | if (!Body) |
35 | return; |
36 | TheBuildResult = SawFunctionBody; |
37 | CFG::BuildOptions Options; |
38 | Options.AddImplicitDtors = true; |
39 | if (CFG::buildCFG(nullptr, Body, Result.Context, Options)) |
40 | TheBuildResult = BuiltCFG; |
41 | } |
42 | }; |
43 | |
44 | BuildResult BuildCFG(const char *Code) { |
45 | CFGCallback Callback; |
46 | |
47 | ast_matchers::MatchFinder Finder; |
48 | Finder.addMatcher(ast_matchers::functionDecl().bind("func"), &Callback); |
49 | std::unique_ptr<tooling::FrontendActionFactory> Factory( |
50 | tooling::newFrontendActionFactory(&Finder)); |
51 | std::vector<std::string> Args = {"-std=c++11", "-fno-delayed-template-parsing"}; |
52 | if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args)) |
53 | return ToolFailed; |
54 | return Callback.TheBuildResult; |
55 | } |
56 | |
57 | |
58 | |
59 | TEST(CFG, RangeBasedForOverDependentType) { |
60 | const char *Code = "class Foo;\n" |
61 | "template <typename T>\n" |
62 | "void f(const T &Range) {\n" |
63 | " for (const Foo *TheFoo : Range) {\n" |
64 | " }\n" |
65 | "}\n"; |
66 | EXPECT_EQ(SawFunctionBody, BuildCFG(Code)); |
67 | } |
68 | |
69 | |
70 | |
71 | TEST(CFG, DeleteExpressionOnDependentType) { |
72 | const char *Code = "template<class T>\n" |
73 | "void f(T t) {\n" |
74 | " delete t;\n" |
75 | "}\n"; |
76 | EXPECT_EQ(BuiltCFG, BuildCFG(Code)); |
77 | } |
78 | |
79 | |
80 | |
81 | TEST(CFG, VariableOfIncompleteType) { |
82 | const char *Code = "template<class T> void f() {\n" |
83 | " class Undefined;\n" |
84 | " Undefined u;\n" |
85 | "}\n"; |
86 | EXPECT_EQ(BuiltCFG, BuildCFG(Code)); |
87 | } |
88 | |
89 | } |
90 | } |
91 | } |
92 | |