1 //===- unittests/AST/NamedDeclPrinterTest.cpp --- NamedDecl printer tests -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains tests for NamedDecl::printQualifiedName().
10 //
11 // These tests have a coding convention:
12 // * declaration to be printed is named 'A' unless it should have some special
13 // name (e.g., 'operator+');
14 // * additional helper declarations are 'Z', 'Y', 'X' and so on.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "clang/AST/ASTContext.h"
19 #include "clang/ASTMatchers/ASTMatchFinder.h"
20 #include "clang/Tooling/Tooling.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "gtest/gtest.h"
23 
24 using namespace clang;
25 using namespace ast_matchers;
26 using namespace tooling;
27 
28 namespace {
29 
30 class PrintMatch : public MatchFinder::MatchCallback {
31   SmallString<1024> Printed;
32   unsigned NumFoundDecls;
33   bool SuppressUnwrittenScope;
34 
35 public:
36   explicit PrintMatch(bool suppressUnwrittenScope)
37     : NumFoundDecls(0), SuppressUnwrittenScope(suppressUnwrittenScope) {}
38 
39   void run(const MatchFinder::MatchResult &Result) override {
40     const NamedDecl *ND = Result.Nodes.getNodeAs<NamedDecl>("id");
41     if (!ND)
42       return;
43     NumFoundDecls++;
44     if (NumFoundDecls > 1)
45       return;
46 
47     llvm::raw_svector_ostream Out(Printed);
48     PrintingPolicy Policy = Result.Context->getPrintingPolicy();
49     Policy.SuppressUnwrittenScope = SuppressUnwrittenScope;
50     ND->printQualifiedName(Out, Policy);
51   }
52 
53   StringRef getPrinted() const {
54     return Printed;
55   }
56 
57   unsigned getNumFoundDecls() const {
58     return NumFoundDecls;
59   }
60 };
61 
62 ::testing::AssertionResult
63 PrintedNamedDeclMatches(StringRef Code, const std::vector<std::string> &Args,
64                         bool SuppressUnwrittenScope,
65                         const DeclarationMatcher &NodeMatch,
66                         StringRef ExpectedPrinted, StringRef FileName) {
67   PrintMatch Printer(SuppressUnwrittenScope);
68   MatchFinder Finder;
69   Finder.addMatcher(NodeMatch, &Printer);
70   std::unique_ptr<FrontendActionFactory> Factory =
71       newFrontendActionFactory(&Finder);
72 
73   if (!runToolOnCodeWithArgs(Factory->create(), Code, Args, FileName))
74     return testing::AssertionFailure()
75         << "Parsing error in \"" << Code.str() << "\"";
76 
77   if (Printer.getNumFoundDecls() == 0)
78     return testing::AssertionFailure()
79         << "Matcher didn't find any named declarations";
80 
81   if (Printer.getNumFoundDecls() > 1)
82     return testing::AssertionFailure()
83         << "Matcher should match only one named declaration "
84            "(found " << Printer.getNumFoundDecls() << ")";
85 
86   if (Printer.getPrinted() != ExpectedPrinted)
87     return ::testing::AssertionFailure()
88         << "Expected \"" << ExpectedPrinted.str() << "\", "
89            "got \"" << Printer.getPrinted().str() << "\"";
90 
91   return ::testing::AssertionSuccess();
92 }
93 
94 ::testing::AssertionResult
95 PrintedNamedDeclCXX98Matches(StringRef Code, StringRef DeclName,
96                              StringRef ExpectedPrinted) {
97   std::vector<std::string> Args(1, "-std=c++98");
98   return PrintedNamedDeclMatches(Code,
99                                  Args,
100                                  /*SuppressUnwrittenScope*/ false,
101                                  namedDecl(hasName(DeclName)).bind("id"),
102                                  ExpectedPrinted,
103                                  "input.cc");
104 }
105 
106 ::testing::AssertionResult
107 PrintedWrittenNamedDeclCXX11Matches(StringRef Code, StringRef DeclName,
108                                     StringRef ExpectedPrinted) {
109   std::vector<std::string> Args(1, "-std=c++11");
110   return PrintedNamedDeclMatches(Code,
111                                  Args,
112                                  /*SuppressUnwrittenScope*/ true,
113                                  namedDecl(hasName(DeclName)).bind("id"),
114                                  ExpectedPrinted,
115                                  "input.cc");
116 }
117 
118 ::testing::AssertionResult
119 PrintedWrittenPropertyDeclObjCMatches(StringRef Code, StringRef DeclName,
120                                    StringRef ExpectedPrinted) {
121   std::vector<std::string> Args{"-std=c++11", "-xobjective-c++"};
122   return PrintedNamedDeclMatches(Code,
123                                  Args,
124                                  /*SuppressUnwrittenScope*/ true,
125                                  objcPropertyDecl(hasName(DeclName)).bind("id"),
126                                  ExpectedPrinted,
127                                  "input.m");
128 }
129 
130 } // unnamed namespace
131 
132 TEST(NamedDeclPrinter, TestNamespace1) {
133   ASSERT_TRUE(PrintedNamedDeclCXX98Matches(
134     "namespace { int A; }",
135     "A",
136     "(anonymous namespace)::A"));
137 }
138 
139 TEST(NamedDeclPrinter, TestNamespace2) {
140   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
141     "inline namespace Z { namespace { int A; } }",
142     "A",
143     "A"));
144 }
145 
146 TEST(NamedDeclPrinter, TestUnscopedUnnamedEnum) {
147   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
148     "enum { A };",
149     "A",
150     "A"));
151 }
152 
153 TEST(NamedDeclPrinter, TestNamedEnum) {
154   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
155     "enum X { A };",
156     "A",
157     "A"));
158 }
159 
160 TEST(NamedDeclPrinter, TestScopedNamedEnum) {
161   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
162     "enum class X { A };",
163     "A",
164     "X::A"));
165 }
166 
167 TEST(NamedDeclPrinter, TestClassWithUnscopedUnnamedEnum) {
168   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
169     "class X { enum { A }; };",
170     "A",
171     "X::A"));
172 }
173 
174 TEST(NamedDeclPrinter, TestClassWithUnscopedNamedEnum) {
175   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
176     "class X { enum Y { A }; };",
177     "A",
178     "X::A"));
179 }
180 
181 TEST(NamedDeclPrinter, TestClassWithScopedNamedEnum) {
182   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
183     "class X { enum class Y { A }; };",
184     "A",
185     "X::Y::A"));
186 }
187 
188 TEST(NamedDeclPrinter, TestLinkageInNamespace) {
189   ASSERT_TRUE(PrintedWrittenNamedDeclCXX11Matches(
190     "namespace X { extern \"C\" { int A; } }",
191     "A",
192     "X::A"));
193 }
194 
195 TEST(NamedDeclPrinter, TestObjCClassExtension) {
196   const char *Code =
197 R"(
198   @interface Obj
199   @end
200 
201   @interface Obj ()
202   @property(nonatomic) int property;
203   @end
204 )";
205   ASSERT_TRUE(PrintedWrittenPropertyDeclObjCMatches(
206     Code,
207     "property",
208     "Obj::property"));
209 }
210 
211 TEST(NamedDeclPrinter, TestObjCClassExtensionWithGetter) {
212   const char *Code =
213 R"(
214   @interface Obj
215   @end
216 
217   @interface Obj ()
218   @property(nonatomic, getter=myPropertyGetter) int property;
219   @end
220 )";
221   ASSERT_TRUE(PrintedWrittenPropertyDeclObjCMatches(
222     Code,
223     "property",
224     "Obj::property"));
225 }
226