CodeCompleteTest.cpp 13 KB

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