CodeCompleteTest.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. EXPECT_THAT(collectPreferredTypes(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. Each("int"));
  167. EXPECT_THAT(collectPreferredTypes(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. Each("float"));
  174. // Pointer types.
  175. EXPECT_THAT(collectPreferredTypes(R"cpp(
  176. void test(int *ptr) {
  177. ptr - ^ptr;
  178. ptr = ^ptr;
  179. })cpp"),
  180. Each("int *"));
  181. EXPECT_THAT(collectPreferredTypes(R"cpp(
  182. void test(int *ptr) {
  183. ptr + ^10;
  184. ptr += ^10;
  185. ptr -= ^10;
  186. })cpp"),
  187. Each("long")); // long is normalized 'ptrdiff_t'.
  188. // Comparison operators.
  189. EXPECT_THAT(collectPreferredTypes(R"cpp(
  190. void test(int i) {
  191. i <= ^1; i < ^1; i >= ^1; i > ^1; i == ^1; i != ^1;
  192. }
  193. )cpp"),
  194. Each("int"));
  195. EXPECT_THAT(collectPreferredTypes(R"cpp(
  196. void test(int *ptr) {
  197. ptr <= ^ptr; ptr < ^ptr; ptr >= ^ptr; ptr > ^ptr;
  198. ptr == ^ptr; ptr != ^ptr;
  199. }
  200. )cpp"),
  201. Each("int *"));
  202. // Relational operations.
  203. EXPECT_THAT(collectPreferredTypes(R"cpp(
  204. void test(int i, int *ptr) {
  205. i && ^1; i || ^1;
  206. ptr && ^1; ptr || ^1;
  207. }
  208. )cpp"),
  209. Each("_Bool"));
  210. // Bitwise operations.
  211. EXPECT_THAT(collectPreferredTypes(R"cpp(
  212. void test(long long ll) {
  213. ll | ^1; ll & ^1;
  214. }
  215. )cpp"),
  216. Each("long long"));
  217. EXPECT_THAT(collectPreferredTypes(R"cpp(
  218. enum A {};
  219. void test(A a) {
  220. a | ^1; a & ^1;
  221. }
  222. )cpp"),
  223. Each("enum A"));
  224. EXPECT_THAT(collectPreferredTypes(R"cpp(
  225. enum class A {};
  226. void test(A a) {
  227. // This is technically illegal with the 'enum class' without overloaded
  228. // operators, but we pretend it's fine.
  229. a | ^a; a & ^a;
  230. }
  231. )cpp"),
  232. Each("enum A"));
  233. // Binary shifts.
  234. EXPECT_THAT(collectPreferredTypes(R"cpp(
  235. void test(int i, long long ll) {
  236. i << ^1; ll << ^1;
  237. i <<= ^1; i <<= ^1;
  238. i >> ^1; ll >> ^1;
  239. i >>= ^1; i >>= ^1;
  240. }
  241. )cpp"),
  242. Each("int"));
  243. // Comma does not provide any useful information.
  244. EXPECT_THAT(collectPreferredTypes(R"cpp(
  245. class Cls {};
  246. void test(int i, int* ptr, Cls x) {
  247. (i, ^i);
  248. (ptr, ^ptr);
  249. (x, ^x);
  250. }
  251. )cpp"),
  252. Each("NULL TYPE"));
  253. // User-defined types do not take operator overloading into account.
  254. // However, they provide heuristics for some common cases.
  255. EXPECT_THAT(collectPreferredTypes(R"cpp(
  256. class Cls {};
  257. void test(Cls c) {
  258. // we assume arithmetic and comparions ops take the same type.
  259. c + ^c; c - ^c; c * ^c; c / ^c; c % ^c;
  260. c == ^c; c != ^c; c < ^c; c <= ^c; c > ^c; c >= ^c;
  261. // same for the assignments.
  262. c = ^c; c += ^c; c -= ^c; c *= ^c; c /= ^c; c %= ^c;
  263. }
  264. )cpp"),
  265. Each("class Cls"));
  266. EXPECT_THAT(collectPreferredTypes(R"cpp(
  267. class Cls {};
  268. void test(Cls c) {
  269. // we assume relational ops operate on bools.
  270. c && ^c; c || ^c;
  271. }
  272. )cpp"),
  273. Each("_Bool"));
  274. EXPECT_THAT(collectPreferredTypes(R"cpp(
  275. class Cls {};
  276. void test(Cls c) {
  277. // we make no assumptions about the following operators, since they are
  278. // often overloaded with a non-standard meaning.
  279. c << ^c; c >> ^c; c | ^c; c & ^c;
  280. c <<= ^c; c >>= ^c; c |= ^c; c &= ^c;
  281. }
  282. )cpp"),
  283. Each("NULL TYPE"));
  284. }
  285. } // namespace