CodeCompleteTest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //=== unittests/Sema/CodeCompleteTest.cpp - Code Complete 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. #include "clang/Frontend/CompilerInstance.h"
  9. #include "clang/Frontend/FrontendActions.h"
  10. #include "clang/Lex/Preprocessor.h"
  11. #include "clang/Parse/ParseAST.h"
  12. #include "clang/Sema/Sema.h"
  13. #include "clang/Sema/SemaDiagnostic.h"
  14. #include "clang/Tooling/Tooling.h"
  15. #include "gmock/gmock.h"
  16. #include "gtest/gtest.h"
  17. #include <cstddef>
  18. #include <string>
  19. namespace {
  20. using namespace clang;
  21. using namespace clang::tooling;
  22. using ::testing::Each;
  23. using ::testing::UnorderedElementsAre;
  24. const char TestCCName[] = "test.cc";
  25. struct CompletionContext {
  26. std::vector<std::string> VisitedNamespaces;
  27. std::string PreferredType;
  28. // String representation of std::ptrdiff_t on a given platform. This is a hack
  29. // to properly account for different configurations of clang.
  30. std::string PtrDiffType;
  31. };
  32. class VisitedContextFinder : public CodeCompleteConsumer {
  33. public:
  34. VisitedContextFinder(CompletionContext &ResultCtx)
  35. : CodeCompleteConsumer(/*CodeCompleteOpts=*/{},
  36. /*CodeCompleteConsumer*/ false),
  37. ResultCtx(ResultCtx),
  38. CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
  39. void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
  40. CodeCompletionResult *Results,
  41. unsigned NumResults) override {
  42. ResultCtx.VisitedNamespaces =
  43. getVisitedNamespace(Context.getVisitedContexts());
  44. ResultCtx.PreferredType = Context.getPreferredType().getAsString();
  45. ResultCtx.PtrDiffType =
  46. S.getASTContext().getPointerDiffType().getAsString();
  47. }
  48. CodeCompletionAllocator &getAllocator() override {
  49. return CCTUInfo.getAllocator();
  50. }
  51. CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
  52. private:
  53. std::vector<std::string> getVisitedNamespace(
  54. CodeCompletionContext::VisitedContextSet VisitedContexts) const {
  55. std::vector<std::string> NSNames;
  56. for (const auto *Context : VisitedContexts)
  57. if (const auto *NS = llvm::dyn_cast<NamespaceDecl>(Context))
  58. NSNames.push_back(NS->getQualifiedNameAsString());
  59. return NSNames;
  60. }
  61. CompletionContext &ResultCtx;
  62. CodeCompletionTUInfo CCTUInfo;
  63. };
  64. class CodeCompleteAction : public SyntaxOnlyAction {
  65. public:
  66. CodeCompleteAction(ParsedSourceLocation P, CompletionContext &ResultCtx)
  67. : CompletePosition(std::move(P)), ResultCtx(ResultCtx) {}
  68. bool BeginInvocation(CompilerInstance &CI) override {
  69. CI.getFrontendOpts().CodeCompletionAt = CompletePosition;
  70. CI.setCodeCompletionConsumer(new VisitedContextFinder(ResultCtx));
  71. return true;
  72. }
  73. private:
  74. // 1-based code complete position <Line, Col>;
  75. ParsedSourceLocation CompletePosition;
  76. CompletionContext &ResultCtx;
  77. };
  78. ParsedSourceLocation offsetToPosition(llvm::StringRef Code, size_t Offset) {
  79. Offset = std::min(Code.size(), Offset);
  80. StringRef Before = Code.substr(0, Offset);
  81. int Lines = Before.count('\n');
  82. size_t PrevNL = Before.rfind('\n');
  83. size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
  84. return {TestCCName, static_cast<unsigned>(Lines + 1),
  85. static_cast<unsigned>(Offset - StartOfLine + 1)};
  86. }
  87. CompletionContext runCompletion(StringRef Code, size_t Offset) {
  88. CompletionContext ResultCtx;
  89. auto Action = llvm::make_unique<CodeCompleteAction>(
  90. offsetToPosition(Code, Offset), ResultCtx);
  91. clang::tooling::runToolOnCodeWithArgs(Action.release(), Code, {"-std=c++11"},
  92. TestCCName);
  93. return ResultCtx;
  94. }
  95. struct ParsedAnnotations {
  96. std::vector<size_t> Points;
  97. std::string Code;
  98. };
  99. ParsedAnnotations parseAnnotations(StringRef AnnotatedCode) {
  100. ParsedAnnotations R;
  101. while (!AnnotatedCode.empty()) {
  102. size_t NextPoint = AnnotatedCode.find('^');
  103. if (NextPoint == StringRef::npos) {
  104. R.Code += AnnotatedCode;
  105. AnnotatedCode = "";
  106. break;
  107. }
  108. R.Code += AnnotatedCode.substr(0, NextPoint);
  109. R.Points.push_back(R.Code.size());
  110. AnnotatedCode = AnnotatedCode.substr(NextPoint + 1);
  111. }
  112. return R;
  113. }
  114. CompletionContext runCodeCompleteOnCode(StringRef AnnotatedCode) {
  115. ParsedAnnotations P = parseAnnotations(AnnotatedCode);
  116. assert(P.Points.size() == 1 && "expected exactly one annotation point");
  117. return runCompletion(P.Code, P.Points.front());
  118. }
  119. std::vector<std::string>
  120. collectPreferredTypes(StringRef AnnotatedCode,
  121. std::string *PtrDiffType = nullptr) {
  122. ParsedAnnotations P = parseAnnotations(AnnotatedCode);
  123. std::vector<std::string> Types;
  124. for (size_t Point : P.Points) {
  125. auto Results = runCompletion(P.Code, Point);
  126. if (PtrDiffType) {
  127. assert(PtrDiffType->empty() || *PtrDiffType == Results.PtrDiffType);
  128. *PtrDiffType = Results.PtrDiffType;
  129. }
  130. Types.push_back(Results.PreferredType);
  131. }
  132. return Types;
  133. }
  134. TEST(SemaCodeCompleteTest, VisitedNSForValidQualifiedId) {
  135. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  136. namespace ns1 {}
  137. namespace ns2 {}
  138. namespace ns3 {}
  139. namespace ns3 { namespace nns3 {} }
  140. namespace foo {
  141. using namespace ns1;
  142. namespace ns4 {} // not visited
  143. namespace { using namespace ns2; }
  144. inline namespace bar { using namespace ns3::nns3; }
  145. } // foo
  146. namespace ns { foo::^ }
  147. )cpp")
  148. .VisitedNamespaces;
  149. EXPECT_THAT(VisitedNS, UnorderedElementsAre("foo", "ns1", "ns2", "ns3::nns3",
  150. "foo::(anonymous)"));
  151. }
  152. TEST(SemaCodeCompleteTest, VisitedNSForInvalideQualifiedId) {
  153. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  154. namespace ns { foo::^ }
  155. )cpp")
  156. .VisitedNamespaces;
  157. EXPECT_TRUE(VisitedNS.empty());
  158. }
  159. TEST(SemaCodeCompleteTest, VisitedNSWithoutQualifier) {
  160. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  161. namespace n1 {
  162. namespace n2 {
  163. void f(^) {}
  164. }
  165. }
  166. )cpp")
  167. .VisitedNamespaces;
  168. EXPECT_THAT(VisitedNS, UnorderedElementsAre("n1", "n1::n2"));
  169. }
  170. TEST(PreferredTypeTest, BinaryExpr) {
  171. // Check various operations for arithmetic types.
  172. StringRef Code = R"cpp(
  173. void test(int x) {
  174. x = ^10;
  175. x += ^10; x -= ^10; x *= ^10; x /= ^10; x %= ^10;
  176. x + ^10; x - ^10; x * ^10; x / ^10; x % ^10;
  177. })cpp";
  178. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  179. Code = R"cpp(
  180. void test(float x) {
  181. x = ^10;
  182. x += ^10; x -= ^10; x *= ^10; x /= ^10; x %= ^10;
  183. x + ^10; x - ^10; x * ^10; x / ^10; x % ^10;
  184. })cpp";
  185. EXPECT_THAT(collectPreferredTypes(Code), Each("float"));
  186. // Pointer types.
  187. Code = R"cpp(
  188. void test(int *ptr) {
  189. ptr - ^ptr;
  190. ptr = ^ptr;
  191. })cpp";
  192. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  193. Code = R"cpp(
  194. void test(int *ptr) {
  195. ptr + ^10;
  196. ptr += ^10;
  197. ptr -= ^10;
  198. })cpp";
  199. {
  200. std::string PtrDiff;
  201. auto Types = collectPreferredTypes(Code, &PtrDiff);
  202. EXPECT_THAT(Types, Each(PtrDiff));
  203. }
  204. // Comparison operators.
  205. Code = R"cpp(
  206. void test(int i) {
  207. i <= ^1; i < ^1; i >= ^1; i > ^1; i == ^1; i != ^1;
  208. }
  209. )cpp";
  210. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  211. Code = R"cpp(
  212. void test(int *ptr) {
  213. ptr <= ^ptr; ptr < ^ptr; ptr >= ^ptr; ptr > ^ptr;
  214. ptr == ^ptr; ptr != ^ptr;
  215. }
  216. )cpp";
  217. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  218. // Relational operations.
  219. Code = R"cpp(
  220. void test(int i, int *ptr) {
  221. i && ^1; i || ^1;
  222. ptr && ^1; ptr || ^1;
  223. }
  224. )cpp";
  225. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  226. // Bitwise operations.
  227. Code = R"cpp(
  228. void test(long long ll) {
  229. ll | ^1; ll & ^1;
  230. }
  231. )cpp";
  232. EXPECT_THAT(collectPreferredTypes(Code), Each("long long"));
  233. Code = R"cpp(
  234. enum A {};
  235. void test(A a) {
  236. a | ^1; a & ^1;
  237. }
  238. )cpp";
  239. EXPECT_THAT(collectPreferredTypes(Code), Each("enum A"));
  240. Code = R"cpp(
  241. enum class A {};
  242. void test(A a) {
  243. // This is technically illegal with the 'enum class' without overloaded
  244. // operators, but we pretend it's fine.
  245. a | ^a; a & ^a;
  246. }
  247. )cpp";
  248. EXPECT_THAT(collectPreferredTypes(Code), Each("enum A"));
  249. // Binary shifts.
  250. Code = R"cpp(
  251. void test(int i, long long ll) {
  252. i << ^1; ll << ^1;
  253. i <<= ^1; i <<= ^1;
  254. i >> ^1; ll >> ^1;
  255. i >>= ^1; i >>= ^1;
  256. }
  257. )cpp";
  258. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  259. // Comma does not provide any useful information.
  260. Code = R"cpp(
  261. class Cls {};
  262. void test(int i, int* ptr, Cls x) {
  263. (i, ^i);
  264. (ptr, ^ptr);
  265. (x, ^x);
  266. }
  267. )cpp";
  268. EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
  269. // User-defined types do not take operator overloading into account.
  270. // However, they provide heuristics for some common cases.
  271. Code = R"cpp(
  272. class Cls {};
  273. void test(Cls c) {
  274. // we assume arithmetic and comparions ops take the same type.
  275. c + ^c; c - ^c; c * ^c; c / ^c; c % ^c;
  276. c == ^c; c != ^c; c < ^c; c <= ^c; c > ^c; c >= ^c;
  277. // same for the assignments.
  278. c = ^c; c += ^c; c -= ^c; c *= ^c; c /= ^c; c %= ^c;
  279. }
  280. )cpp";
  281. EXPECT_THAT(collectPreferredTypes(Code), Each("class Cls"));
  282. Code = R"cpp(
  283. class Cls {};
  284. void test(Cls c) {
  285. // we assume relational ops operate on bools.
  286. c && ^c; c || ^c;
  287. }
  288. )cpp";
  289. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  290. Code = R"cpp(
  291. class Cls {};
  292. void test(Cls c) {
  293. // we make no assumptions about the following operators, since they are
  294. // often overloaded with a non-standard meaning.
  295. c << ^c; c >> ^c; c | ^c; c & ^c;
  296. c <<= ^c; c >>= ^c; c |= ^c; c &= ^c;
  297. }
  298. )cpp";
  299. EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
  300. }
  301. TEST(PreferredTypeTest, Members) {
  302. StringRef Code = R"cpp(
  303. struct vector {
  304. int *begin();
  305. vector clone();
  306. };
  307. void test(int *a) {
  308. a = ^vector().^clone().^begin();
  309. }
  310. )cpp";
  311. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  312. }
  313. TEST(PreferredTypeTest, Conditions) {
  314. StringRef Code = R"cpp(
  315. struct vector {
  316. bool empty();
  317. };
  318. void test() {
  319. if (^vector().^empty()) {}
  320. while (^vector().^empty()) {}
  321. for (; ^vector().^empty();) {}
  322. }
  323. )cpp";
  324. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  325. }
  326. TEST(PreferredTypeTest, InitAndAssignment) {
  327. StringRef Code = R"cpp(
  328. struct vector {
  329. int* begin();
  330. };
  331. void test() {
  332. const int* x = ^vector().^begin();
  333. x = ^vector().^begin();
  334. if (const int* y = ^vector().^begin()) {}
  335. }
  336. )cpp";
  337. EXPECT_THAT(collectPreferredTypes(Code), Each("const int *"));
  338. }
  339. TEST(PreferredTypeTest, UnaryExprs) {
  340. StringRef Code = R"cpp(
  341. void test(long long a) {
  342. a = +^a;
  343. a = -^a
  344. a = ++^a;
  345. a = --^a;
  346. }
  347. )cpp";
  348. EXPECT_THAT(collectPreferredTypes(Code), Each("long long"));
  349. Code = R"cpp(
  350. void test(int a, int *ptr) {
  351. !^a;
  352. !^ptr;
  353. !!!^a;
  354. a = !^a;
  355. a = !^ptr;
  356. a = !!!^a;
  357. }
  358. )cpp";
  359. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  360. Code = R"cpp(
  361. void test(int a) {
  362. const int* x = &^a;
  363. }
  364. )cpp";
  365. EXPECT_THAT(collectPreferredTypes(Code), Each("const int"));
  366. Code = R"cpp(
  367. void test(int *a) {
  368. int x = *^a;
  369. int &r = *^a;
  370. }
  371. )cpp";
  372. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  373. Code = R"cpp(
  374. void test(int a) {
  375. *^a;
  376. &^a;
  377. }
  378. )cpp";
  379. }
  380. TEST(PreferredTypeTest, ParenExpr) {
  381. StringRef Code = R"cpp(
  382. const int *i = ^(^(^(^10)));
  383. )cpp";
  384. EXPECT_THAT(collectPreferredTypes(Code), Each("const int *"));
  385. }
  386. } // namespace