CodeCompleteTest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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, VisitedNSForInvalidQualifiedId) {
  153. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  154. namespace na {}
  155. namespace ns1 {
  156. using namespace na;
  157. foo::^
  158. }
  159. )cpp")
  160. .VisitedNamespaces;
  161. EXPECT_THAT(VisitedNS, UnorderedElementsAre("ns1", "na"));
  162. }
  163. TEST(SemaCodeCompleteTest, VisitedNSWithoutQualifier) {
  164. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  165. namespace n1 {
  166. namespace n2 {
  167. void f(^) {}
  168. }
  169. }
  170. )cpp")
  171. .VisitedNamespaces;
  172. EXPECT_THAT(VisitedNS, UnorderedElementsAre("n1", "n1::n2"));
  173. }
  174. TEST(PreferredTypeTest, BinaryExpr) {
  175. // Check various operations for arithmetic types.
  176. StringRef Code = R"cpp(
  177. void test(int x) {
  178. x = ^10;
  179. x += ^10; x -= ^10; x *= ^10; x /= ^10; x %= ^10;
  180. x + ^10; x - ^10; x * ^10; x / ^10; x % ^10;
  181. })cpp";
  182. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  183. Code = R"cpp(
  184. void test(float x) {
  185. x = ^10;
  186. x += ^10; x -= ^10; x *= ^10; x /= ^10; x %= ^10;
  187. x + ^10; x - ^10; x * ^10; x / ^10; x % ^10;
  188. })cpp";
  189. EXPECT_THAT(collectPreferredTypes(Code), Each("float"));
  190. // Pointer types.
  191. Code = R"cpp(
  192. void test(int *ptr) {
  193. ptr - ^ptr;
  194. ptr = ^ptr;
  195. })cpp";
  196. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  197. Code = R"cpp(
  198. void test(int *ptr) {
  199. ptr + ^10;
  200. ptr += ^10;
  201. ptr -= ^10;
  202. })cpp";
  203. {
  204. std::string PtrDiff;
  205. auto Types = collectPreferredTypes(Code, &PtrDiff);
  206. EXPECT_THAT(Types, Each(PtrDiff));
  207. }
  208. // Comparison operators.
  209. Code = R"cpp(
  210. void test(int i) {
  211. i <= ^1; i < ^1; i >= ^1; i > ^1; i == ^1; i != ^1;
  212. }
  213. )cpp";
  214. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  215. Code = R"cpp(
  216. void test(int *ptr) {
  217. ptr <= ^ptr; ptr < ^ptr; ptr >= ^ptr; ptr > ^ptr;
  218. ptr == ^ptr; ptr != ^ptr;
  219. }
  220. )cpp";
  221. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  222. // Relational operations.
  223. Code = R"cpp(
  224. void test(int i, int *ptr) {
  225. i && ^1; i || ^1;
  226. ptr && ^1; ptr || ^1;
  227. }
  228. )cpp";
  229. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  230. // Bitwise operations.
  231. Code = R"cpp(
  232. void test(long long ll) {
  233. ll | ^1; ll & ^1;
  234. }
  235. )cpp";
  236. EXPECT_THAT(collectPreferredTypes(Code), Each("long long"));
  237. Code = R"cpp(
  238. enum A {};
  239. void test(A a) {
  240. a | ^1; a & ^1;
  241. }
  242. )cpp";
  243. EXPECT_THAT(collectPreferredTypes(Code), Each("enum A"));
  244. Code = R"cpp(
  245. enum class A {};
  246. void test(A a) {
  247. // This is technically illegal with the 'enum class' without overloaded
  248. // operators, but we pretend it's fine.
  249. a | ^a; a & ^a;
  250. }
  251. )cpp";
  252. EXPECT_THAT(collectPreferredTypes(Code), Each("enum A"));
  253. // Binary shifts.
  254. Code = R"cpp(
  255. void test(int i, long long ll) {
  256. i << ^1; ll << ^1;
  257. i <<= ^1; i <<= ^1;
  258. i >> ^1; ll >> ^1;
  259. i >>= ^1; i >>= ^1;
  260. }
  261. )cpp";
  262. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  263. // Comma does not provide any useful information.
  264. Code = R"cpp(
  265. class Cls {};
  266. void test(int i, int* ptr, Cls x) {
  267. (i, ^i);
  268. (ptr, ^ptr);
  269. (x, ^x);
  270. }
  271. )cpp";
  272. EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
  273. // User-defined types do not take operator overloading into account.
  274. // However, they provide heuristics for some common cases.
  275. Code = R"cpp(
  276. class Cls {};
  277. void test(Cls c) {
  278. // we assume arithmetic and comparions ops take the same type.
  279. c + ^c; c - ^c; c * ^c; c / ^c; c % ^c;
  280. c == ^c; c != ^c; c < ^c; c <= ^c; c > ^c; c >= ^c;
  281. // same for the assignments.
  282. c = ^c; c += ^c; c -= ^c; c *= ^c; c /= ^c; c %= ^c;
  283. }
  284. )cpp";
  285. EXPECT_THAT(collectPreferredTypes(Code), Each("class Cls"));
  286. Code = R"cpp(
  287. class Cls {};
  288. void test(Cls c) {
  289. // we assume relational ops operate on bools.
  290. c && ^c; c || ^c;
  291. }
  292. )cpp";
  293. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  294. Code = R"cpp(
  295. class Cls {};
  296. void test(Cls c) {
  297. // we make no assumptions about the following operators, since they are
  298. // often overloaded with a non-standard meaning.
  299. c << ^c; c >> ^c; c | ^c; c & ^c;
  300. c <<= ^c; c >>= ^c; c |= ^c; c &= ^c;
  301. }
  302. )cpp";
  303. EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
  304. }
  305. TEST(PreferredTypeTest, Members) {
  306. StringRef Code = R"cpp(
  307. struct vector {
  308. int *begin();
  309. vector clone();
  310. };
  311. void test(int *a) {
  312. a = ^vector().^clone().^begin();
  313. }
  314. )cpp";
  315. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  316. }
  317. TEST(PreferredTypeTest, Conditions) {
  318. StringRef Code = R"cpp(
  319. struct vector {
  320. bool empty();
  321. };
  322. void test() {
  323. if (^vector().^empty()) {}
  324. while (^vector().^empty()) {}
  325. for (; ^vector().^empty();) {}
  326. }
  327. )cpp";
  328. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  329. }
  330. TEST(PreferredTypeTest, InitAndAssignment) {
  331. StringRef Code = R"cpp(
  332. struct vector {
  333. int* begin();
  334. };
  335. void test() {
  336. const int* x = ^vector().^begin();
  337. x = ^vector().^begin();
  338. if (const int* y = ^vector().^begin()) {}
  339. }
  340. )cpp";
  341. EXPECT_THAT(collectPreferredTypes(Code), Each("const int *"));
  342. }
  343. TEST(PreferredTypeTest, UnaryExprs) {
  344. StringRef Code = R"cpp(
  345. void test(long long a) {
  346. a = +^a;
  347. a = -^a
  348. a = ++^a;
  349. a = --^a;
  350. }
  351. )cpp";
  352. EXPECT_THAT(collectPreferredTypes(Code), Each("long long"));
  353. Code = R"cpp(
  354. void test(int a, int *ptr) {
  355. !^a;
  356. !^ptr;
  357. !!!^a;
  358. a = !^a;
  359. a = !^ptr;
  360. a = !!!^a;
  361. }
  362. )cpp";
  363. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  364. Code = R"cpp(
  365. void test(int a) {
  366. const int* x = &^a;
  367. }
  368. )cpp";
  369. EXPECT_THAT(collectPreferredTypes(Code), Each("const int"));
  370. Code = R"cpp(
  371. void test(int *a) {
  372. int x = *^a;
  373. int &r = *^a;
  374. }
  375. )cpp";
  376. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  377. Code = R"cpp(
  378. void test(int a) {
  379. *^a;
  380. &^a;
  381. }
  382. )cpp";
  383. }
  384. TEST(PreferredTypeTest, ParenExpr) {
  385. StringRef Code = R"cpp(
  386. const int *i = ^(^(^(^10)));
  387. )cpp";
  388. EXPECT_THAT(collectPreferredTypes(Code), Each("const int *"));
  389. }
  390. TEST(PreferredTypeTest, FunctionArguments) {
  391. StringRef Code = R"cpp(
  392. void foo(const int*);
  393. void bar(const int*);
  394. void bar(const int*, int b);
  395. struct vector {
  396. const int *data();
  397. };
  398. void test() {
  399. foo(^(^(^(^vec^tor^().^da^ta^()))));
  400. bar(^(^(^(^vec^tor^().^da^ta^()))));
  401. }
  402. )cpp";
  403. EXPECT_THAT(collectPreferredTypes(Code), Each("const int *"));
  404. Code = R"cpp(
  405. void bar(int, volatile double *);
  406. void bar(int, volatile double *, int, int);
  407. struct vector {
  408. double *data();
  409. };
  410. struct class_members {
  411. void bar(int, volatile double *);
  412. void bar(int, volatile double *, int, int);
  413. };
  414. void test() {
  415. bar(10, ^(^(^(^vec^tor^().^da^ta^()))));
  416. class_members().bar(10, ^(^(^(^vec^tor^().^da^ta^()))));
  417. }
  418. )cpp";
  419. EXPECT_THAT(collectPreferredTypes(Code), Each("volatile double *"));
  420. }
  421. } // namespace