CodeCompleteTest.cpp 13 KB

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