CodeCompleteTest.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. //=== unittests/Sema/CodeCompleteTest.cpp - Code Complete tests ==============//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/Frontend/CompilerInstance.h"
  10. #include "clang/Frontend/FrontendActions.h"
  11. #include "clang/Lex/Preprocessor.h"
  12. #include "clang/Parse/ParseAST.h"
  13. #include "clang/Sema/Sema.h"
  14. #include "clang/Sema/SemaDiagnostic.h"
  15. #include "clang/Tooling/Tooling.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=*/{},
  37. /*CodeCompleteConsumer*/ false),
  38. ResultCtx(ResultCtx),
  39. CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
  40. void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
  41. CodeCompletionResult *Results,
  42. unsigned NumResults) override {
  43. ResultCtx.VisitedNamespaces =
  44. getVisitedNamespace(Context.getVisitedContexts());
  45. ResultCtx.PreferredType = Context.getPreferredType().getAsString();
  46. ResultCtx.PtrDiffType =
  47. S.getASTContext().getPointerDiffType().getAsString();
  48. }
  49. CodeCompletionAllocator &getAllocator() override {
  50. return CCTUInfo.getAllocator();
  51. }
  52. CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
  53. private:
  54. std::vector<std::string> getVisitedNamespace(
  55. CodeCompletionContext::VisitedContextSet VisitedContexts) const {
  56. std::vector<std::string> NSNames;
  57. for (const auto *Context : VisitedContexts)
  58. if (const auto *NS = llvm::dyn_cast<NamespaceDecl>(Context))
  59. NSNames.push_back(NS->getQualifiedNameAsString());
  60. return NSNames;
  61. }
  62. CompletionContext &ResultCtx;
  63. CodeCompletionTUInfo CCTUInfo;
  64. };
  65. class CodeCompleteAction : public SyntaxOnlyAction {
  66. public:
  67. CodeCompleteAction(ParsedSourceLocation P, CompletionContext &ResultCtx)
  68. : CompletePosition(std::move(P)), ResultCtx(ResultCtx) {}
  69. bool BeginInvocation(CompilerInstance &CI) override {
  70. CI.getFrontendOpts().CodeCompletionAt = CompletePosition;
  71. CI.setCodeCompletionConsumer(new VisitedContextFinder(ResultCtx));
  72. return true;
  73. }
  74. private:
  75. // 1-based code complete position <Line, Col>;
  76. ParsedSourceLocation CompletePosition;
  77. CompletionContext &ResultCtx;
  78. };
  79. ParsedSourceLocation offsetToPosition(llvm::StringRef Code, size_t Offset) {
  80. Offset = std::min(Code.size(), Offset);
  81. StringRef Before = Code.substr(0, Offset);
  82. int Lines = Before.count('\n');
  83. size_t PrevNL = Before.rfind('\n');
  84. size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
  85. return {TestCCName, static_cast<unsigned>(Lines + 1),
  86. static_cast<unsigned>(Offset - StartOfLine + 1)};
  87. }
  88. CompletionContext runCompletion(StringRef Code, size_t Offset) {
  89. CompletionContext ResultCtx;
  90. auto Action = llvm::make_unique<CodeCompleteAction>(
  91. offsetToPosition(Code, Offset), ResultCtx);
  92. clang::tooling::runToolOnCodeWithArgs(Action.release(), Code, {"-std=c++11"},
  93. TestCCName);
  94. return ResultCtx;
  95. }
  96. struct ParsedAnnotations {
  97. std::vector<size_t> Points;
  98. std::string Code;
  99. };
  100. ParsedAnnotations parseAnnotations(StringRef AnnotatedCode) {
  101. ParsedAnnotations R;
  102. while (!AnnotatedCode.empty()) {
  103. size_t NextPoint = AnnotatedCode.find('^');
  104. if (NextPoint == StringRef::npos) {
  105. R.Code += AnnotatedCode;
  106. AnnotatedCode = "";
  107. break;
  108. }
  109. R.Code += AnnotatedCode.substr(0, NextPoint);
  110. R.Points.push_back(R.Code.size());
  111. AnnotatedCode = AnnotatedCode.substr(NextPoint + 1);
  112. }
  113. return R;
  114. }
  115. CompletionContext runCodeCompleteOnCode(StringRef AnnotatedCode) {
  116. ParsedAnnotations P = parseAnnotations(AnnotatedCode);
  117. assert(P.Points.size() == 1 && "expected exactly one annotation point");
  118. return runCompletion(P.Code, P.Points.front());
  119. }
  120. std::vector<std::string>
  121. collectPreferredTypes(StringRef AnnotatedCode,
  122. std::string *PtrDiffType = nullptr) {
  123. ParsedAnnotations P = parseAnnotations(AnnotatedCode);
  124. std::vector<std::string> Types;
  125. for (size_t Point : P.Points) {
  126. auto Results = runCompletion(P.Code, Point);
  127. if (PtrDiffType) {
  128. assert(PtrDiffType->empty() || *PtrDiffType == Results.PtrDiffType);
  129. *PtrDiffType = Results.PtrDiffType;
  130. }
  131. Types.push_back(Results.PreferredType);
  132. }
  133. return Types;
  134. }
  135. TEST(SemaCodeCompleteTest, VisitedNSForValidQualifiedId) {
  136. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  137. namespace ns1 {}
  138. namespace ns2 {}
  139. namespace ns3 {}
  140. namespace ns3 { namespace nns3 {} }
  141. namespace foo {
  142. using namespace ns1;
  143. namespace ns4 {} // not visited
  144. namespace { using namespace ns2; }
  145. inline namespace bar { using namespace ns3::nns3; }
  146. } // foo
  147. namespace ns { foo::^ }
  148. )cpp")
  149. .VisitedNamespaces;
  150. EXPECT_THAT(VisitedNS, UnorderedElementsAre("foo", "ns1", "ns2", "ns3::nns3",
  151. "foo::(anonymous)"));
  152. }
  153. TEST(SemaCodeCompleteTest, VisitedNSForInvalideQualifiedId) {
  154. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  155. namespace ns { foo::^ }
  156. )cpp")
  157. .VisitedNamespaces;
  158. EXPECT_TRUE(VisitedNS.empty());
  159. }
  160. TEST(SemaCodeCompleteTest, VisitedNSWithoutQualifier) {
  161. auto VisitedNS = runCodeCompleteOnCode(R"cpp(
  162. namespace n1 {
  163. namespace n2 {
  164. void f(^) {}
  165. }
  166. }
  167. )cpp")
  168. .VisitedNamespaces;
  169. EXPECT_THAT(VisitedNS, UnorderedElementsAre("n1", "n1::n2"));
  170. }
  171. TEST(PreferredTypeTest, BinaryExpr) {
  172. // Check various operations for arithmetic types.
  173. StringRef Code = R"cpp(
  174. void test(int x) {
  175. x = ^10;
  176. x += ^10; x -= ^10; x *= ^10; x /= ^10; x %= ^10;
  177. x + ^10; x - ^10; x * ^10; x / ^10; x % ^10;
  178. })cpp";
  179. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  180. Code = R"cpp(
  181. void test(float x) {
  182. x = ^10;
  183. x += ^10; x -= ^10; x *= ^10; x /= ^10; x %= ^10;
  184. x + ^10; x - ^10; x * ^10; x / ^10; x % ^10;
  185. })cpp";
  186. EXPECT_THAT(collectPreferredTypes(Code), Each("float"));
  187. // Pointer types.
  188. Code = R"cpp(
  189. void test(int *ptr) {
  190. ptr - ^ptr;
  191. ptr = ^ptr;
  192. })cpp";
  193. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  194. Code = R"cpp(
  195. void test(int *ptr) {
  196. ptr + ^10;
  197. ptr += ^10;
  198. ptr -= ^10;
  199. })cpp";
  200. {
  201. std::string PtrDiff;
  202. auto Types = collectPreferredTypes(Code, &PtrDiff);
  203. EXPECT_THAT(Types, Each(PtrDiff));
  204. }
  205. // Comparison operators.
  206. Code = R"cpp(
  207. void test(int i) {
  208. i <= ^1; i < ^1; i >= ^1; i > ^1; i == ^1; i != ^1;
  209. }
  210. )cpp";
  211. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  212. Code = R"cpp(
  213. void test(int *ptr) {
  214. ptr <= ^ptr; ptr < ^ptr; ptr >= ^ptr; ptr > ^ptr;
  215. ptr == ^ptr; ptr != ^ptr;
  216. }
  217. )cpp";
  218. EXPECT_THAT(collectPreferredTypes(Code), Each("int *"));
  219. // Relational operations.
  220. Code = R"cpp(
  221. void test(int i, int *ptr) {
  222. i && ^1; i || ^1;
  223. ptr && ^1; ptr || ^1;
  224. }
  225. )cpp";
  226. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  227. // Bitwise operations.
  228. Code = R"cpp(
  229. void test(long long ll) {
  230. ll | ^1; ll & ^1;
  231. }
  232. )cpp";
  233. EXPECT_THAT(collectPreferredTypes(Code), Each("long long"));
  234. Code = R"cpp(
  235. enum A {};
  236. void test(A a) {
  237. a | ^1; a & ^1;
  238. }
  239. )cpp";
  240. EXPECT_THAT(collectPreferredTypes(Code), Each("enum A"));
  241. Code = R"cpp(
  242. enum class A {};
  243. void test(A a) {
  244. // This is technically illegal with the 'enum class' without overloaded
  245. // operators, but we pretend it's fine.
  246. a | ^a; a & ^a;
  247. }
  248. )cpp";
  249. EXPECT_THAT(collectPreferredTypes(Code), Each("enum A"));
  250. // Binary shifts.
  251. Code = R"cpp(
  252. void test(int i, long long ll) {
  253. i << ^1; ll << ^1;
  254. i <<= ^1; i <<= ^1;
  255. i >> ^1; ll >> ^1;
  256. i >>= ^1; i >>= ^1;
  257. }
  258. )cpp";
  259. EXPECT_THAT(collectPreferredTypes(Code), Each("int"));
  260. // Comma does not provide any useful information.
  261. Code = R"cpp(
  262. class Cls {};
  263. void test(int i, int* ptr, Cls x) {
  264. (i, ^i);
  265. (ptr, ^ptr);
  266. (x, ^x);
  267. }
  268. )cpp";
  269. EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
  270. // User-defined types do not take operator overloading into account.
  271. // However, they provide heuristics for some common cases.
  272. Code = R"cpp(
  273. class Cls {};
  274. void test(Cls c) {
  275. // we assume arithmetic and comparions ops take the same type.
  276. c + ^c; c - ^c; c * ^c; c / ^c; c % ^c;
  277. c == ^c; c != ^c; c < ^c; c <= ^c; c > ^c; c >= ^c;
  278. // same for the assignments.
  279. c = ^c; c += ^c; c -= ^c; c *= ^c; c /= ^c; c %= ^c;
  280. }
  281. )cpp";
  282. EXPECT_THAT(collectPreferredTypes(Code), Each("class Cls"));
  283. Code = R"cpp(
  284. class Cls {};
  285. void test(Cls c) {
  286. // we assume relational ops operate on bools.
  287. c && ^c; c || ^c;
  288. }
  289. )cpp";
  290. EXPECT_THAT(collectPreferredTypes(Code), Each("_Bool"));
  291. Code = R"cpp(
  292. class Cls {};
  293. void test(Cls c) {
  294. // we make no assumptions about the following operators, since they are
  295. // often overloaded with a non-standard meaning.
  296. c << ^c; c >> ^c; c | ^c; c & ^c;
  297. c <<= ^c; c >>= ^c; c |= ^c; c &= ^c;
  298. }
  299. )cpp";
  300. EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
  301. }
  302. } // namespace