CodeCompleteTest.cpp 9.5 KB

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