Debian Codegraph @

llvm-project/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

raw
1 //===--- DiagnosticsTests.cpp ------------------------------------*- C++-*-===//
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
9 #include "Annotations.h"
10 #include "Config.h"
11 #include "Diagnostics.h"
12 #include "Feature.h"
13 #include "FeatureModule.h"
14 #include "ParsedAST.h"
15 #include "Protocol.h"
16 #include "TestFS.h"
17 #include "TestIndex.h"
18 #include "TestTU.h"
19 #include "TidyProvider.h"
20 #include "index/MemIndex.h"
21 #include "support/Context.h"
22 #include "support/Path.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/DiagnosticSema.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/ScopedPrinter.h"
27 #include "llvm/Support/TargetSelect.h"
28 #include "gmock/gmock.h"
29 #include "gtest/gtest.h"
30 #include <algorithm>
31 #include <memory>
32
33 namespace clang {
34 namespace clangd {
35 namespace {
36
37 using ::testing::_;
38 using ::testing::AllOf;
39 using ::testing::Contains;
40 using ::testing::Each;
41 using ::testing::ElementsAre;
42 using ::testing::Field;
43 using ::testing::IsEmpty;
44 using ::testing::Pair;
45 using ::testing::SizeIs;
46 using ::testing::UnorderedElementsAre;
47
48 ::testing::Matcher<const Diag &> withFix(::testing::Matcher<Fix> FixMatcher) {
49 return Field(&Diag::Fixes, ElementsAre(FixMatcher));
50 }
51
52 ::testing::Matcher<const Diag &> withFix(::testing::Matcher<Fix> FixMatcher1,
53 ::testing::Matcher<Fix> FixMatcher2) {
54 return Field(&Diag::Fixes, UnorderedElementsAre(FixMatcher1, FixMatcher2));
55 }
56
57 ::testing::Matcher<const Diag &> withID(unsigned ID) {
58 return Field(&Diag::ID, ID);
59 }
60 ::testing::Matcher<const Diag &>
61 withNote(::testing::Matcher<Note> NoteMatcher) {
62 return Field(&Diag::Notes, ElementsAre(NoteMatcher));
63 }
64
65 ::testing::Matcher<const Diag &>
66 withNote(::testing::Matcher<Note> NoteMatcher1,
67 ::testing::Matcher<Note> NoteMatcher2) {
68 return Field(&Diag::Notes, UnorderedElementsAre(NoteMatcher1, NoteMatcher2));
69 }
70
71 ::testing::Matcher<const Diag &>
72 withTag(::testing::Matcher<DiagnosticTag> TagMatcher) {
73 return Field(&Diag::Tags, Contains(TagMatcher));
74 }
75
76 MATCHER_P(hasRange, Range, "") { return arg.Range == Range; }
77
78 MATCHER_P2(Diag, Range, Message,
79 "Diag at " + llvm::to_string(Range) + " = [" + Message + "]") {
80 return arg.Range == Range && arg.Message == Message;
81 }
82
83 MATCHER_P3(Fix, Range, Replacement, Message,
84 "Fix " + llvm::to_string(Range) + " => " +
85 ::testing::PrintToString(Replacement) + " = [" + Message + "]") {
86 return arg.Message == Message && arg.Edits.size() == 1 &&
87 arg.Edits[0].range == Range && arg.Edits[0].newText == Replacement;
88 }
89
90 MATCHER_P(fixMessage, Message, "") { return arg.Message == Message; }
91
92 MATCHER_P(equalToLSPDiag, LSPDiag,
93 "LSP diagnostic " + llvm::to_string(LSPDiag)) {
94 if (toJSON(arg) != toJSON(LSPDiag)) {
95 *result_listener << llvm::formatv("expected:\n{0:2}\ngot\n{1:2}",
96 toJSON(LSPDiag), toJSON(arg))
97 .str();
98 return false;
99 }
100 return true;
101 }
102
103 MATCHER_P(diagSource, S, "") { return arg.Source == S; }
104 MATCHER_P(diagName, N, "") { return arg.Name == N; }
105 MATCHER_P(diagSeverity, S, "") { return arg.Severity == S; }
106
107 MATCHER_P(equalToFix, Fix, "LSP fix " + llvm::to_string(Fix)) {
108 if (arg.Message != Fix.Message)
109 return false;
110 if (arg.Edits.size() != Fix.Edits.size())
111 return false;
112 for (std::size_t I = 0; I < arg.Edits.size(); ++I) {
113 if (arg.Edits[I].range != Fix.Edits[I].range ||
114 arg.Edits[I].newText != Fix.Edits[I].newText)
115 return false;
116 }
117 return true;
118 }
119
120 // Helper function to make tests shorter.
121 Position pos(int Line, int Character) {
122 Position Res;
123 Res.line = Line;
124 Res.character = Character;
125 return Res;
126 }
127
128 // Normally returns the provided diagnostics matcher.
129 // If clang-tidy checks are not linked in, returns a matcher for no diagnostics!
130 // This is intended for tests where the diagnostics come from clang-tidy checks.
131 // We don't #ifdef each individual test as it's intrusive and we want to ensure
132 // that as much of the test is still compiled an run as possible.
133 ::testing::Matcher<std::vector<clangd::Diag>>
134 ifTidyChecks(::testing::Matcher<std::vector<clangd::Diag>> M) {
135 if (!CLANGD_TIDY_CHECKS)
136 return IsEmpty();
137 return M;
138 }
139
140 TEST(DiagnosticsTest, DiagnosticRanges) {
141 // Check we report correct ranges, including various edge-cases.
142 Annotations Test(R"cpp(
143 // error-ok
144 #define ID(X) X
145 namespace test{};
146 void $decl[[foo]]();
147 int main() {
148 struct Container { int* begin(); int* end(); } *container;
149 for (auto i : $insertstar[[]]$range[[container]]) {
150 }
151
152 $typo[[go\
153 o]]();
154 foo()$semicolon[[]]//with comments
155 $unk[[unknown]]();
156 double $type[[bar]] = "foo";
157 struct Foo { int x; }; Foo a;
158 a.$nomember[[y]];
159 test::$nomembernamespace[[test]];
160 $macro[[ID($macroarg[[fod]])]]();
161 }
162 )cpp");
163 auto TU = TestTU::withCode(Test.code());
164 EXPECT_THAT(
165 *TU.build().getDiagnostics(),
166 ElementsAre(
167 // Make sure the whole token is highlighted.
168 AllOf(Diag(Test.range("range"),
169 "invalid range expression of type 'struct Container *'; "
170 "did you mean to dereference it with '*'?"),
171 withFix(Fix(Test.range("insertstar"), "*", "insert '*'"))),
172 // This range spans lines.
173 AllOf(Diag(Test.range("typo"),
174 "use of undeclared identifier 'goo'; did you mean 'foo'?"),
175 diagSource(Diag::Clang), diagName("undeclared_var_use_suggest"),
176 withFix(
177 Fix(Test.range("typo"), "foo", "change 'go\\…' to 'foo'")),
178 // This is a pretty normal range.
179 withNote(Diag(Test.range("decl"), "'foo' declared here"))),
180 // This range is zero-width and insertion. Therefore make sure we are
181 // not expanding it into other tokens. Since we are not going to
182 // replace those.
183 AllOf(Diag(Test.range("semicolon"), "expected ';' after expression"),
184 withFix(Fix(Test.range("semicolon"), ";", "insert ';'"))),
185 // This range isn't provided by clang, we expand to the token.
186 Diag(Test.range("unk"), "use of undeclared identifier 'unknown'"),
187 Diag(Test.range("type"),
188 "cannot initialize a variable of type 'double' with an lvalue "
189 "of type 'const char[4]'"),
190 Diag(Test.range("nomember"), "no member named 'y' in 'Foo'"),
191 Diag(Test.range("nomembernamespace"),
192 "no member named 'test' in namespace 'test'"),
193 AllOf(Diag(Test.range("macro"),
194 "use of undeclared identifier 'fod'; did you mean 'foo'?"),
195 withFix(Fix(Test.range("macroarg"), "foo",
196 "change 'fod' to 'foo'")))));
197 }
198
199 // Verify that the -Wswitch case-not-covered diagnostic range covers the
200 // whole expression. This is important because the "populate-switch" tweak
201 // fires for the full expression range (see tweaks/PopulateSwitchTests.cpp).
202 // The quickfix flow only works end-to-end if the tweak can be triggered on
203 // the diagnostic's range.
204 TEST(DiagnosticsTest, WSwitch) {
205 Annotations Test(R"cpp(
206 enum A { X };
207 struct B { A a; };
208 void foo(B b) {
209 switch ([[b.a]]) {}
210 }
211 )cpp");
212 auto TU = TestTU::withCode(Test.code());
213 TU.ExtraArgs = {"-Wswitch"};
214 EXPECT_THAT(*TU.build().getDiagnostics(),
215 ElementsAre(Diag(Test.range(),
216 "enumeration value 'X' not handled in switch")));
217 }
218
219 TEST(DiagnosticsTest, FlagsMatter) {
220 Annotations Test("[[void]] main() {} // error-ok");
221 auto TU = TestTU::withCode(Test.code());
222 EXPECT_THAT(*TU.build().getDiagnostics(),
223 ElementsAre(AllOf(Diag(Test.range(), "'main' must return 'int'"),
224 withFix(Fix(Test.range(), "int",
225 "change 'void' to 'int'")))));
226 // Same code built as C gets different diagnostics.
227 TU.Filename = "Plain.c";
228 EXPECT_THAT(
229 *TU.build().getDiagnostics(),
230 ElementsAre(AllOf(
231 Diag(Test.range(), "return type of 'main' is not 'int'"),
232 withFix(Fix(Test.range(), "int", "change return type to 'int'")))));
233 }
234
235 TEST(DiagnosticsTest, DiagnosticPreamble) {
236 Annotations Test(R"cpp(
237 #include $[["not-found.h"]] // error-ok
238 )cpp");
239
240 auto TU = TestTU::withCode(Test.code());
241 EXPECT_THAT(*TU.build().getDiagnostics(),
242 ElementsAre(::testing::AllOf(
243 Diag(Test.range(), "'not-found.h' file not found"),
244 diagSource(Diag::Clang), diagName("pp_file_not_found"))));
245 }
246
247 TEST(DiagnosticsTest, DeduplicatedClangTidyDiagnostics) {
248 Annotations Test(R"cpp(
249 float foo = [[0.1f]];
250 )cpp");
251 auto TU = TestTU::withCode(Test.code());
252 // Enable alias clang-tidy checks, these check emits the same diagnostics
253 // (except the check name).
254 TU.ClangTidyProvider = addTidyChecks("readability-uppercase-literal-suffix,"
255 "hicpp-uppercase-literal-suffix");
256 // Verify that we filter out the duplicated diagnostic message.
257 EXPECT_THAT(
258 *TU.build().getDiagnostics(),
259 ifTidyChecks(UnorderedElementsAre(::testing::AllOf(
260 Diag(Test.range(),
261 "floating point literal has suffix 'f', which is not uppercase"),
262 diagSource(Diag::ClangTidy)))));
263
264 Test = Annotations(R"cpp(
265 template<typename T>
266 void func(T) {
267 float f = [[0.3f]];
268 }
269 void k() {
270 func(123);
271 func(2.0);
272 }
273 )cpp");
274 TU.Code = std::string(Test.code());
275 // The check doesn't handle template instantiations which ends up emitting
276 // duplicated messages, verify that we deduplicate them.
277 EXPECT_THAT(
278 *TU.build().getDiagnostics(),
279 ifTidyChecks(UnorderedElementsAre(::testing::AllOf(
280 Diag(Test.range(),
281 "floating point literal has suffix 'f', which is not uppercase"),
282 diagSource(Diag::ClangTidy)))));
283 }
284
285 TEST(DiagnosticsTest, ClangTidy) {
286 Annotations Test(R"cpp(
287 #include $deprecated[["assert.h"]]
288
289 #define $macrodef[[SQUARE]](X) (X)*(X)
290 int $main[[main]]() {
291 int y = 4;
292 return SQUARE($macroarg[[++]]y);
293 return $doubled[[sizeof]](sizeof(int));
294 }
295
296 // misc-no-recursion uses a custom traversal from the TUDecl
297 void foo();
298 void $bar[[bar]]() {
299 foo();
300 }
301 void $foo[[foo]]() {
302 bar();
303 }
304 )cpp");
305 auto TU = TestTU::withCode(Test.code());
306 TU.HeaderFilename = "assert.h"; // Suppress "not found" error.
307 TU.ClangTidyProvider = addTidyChecks("bugprone-sizeof-expression,"
308 "bugprone-macro-repeated-side-effects,"
309 "modernize-deprecated-headers,"
310 "modernize-use-trailing-return-type,"
311 "misc-no-recursion");
312 TU.ExtraArgs.push_back("-Wno-unsequenced");
313 EXPECT_THAT(
314 *TU.build().getDiagnostics(),
315 ifTidyChecks(UnorderedElementsAre(
316 AllOf(Diag(Test.range("deprecated"),
317 "inclusion of deprecated C++ header 'assert.h'; consider "
318 "using 'cassert' instead"),
319 diagSource(Diag::ClangTidy),
320 diagName("modernize-deprecated-headers"),
321 withFix(Fix(Test.range("deprecated"), "<cassert>",
322 "change '\"assert.h\"' to '<cassert>'"))),
323 Diag(Test.range("doubled"),
324 "suspicious usage of 'sizeof(sizeof(...))'"),
325 AllOf(Diag(Test.range("macroarg"),
326 "side effects in the 1st macro argument 'X' are "
327 "repeated in "
328 "macro expansion"),
329 diagSource(Diag::ClangTidy),
330 diagName("bugprone-macro-repeated-side-effects"),
331 withNote(Diag(Test.range("macrodef"),
332 "macro 'SQUARE' defined here"))),
333 AllOf(Diag(Test.range("main"),
334 "use a trailing return type for this function"),
335 diagSource(Diag::ClangTidy),
336 diagName("modernize-use-trailing-return-type"),
337 // Verify there's no "[check-name]" suffix in the message.
338 withFix(fixMessage(
339 "use a trailing return type for this function"))),
340 Diag(Test.range("foo"),
341 "function 'foo' is within a recursive call chain"),
342 Diag(Test.range("bar"),
343 "function 'bar' is within a recursive call chain"))));
344 }
345
346 TEST(DiagnosticsTest, ClangTidyEOF) {
347 // clang-format off
348 Annotations Test(R"cpp(
349 [[#]]include <b.h>
350 #include "a.h")cpp");
351 // clang-format on
352 auto TU = TestTU::withCode(Test.code());
353 TU.ExtraArgs = {"-isystem."};
354 TU.AdditionalFiles["a.h"] = TU.AdditionalFiles["b.h"] = "";
355 TU.ClangTidyProvider = addTidyChecks("llvm-include-order");
356 EXPECT_THAT(
357 *TU.build().getDiagnostics(),
358 ifTidyChecks(Contains(
359 AllOf(Diag(Test.range(), "#includes are not sorted properly"),
360 diagSource(Diag::ClangTidy), diagName("llvm-include-order")))));
361 }
362
363 TEST(DiagnosticTest, TemplatesInHeaders) {
364 // Diagnostics from templates defined in headers are placed at the expansion.
365 Annotations Main(R"cpp(
366 Derived<int> [[y]]; // error-ok
367 )cpp");
368 Annotations Header(R"cpp(
369 template <typename T>
370 struct Derived : [[T]] {};
371 )cpp");
372 TestTU TU = TestTU::withCode(Main.code());
373 TU.HeaderCode = Header.code().str();
374 EXPECT_THAT(
375 *TU.build().getDiagnostics(),
376 ElementsAre(AllOf(
377 Diag(Main.range(), "in template: base specifier must name a class"),
378 withNote(Diag(Header.range(), "error occurred here"),
379 Diag(Main.range(), "in instantiation of template class "
380 "'Derived<int>' requested here")))));
381 }
382
383 TEST(DiagnosticTest, MakeUnique) {
384 // We usually miss diagnostics from header functions as we don't parse them.
385 // std::make_unique is an exception.
386 Annotations Main(R"cpp(
387 struct S { S(char*); };
388 auto x = std::[[make_unique]]<S>(42); // error-ok
389 )cpp");
390 TestTU TU = TestTU::withCode(Main.code());
391 TU.HeaderCode = R"cpp(
392 namespace std {
393 // These mocks aren't quite right - we omit unique_ptr for simplicity.
394 // forward is included to show its body is not needed to get the diagnostic.
395 template <typename T> T&& forward(T& t);
396 template <typename T, typename... A> T* make_unique(A&&... args) {
397 return new T(std::forward<A>(args)...);
398 }
399 }
400 )cpp";
401 EXPECT_THAT(*TU.build().getDiagnostics(),
402 UnorderedElementsAre(
403 Diag(Main.range(),
404 "in template: "
405 "no matching constructor for initialization of 'S'")));
406 }
407
408 TEST(DiagnosticTest, MakeShared) {
409 // We usually miss diagnostics from header functions as we don't parse them.
410 // std::make_shared is only parsed when --parse-forwarding-functions is set
411 Annotations Main(R"cpp(
412 struct S { S(char*); };
413 auto x = std::[[make_shared]]<S>(42); // error-ok
414 )cpp");
415 TestTU TU = TestTU::withCode(Main.code());
416 TU.HeaderCode = R"cpp(
417 namespace std {
418 // These mocks aren't quite right - we omit shared_ptr for simplicity.
419 // forward is included to show its body is not needed to get the diagnostic.
420 template <typename T> T&& forward(T& t);
421 template <typename T, typename... A> T* make_shared(A&&... args) {
422 return new T(std::forward<A>(args)...);
423 }
424 }
425 )cpp";
426 TU.ParseOpts.PreambleParseForwardingFunctions = true;
427 EXPECT_THAT(*TU.build().getDiagnostics(),
428 UnorderedElementsAre(
429 Diag(Main.range(),
430 "in template: "
431 "no matching constructor for initialization of 'S'")));
432 }
433
434 TEST(DiagnosticTest, NoMultipleDiagnosticInFlight) {
435 Annotations Main(R"cpp(
436 template <typename T> struct Foo {
437 T *begin();
438 T *end();
439 };
440 struct LabelInfo {
441 int a;
442 bool b;
443 };
444
445 void f() {
446 Foo<LabelInfo> label_info_map;
447 [[for]] (auto it = label_info_map.begin(); it != label_info_map.end(); ++it) {
448 auto S = *it;
449 }
450 }
451 )cpp");
452 TestTU TU = TestTU::withCode(Main.code());
453 TU.ClangTidyProvider = addTidyChecks("modernize-loop-convert");
454 EXPECT_THAT(
455 *TU.build().getDiagnostics(),
456 ifTidyChecks(UnorderedElementsAre(::testing::AllOf(
457 Diag(Main.range(), "use range-based for loop instead"),
458 diagSource(Diag::ClangTidy), diagName("modernize-loop-convert")))));
459 }
460
461 TEST(DiagnosticTest, RespectsDiagnosticConfig) {
462 Annotations Main(R"cpp(
463 // error-ok
464 void x() {
465 [[unknown]]();
466 $ret[[return]] 42;
467 }
468 )cpp");
469 auto TU = TestTU::withCode(Main.code());
470 EXPECT_THAT(
471 *TU.build().getDiagnostics(),
472 ElementsAre(Diag(Main.range(), "use of undeclared identifier 'unknown'"),
473 Diag(Main.range("ret"),
474 "void function 'x' should not return a value")));
475 Config Cfg;
476 Cfg.Diagnostics.Suppress.insert("return-type");
477 WithContextValue WithCfg(Config::Key, std::move(Cfg));
478 EXPECT_THAT(*TU.build().getDiagnostics(),
479 ElementsAre(Diag(Main.range(),
480 "use of undeclared identifier 'unknown'")));
481 }
482
483 TEST(DiagnosticTest, RespectsDiagnosticConfigInHeader) {
484 Annotations Header(R"cpp(
485 int x = "42"; // error-ok
486 )cpp");
487 Annotations Main(R"cpp(
488 #include "header.hpp"
489 )cpp");
490 auto TU = TestTU::withCode(Main.code());
491 TU.AdditionalFiles["header.hpp"] = std::string(Header.code());
492 Config Cfg;
493 Cfg.Diagnostics.Suppress.insert("init_conversion_failed");
494 WithContextValue WithCfg(Config::Key, std::move(Cfg));
495 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
496 }
497
498 TEST(DiagnosticTest, ClangTidySuppressionComment) {
499 Annotations Main(R"cpp(
500 int main() {
501 int i = 3;
502 double d = 8 / i; // NOLINT
503 // NOLINTNEXTLINE
504 double e = 8 / i;
505 #define BAD 8 / i
506 double f = BAD; // NOLINT
507 double g = [[8]] / i;
508 #define BAD2 BAD
509 double h = BAD2; // NOLINT
510 // NOLINTBEGIN
511 double x = BAD2;
512 double y = BAD2;
513 // NOLINTEND
514
515 // verify no crashes on unmatched nolints.
516 // NOLINTBEGIN
517 }
518 )cpp");
519 TestTU TU = TestTU::withCode(Main.code());
520 TU.ClangTidyProvider = addTidyChecks("bugprone-integer-division");
521 EXPECT_THAT(
522 *TU.build().getDiagnostics(),
523 ifTidyChecks(UnorderedElementsAre(::testing::AllOf(
524 Diag(Main.range(), "result of integer division used in a floating "
525 "point context; possible loss of precision"),
526 diagSource(Diag::ClangTidy),
527 diagName("bugprone-integer-division")))));
528 }
529
530 TEST(DiagnosticTest, ClangTidySystemMacro) {
531 Annotations Main(R"cpp(
532 #include "user.h"
533 #include "system.h"
534 int i = 3;
535 double x = $inline[[8]] / i;
536 double y = $user[[DIVIDE_USER]](i);
537 double z = DIVIDE_SYS(i);
538 )cpp");
539
540 auto TU = TestTU::withCode(Main.code());
541 TU.AdditionalFiles["user.h"] = R"cpp(
542 #define DIVIDE_USER(Y) 8/Y
543 )cpp";
544 TU.AdditionalFiles["system.h"] = R"cpp(
545 #pragma clang system_header
546 #define DIVIDE_SYS(Y) 8/Y
547 )cpp";
548
549 TU.ClangTidyProvider = addTidyChecks("bugprone-integer-division");
550 std::string BadDivision = "result of integer division used in a floating "
551 "point context; possible loss of precision";
552
553 // Expect to see warning from user macros, but not system macros.
554 // This matches clang-tidy --system-headers=0 (the default).
555 EXPECT_THAT(*TU.build().getDiagnostics(),
556 ifTidyChecks(
557 UnorderedElementsAre(Diag(Main.range("inline"), BadDivision),
558 Diag(Main.range("user"), BadDivision))));
559 }
560
561 TEST(DiagnosticTest, ClangTidyWarningAsError) {
562 Annotations Main(R"cpp(
563 int main() {
564 int i = 3;
565 double f = [[8]] / i; // error-ok
566 }
567 )cpp");
568 TestTU TU = TestTU::withCode(Main.code());
569 TU.ClangTidyProvider =
570 addTidyChecks("bugprone-integer-division", "bugprone-integer-division");
571 EXPECT_THAT(
572 *TU.build().getDiagnostics(),
573 ifTidyChecks(UnorderedElementsAre(::testing::AllOf(
574 Diag(Main.range(), "result of integer division used in a floating "
575 "point context; possible loss of precision"),
576 diagSource(Diag::ClangTidy), diagName("bugprone-integer-division"),
577 diagSeverity(DiagnosticsEngine::Error)))));
578 }
579
580 TidyProvider addClangArgs(std::vector<llvm::StringRef> ExtraArgs,
581 llvm::StringRef Checks) {
582 return [ExtraArgs = std::move(ExtraArgs), Checks = Checks.str()](
583 tidy::ClangTidyOptions &Opts, llvm::StringRef) {
584 if (!Opts.ExtraArgs)
585 Opts.ExtraArgs.emplace();
586 for (llvm::StringRef Arg : ExtraArgs)
587 Opts.ExtraArgs->emplace_back(Arg);
588 if (!Checks.empty())
589 Opts.Checks = Checks;
590 };
591 }
592
593 TEST(DiagnosticTest, ClangTidyEnablesClangWarning) {
594 Annotations Main(R"cpp( // error-ok
595 static void [[foo]]() {}
596 )cpp");
597 TestTU TU = TestTU::withCode(Main.code());
598 // This is always emitted as a clang warning, not a clang-tidy diagnostic.
599 auto UnusedFooWarning =
600 AllOf(Diag(Main.range(), "unused function 'foo'"),
601 diagName("-Wunused-function"), diagSource(Diag::Clang),
602 diagSeverity(DiagnosticsEngine::Warning));
603
604 // Check the -Wunused warning isn't initially on.
605 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
606
607 // We enable warnings based on clang-tidy extra args, if the matching
608 // clang-diagnostic- is there.
609 TU.ClangTidyProvider =
610 addClangArgs({"-Wunused"}, "clang-diagnostic-unused-function");
611 EXPECT_THAT(*TU.build().getDiagnostics(), ElementsAre(UnusedFooWarning));
612
613 // clang-diagnostic-* is acceptable
614 TU.ClangTidyProvider = addClangArgs({"-Wunused"}, "clang-diagnostic-*");
615 EXPECT_THAT(*TU.build().getDiagnostics(), ElementsAre(UnusedFooWarning));
616 // And plain * (may turn on other checks too).
617 TU.ClangTidyProvider = addClangArgs({"-Wunused"}, "*");
618 EXPECT_THAT(*TU.build().getDiagnostics(), Contains(UnusedFooWarning));
619 // And we can explicitly exclude a category too.
620 TU.ClangTidyProvider = addClangArgs(
621 {"-Wunused"}, "clang-diagnostic-*,-clang-diagnostic-unused-function");
622 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
623
624 // Without the exact check specified, the warnings are not enabled.
625 TU.ClangTidyProvider = addClangArgs({"-Wunused"}, "clang-diagnostic-unused");
626 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
627
628 // We don't respect other args.
629 TU.ClangTidyProvider = addClangArgs({"-Wunused", "-Dfoo=bar"},
630 "clang-diagnostic-unused-function");
631 EXPECT_THAT(*TU.build().getDiagnostics(), ElementsAre(UnusedFooWarning))
632 << "Not unused function 'bar'!";
633
634 // -Werror doesn't apply to warnings enabled by clang-tidy extra args.
635 TU.ExtraArgs = {"-Werror"};
636 TU.ClangTidyProvider =
637 addClangArgs({"-Wunused"}, "clang-diagnostic-unused-function");
638 EXPECT_THAT(*TU.build().getDiagnostics(),
639 ElementsAre(diagSeverity(DiagnosticsEngine::Warning)));
640
641 // But clang-tidy extra args won't *downgrade* errors to warnings either.
642 TU.ExtraArgs = {"-Wunused", "-Werror"};
643 TU.ClangTidyProvider =
644 addClangArgs({"-Wunused"}, "clang-diagnostic-unused-function");
645 EXPECT_THAT(*TU.build().getDiagnostics(),
646 ElementsAre(diagSeverity(DiagnosticsEngine::Error)));
647
648 // FIXME: we're erroneously downgrading the whole group, this should be Error.
649 TU.ExtraArgs = {"-Wunused-function", "-Werror"};
650 TU.ClangTidyProvider =
651 addClangArgs({"-Wunused"}, "clang-diagnostic-unused-label");
652 EXPECT_THAT(*TU.build().getDiagnostics(),
653 ElementsAre(diagSeverity(DiagnosticsEngine::Warning)));
654
655 // This looks silly, but it's the typical result if a warning is enabled by a
656 // high-level .clang-tidy file and disabled by a low-level one.
657 TU.ExtraArgs = {};
658 TU.ClangTidyProvider = addClangArgs({"-Wunused", "-Wno-unused"},
659 "clang-diagnostic-unused-function");
660 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
661
662 // Overriding only works in the proper order.
663 TU.ClangTidyProvider =
664 addClangArgs({"-Wunused"}, {"clang-diagnostic-unused-function"});
665 EXPECT_THAT(*TU.build().getDiagnostics(), SizeIs(1));
666
667 // More specific vs less-specific: match clang behavior
668 TU.ClangTidyProvider = addClangArgs({"-Wunused", "-Wno-unused-function"},
669 {"clang-diagnostic-unused-function"});
670 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
671 TU.ClangTidyProvider = addClangArgs({"-Wunused-function", "-Wno-unused"},
672 {"clang-diagnostic-unused-function"});
673 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
674
675 // We do allow clang-tidy config to disable warnings from the compile
676 // command. It's unclear this is ideal, but it's hard to avoid.
677 TU.ExtraArgs = {"-Wunused"};
678 TU.ClangTidyProvider = addClangArgs({"-Wno-unused"}, {});
679 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
680 }
681
682 TEST(DiagnosticTest, LongFixMessages) {
683 // We limit the size of printed code.
684 Annotations Source(R"cpp(
685 int main() {
686 // error-ok
687 int somereallyreallyreallyreallyreallyreallyreallyreallylongidentifier;
688 [[omereallyreallyreallyreallyreallyreallyreallyreallylongidentifier]]= 10;
689 }
690 )cpp");
691 TestTU TU = TestTU::withCode(Source.code());
692 EXPECT_THAT(
693 *TU.build().getDiagnostics(),
694 ElementsAre(withFix(Fix(
695 Source.range(),
696 "somereallyreallyreallyreallyreallyreallyreallyreallylongidentifier",
697 "change 'omereallyreallyreallyreallyreallyreallyreallyreall…' to "
698 "'somereallyreallyreallyreallyreallyreallyreallyreal…'"))));
699 // Only show changes up to a first newline.
700 Source = Annotations(R"cpp(
701 // error-ok
702 int main() {
703 int ident;
704 [[ide\
705 n]] = 10; // error-ok
706 }
707 )cpp");
708 TU.Code = std::string(Source.code());
709 EXPECT_THAT(*TU.build().getDiagnostics(),
710 ElementsAre(withFix(
711 Fix(Source.range(), "ident", "change 'ide\\…' to 'ident'"))));
712 }
713
714 TEST(DiagnosticTest, NewLineFixMessage) {
715 Annotations Source("int a;[[]]");
716 TestTU TU = TestTU::withCode(Source.code());
717 TU.ExtraArgs = {"-Wnewline-eof"};
718 EXPECT_THAT(
719 *TU.build().getDiagnostics(),
720 ElementsAre(withFix((Fix(Source.range(), "\n", "insert '\\n'")))));
721 }
722
723 TEST(DiagnosticTest, ClangTidySuppressionCommentTrumpsWarningAsError) {
724 Annotations Main(R"cpp(
725 int main() {
726 int i = 3;
727 double f = [[8]] / i; // NOLINT
728 }
729 )cpp");
730 TestTU TU = TestTU::withCode(Main.code());
731 TU.ClangTidyProvider =
732 addTidyChecks("bugprone-integer-division", "bugprone-integer-division");
733 EXPECT_THAT(*TU.build().getDiagnostics(), UnorderedElementsAre());
734 }
735
736 TEST(DiagnosticTest, ClangTidyNoLiteralDataInMacroToken) {
737 Annotations Main(R"cpp(
738 #define SIGTERM 15
739 using pthread_t = int;
740 int pthread_kill(pthread_t thread, int sig);
741 int func() {
742 pthread_t thread;
743 return pthread_kill(thread, 0);
744 }
745 )cpp");
746 TestTU TU = TestTU::withCode(Main.code());
747 TU.ClangTidyProvider = addTidyChecks("bugprone-bad-signal-to-kill-thread");
748 EXPECT_THAT(*TU.build().getDiagnostics(), UnorderedElementsAre()); // no-crash
749 }
750
751 TEST(DiagnosticTest, ElseAfterReturnRange) {
752 Annotations Main(R"cpp(
753 int foo(int cond) {
754 if (cond == 1) {
755 return 42;
756 } [[else]] if (cond == 2) {
757 return 43;
758 }
759 return 44;
760 }
761 )cpp");
762 TestTU TU = TestTU::withCode(Main.code());
763 TU.ClangTidyProvider = addTidyChecks("llvm-else-after-return");
764 EXPECT_THAT(*TU.build().getDiagnostics(),
765 ifTidyChecks(ElementsAre(
766 Diag(Main.range(), "do not use 'else' after 'return'"))));
767 }
768
769 TEST(DiagnosticTest, ClangTidySelfContainedDiags) {
770 Annotations Main(R"cpp($MathHeader[[]]
771 struct Foo{
772 int A, B;
773 Foo()$Fix[[]] {
774 $A[[A = 1;]]
775 $B[[B = 1;]]
776 }
777 };
778 void InitVariables() {
779 float $C[[C]]$CFix[[]];
780 double $D[[D]]$DFix[[]];
781 }
782 )cpp");
783 TestTU TU = TestTU::withCode(Main.code());
784 TU.ClangTidyProvider =
785 addTidyChecks("cppcoreguidelines-prefer-member-initializer,"
786 "cppcoreguidelines-init-variables");
787 clangd::Fix ExpectedAFix;
788 ExpectedAFix.Message =
789 "'A' should be initialized in a member initializer of the constructor";
790 ExpectedAFix.Edits.push_back(TextEdit{Main.range("Fix"), " : A(1)"});
791 ExpectedAFix.Edits.push_back(TextEdit{Main.range("A"), ""});
792
793 // When invoking clang-tidy normally, this code would produce `, B(1)` as the
794 // fix the `B` member, as it would think its already included the ` : ` from
795 // the previous `A` fix.
796 clangd::Fix ExpectedBFix;
797 ExpectedBFix.Message =
798 "'B' should be initialized in a member initializer of the constructor";
799 ExpectedBFix.Edits.push_back(TextEdit{Main.range("Fix"), " : B(1)"});
800 ExpectedBFix.Edits.push_back(TextEdit{Main.range("B"), ""});
801
802 clangd::Fix ExpectedCFix;
803 ExpectedCFix.Message = "variable 'C' is not initialized";
804 ExpectedCFix.Edits.push_back(TextEdit{Main.range("CFix"), " = NAN"});
805 ExpectedCFix.Edits.push_back(
806 TextEdit{Main.range("MathHeader"), "#include <math.h>\n\n"});
807
808 // Again in clang-tidy only the include directive would be emitted for the
809 // first warning. However we need the include attaching for both warnings.
810 clangd::Fix ExpectedDFix;
811 ExpectedDFix.Message = "variable 'D' is not initialized";
812 ExpectedDFix.Edits.push_back(TextEdit{Main.range("DFix"), " = NAN"});
813 ExpectedDFix.Edits.push_back(
814 TextEdit{Main.range("MathHeader"), "#include <math.h>\n\n"});
815 EXPECT_THAT(
816 *TU.build().getDiagnostics(),
817 ifTidyChecks(UnorderedElementsAre(
818 AllOf(Diag(Main.range("A"), "'A' should be initialized in a member "
819 "initializer of the constructor"),
820 withFix(equalToFix(ExpectedAFix))),
821 AllOf(Diag(Main.range("B"), "'B' should be initialized in a member "
822 "initializer of the constructor"),
823 withFix(equalToFix(ExpectedBFix))),
824 AllOf(Diag(Main.range("C"), "variable 'C' is not initialized"),
825 withFix(equalToFix(ExpectedCFix))),
826 AllOf(Diag(Main.range("D"), "variable 'D' is not initialized"),
827 withFix(equalToFix(ExpectedDFix))))));
828 }
829
830 TEST(DiagnosticsTest, Preprocessor) {
831 // This looks like a preamble, but there's an #else in the middle!
832 // Check that:
833 // - the #else doesn't generate diagnostics (we had this bug)
834 // - we get diagnostics from the taken branch
835 // - we get no diagnostics from the not taken branch
836 Annotations Test(R"cpp(
837 #ifndef FOO
838 #define FOO
839 int a = [[b]]; // error-ok
840 #else
841 int x = y;
842 #endif
843 )cpp");
844 EXPECT_THAT(
845 *TestTU::withCode(Test.code()).build().getDiagnostics(),
846 ElementsAre(Diag(Test.range(), "use of undeclared identifier 'b'")));
847 }
848
849 TEST(DiagnosticsTest, IgnoreVerify) {
850 auto TU = TestTU::withCode(R"cpp(
851 int a; // expected-error {{}}
852 )cpp");
853 TU.ExtraArgs.push_back("-Xclang");
854 TU.ExtraArgs.push_back("-verify");
855 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
856 }
857
858 TEST(DiagnosticTest, IgnoreBEFilelistOptions) {
859 auto TU = TestTU::withCode("");
860 TU.ExtraArgs.push_back("-Xclang");
861 for (const auto *DisableOption :
862 {"-fsanitize-ignorelist=null", "-fprofile-list=null",
863 "-fxray-always-instrument=null", "-fxray-never-instrument=null",
864 "-fxray-attr-list=null"}) {
865 TU.ExtraArgs.push_back(DisableOption);
866 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
867 TU.ExtraArgs.pop_back();
868 }
869 }
870
871 // Recursive main-file include is diagnosed, and doesn't crash.
872 TEST(DiagnosticsTest, RecursivePreamble) {
873 auto TU = TestTU::withCode(R"cpp(
874 #include "foo.h" // error-ok
875 int symbol;
876 )cpp");
877 TU.Filename = "foo.h";
878 EXPECT_THAT(*TU.build().getDiagnostics(),
879 ElementsAre(diagName("pp_including_mainfile_in_preamble")));
880 EXPECT_THAT(TU.build().getLocalTopLevelDecls(), SizeIs(1));
881 }
882
883 // Recursive main-file include with #pragma once guard is OK.
884 TEST(DiagnosticsTest, RecursivePreamblePragmaOnce) {
885 auto TU = TestTU::withCode(R"cpp(
886 #pragma once
887 #include "foo.h"
888 int symbol;
889 )cpp");
890 TU.Filename = "foo.h";
891 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
892 EXPECT_THAT(TU.build().getLocalTopLevelDecls(), SizeIs(1));
893 }
894
895 // Recursive main-file include with #ifndef guard should be OK.
896 // However, it's not yet recognized (incomplete at end of preamble).
897 TEST(DiagnosticsTest, RecursivePreambleIfndefGuard) {
898 auto TU = TestTU::withCode(R"cpp(
899 #ifndef FOO
900 #define FOO
901 #include "foo.h" // error-ok
902 int symbol;
903 #endif
904 )cpp");
905 TU.Filename = "foo.h";
906 // FIXME: should be no errors here.
907 EXPECT_THAT(*TU.build().getDiagnostics(),
908 ElementsAre(diagName("pp_including_mainfile_in_preamble")));
909 EXPECT_THAT(TU.build().getLocalTopLevelDecls(), SizeIs(1));
910 }
911
912 TEST(DiagnosticsTest, PreambleWithPragmaAssumeNonnull) {
913 auto TU = TestTU::withCode(R"cpp(
914 #pragma clang assume_nonnull begin
915 void foo(int *x);
916 #pragma clang assume_nonnull end
917 )cpp");
918 auto AST = TU.build();
919 EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
920 const auto *X = cast<FunctionDecl>(findDecl(AST, "foo")).getParamDecl(0);
921 ASSERT_TRUE(X->getOriginalType()->getNullability() ==
922 NullabilityKind::NonNull);
923 }
924
925 TEST(DiagnosticsTest, PreambleHeaderWithBadPragmaAssumeNonnull) {
926 Annotations Header(R"cpp(
927 #pragma clang assume_nonnull begin // error-ok
928 void foo(int *X);
929 )cpp");
930 auto TU = TestTU::withCode(R"cpp(
931 #include "foo.h" // unterminated assume_nonnull should not affect bar.
932 void bar(int *Y);
933 )cpp");
934 TU.AdditionalFiles = {{"foo.h", std::string(Header.code())}};
935 auto AST = TU.build();
936 EXPECT_THAT(*AST.getDiagnostics(),
937 ElementsAre(diagName("pp_eof_in_assume_nonnull")));
938 const auto *X = cast<FunctionDecl>(findDecl(AST, "foo")).getParamDecl(0);
939 ASSERT_TRUE(X->getOriginalType()->getNullability() ==
940 NullabilityKind::NonNull);
941 const auto *Y = cast<FunctionDecl>(findDecl(AST, "bar")).getParamDecl(0);
942 ASSERT_FALSE(Y->getOriginalType()->getNullability());
943 }
944
945 TEST(DiagnosticsTest, InsideMacros) {
946 Annotations Test(R"cpp(
947 #define TEN 10
948 #define RET(x) return x + 10
949
950 int* foo() {
951 RET($foo[[0]]); // error-ok
952 }
953 int* bar() {
954 return $bar[[TEN]];
955 }
956 )cpp");
957 EXPECT_THAT(*TestTU::withCode(Test.code()).build().getDiagnostics(),
958 ElementsAre(Diag(Test.range("foo"),
959 "cannot initialize return object of type "
960 "'int *' with an rvalue of type 'int'"),
961 Diag(Test.range("bar"),
962 "cannot initialize return object of type "
963 "'int *' with an rvalue of type 'int'")));
964 }
965
966 TEST(DiagnosticsTest, NoFixItInMacro) {
967 Annotations Test(R"cpp(
968 #define Define(name) void name() {}
969
970 [[Define]](main) // error-ok
971 )cpp");
972 auto TU = TestTU::withCode(Test.code());
973 EXPECT_THAT(*TU.build().getDiagnostics(),
974 ElementsAre(AllOf(Diag(Test.range(), "'main' must return 'int'"),
975 Not(withFix(_)))));
976 }
977
978 TEST(DiagnosticsTest, PragmaSystemHeader) {
979 Annotations Test("#pragma clang [[system_header]]\n");
980 auto TU = TestTU::withCode(Test.code());
981 EXPECT_THAT(
982 *TU.build().getDiagnostics(),
983 ElementsAre(AllOf(
984 Diag(Test.range(), "#pragma system_header ignored in main file"))));
985 TU.Filename = "TestTU.h";
986 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
987 }
988
989 TEST(ClangdTest, MSAsm) {
990 // Parsing MS assembly tries to use the target MCAsmInfo, which we don't link.
991 // We used to crash here. Now clang emits a diagnostic, which we filter out.
992 llvm::InitializeAllTargetInfos(); // As in ClangdMain
993 auto TU = TestTU::withCode("void fn() { __asm { cmp cl,64 } }");
994 TU.ExtraArgs = {"-fms-extensions"};
995 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
996 }
997
998 TEST(DiagnosticsTest, ToLSP) {
999 URIForFile MainFile =
1000 URIForFile::canonicalize(testPath("foo/bar/main.cpp"), "");
1001 URIForFile HeaderFile =
1002 URIForFile::canonicalize(testPath("foo/bar/header.h"), "");
1003
1004 clangd::Diag D;
1005 D.ID = clang::diag::err_undeclared_var_use;
1006 D.Tags = {DiagnosticTag::Unnecessary};
1007 D.Name = "undeclared_var_use";
1008 D.Source = clangd::Diag::Clang;
1009 D.Message = "something terrible happened";
1010 D.Range = {pos(1, 2), pos(3, 4)};
1011 D.InsideMainFile = true;
1012 D.Severity = DiagnosticsEngine::Error;
1013 D.File = "foo/bar/main.cpp";
1014 D.AbsFile = std::string(MainFile.file());
1015
1016 clangd::Note NoteInMain;
1017 NoteInMain.Message = "declared somewhere in the main file";
1018 NoteInMain.Range = {pos(5, 6), pos(7, 8)};
1019 NoteInMain.Severity = DiagnosticsEngine::Remark;
1020 NoteInMain.File = "../foo/bar/main.cpp";
1021 NoteInMain.InsideMainFile = true;
1022 NoteInMain.AbsFile = std::string(MainFile.file());
1023
1024 D.Notes.push_back(NoteInMain);
1025
1026 clangd::Note NoteInHeader;
1027 NoteInHeader.Message = "declared somewhere in the header file";
1028 NoteInHeader.Range = {pos(9, 10), pos(11, 12)};
1029 NoteInHeader.Severity = DiagnosticsEngine::Note;
1030 NoteInHeader.File = "../foo/baz/header.h";
1031 NoteInHeader.InsideMainFile = false;
1032 NoteInHeader.AbsFile = std::string(HeaderFile.file());
1033 D.Notes.push_back(NoteInHeader);
1034
1035 clangd::Fix F;
1036 F.Message = "do something";
1037 D.Fixes.push_back(F);
1038
1039 // Diagnostics should turn into these:
1040 clangd::Diagnostic MainLSP;
1041 MainLSP.range = D.Range;
1042 MainLSP.severity = getSeverity(DiagnosticsEngine::Error);
1043 MainLSP.code = "undeclared_var_use";
1044 MainLSP.source = "clang";
1045 MainLSP.message =
1046 R"(Something terrible happened (fix available)
1047
1048 main.cpp:6:7: remark: declared somewhere in the main file
1049
1050 ../foo/baz/header.h:10:11:
1051 note: declared somewhere in the header file)";
1052 MainLSP.tags = {DiagnosticTag::Unnecessary};
1053
1054 clangd::Diagnostic NoteInMainLSP;
1055 NoteInMainLSP.range = NoteInMain.Range;
1056 NoteInMainLSP.severity = getSeverity(DiagnosticsEngine::Remark);
1057 NoteInMainLSP.message = R"(Declared somewhere in the main file
1058
1059 main.cpp:2:3: error: something terrible happened)";
1060
1061 ClangdDiagnosticOptions Opts;
1062 // Transform diagnostics and check the results.
1063 std::vector<std::pair<clangd::Diagnostic, std::vector<clangd::Fix>>> LSPDiags;
1064 toLSPDiags(D, MainFile, Opts,
1065 [&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix> Fixes) {
1066 LSPDiags.push_back(
1067 {std::move(LSPDiag),
1068 std::vector<clangd::Fix>(Fixes.begin(), Fixes.end())});
1069 });
1070
1071 EXPECT_THAT(
1072 LSPDiags,
1073 ElementsAre(Pair(equalToLSPDiag(MainLSP), ElementsAre(equalToFix(F))),
1074 Pair(equalToLSPDiag(NoteInMainLSP), IsEmpty())));
1075 EXPECT_EQ(LSPDiags[0].first.code, "undeclared_var_use");
1076 EXPECT_EQ(LSPDiags[0].first.source, "clang");
1077 EXPECT_EQ(LSPDiags[1].first.code, "");
1078 EXPECT_EQ(LSPDiags[1].first.source, "");
1079
1080 // Same thing, but don't flatten notes into the main list.
1081 LSPDiags.clear();
1082 Opts.EmitRelatedLocations = true;
1083 toLSPDiags(D, MainFile, Opts,
1084 [&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix> Fixes) {
1085 LSPDiags.push_back(
1086 {std::move(LSPDiag),
1087 std::vector<clangd::Fix>(Fixes.begin(), Fixes.end())});
1088 });
1089 MainLSP.message = "Something terrible happened (fix available)";
1090 DiagnosticRelatedInformation NoteInMainDRI;
1091 NoteInMainDRI.message = "Declared somewhere in the main file";
1092 NoteInMainDRI.location.range = NoteInMain.Range;
1093 NoteInMainDRI.location.uri = MainFile;
1094 MainLSP.relatedInformation = {NoteInMainDRI};
1095 DiagnosticRelatedInformation NoteInHeaderDRI;
1096 NoteInHeaderDRI.message = "Declared somewhere in the header file";
1097 NoteInHeaderDRI.location.range = NoteInHeader.Range;
1098 NoteInHeaderDRI.location.uri = HeaderFile;
1099 MainLSP.relatedInformation = {NoteInMainDRI, NoteInHeaderDRI};
1100 EXPECT_THAT(LSPDiags, ElementsAre(Pair(equalToLSPDiag(MainLSP),
1101 ElementsAre(equalToFix(F)))));
1102 }
1103
1104 struct SymbolWithHeader {
1105 std::string QName;
1106 std::string DeclaringFile;
1107 std::string IncludeHeader;
1108 };
1109
1110 std::unique_ptr<SymbolIndex>
1111 buildIndexWithSymbol(llvm::ArrayRef<SymbolWithHeader> Syms) {
1112 SymbolSlab::Builder Slab;
1113 for (const auto &S : Syms) {
1114 Symbol Sym = cls(S.QName);
1115 Sym.Flags |= Symbol::IndexedForCodeCompletion;
1116 Sym.CanonicalDeclaration.FileURI = S.DeclaringFile.c_str();
1117 Sym.Definition.FileURI = S.DeclaringFile.c_str();
1118 Sym.IncludeHeaders.emplace_back(S.IncludeHeader, 1, Symbol::Include);
1119 Slab.insert(Sym);
1120 }
1121 return MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
1122 }
1123
1124 TEST(IncludeFixerTest, IncompleteType) {
1125 auto TU = TestTU::withHeaderCode("namespace ns { class X; } ns::X *x;");
1126 TU.ExtraArgs.push_back("-std=c++20");
1127 auto Index = buildIndexWithSymbol(
1128 {SymbolWithHeader{"ns::X", "unittest:///x.h", "\"x.h\""}});
1129 TU.ExternalIndex = Index.get();
1130
1131 std::vector<std::pair<llvm::StringRef, llvm::StringRef>> Tests{
1132 {"incomplete_nested_name_spec", "[[ns::X::]]Nested n;"},
1133 {"incomplete_base_class", "class Y : [[ns::X]] {};"},
1134 {"incomplete_member_access", "auto i = x[[->]]f();"},
1135 {"incomplete_type", "auto& [[[]]m] = *x;"},
1136 {"init_incomplete_type",
1137 "struct C { static int f(ns::X&); }; int i = C::f([[{]]});"},
1138 {"bad_cast_incomplete", "auto a = [[static_cast]]<ns::X>(0);"},
1139 {"template_nontype_parm_incomplete", "template <ns::X [[foo]]> int a;"},
1140 {"typecheck_decl_incomplete_type", "ns::X [[var]];"},
1141 {"typecheck_incomplete_tag", "auto i = [[(*x)]]->f();"},
1142 {"typecheck_nonviable_condition_incomplete",
1143 "struct A { operator ns::X(); } a; const ns::X &[[b]] = a;"},
1144 {"invalid_incomplete_type_use", "auto var = [[ns::X()]];"},
1145 {"sizeof_alignof_incomplete_or_sizeless_type",
1146 "auto s = [[sizeof]](ns::X);"},
1147 {"for_range_incomplete_type", "void foo() { for (auto i : [[*]]x ) {} }"},
1148 {"func_def_incomplete_result", "ns::X [[func]] () {}"},
1149 {"field_incomplete_or_sizeless", "class M { ns::X [[member]]; };"},
1150 {"array_incomplete_or_sizeless_type", "auto s = [[(ns::X[]){}]];"},
1151 {"call_incomplete_return", "ns::X f(); auto fp = &f; auto z = [[fp()]];"},
1152 {"call_function_incomplete_return", "ns::X foo(); auto a = [[foo()]];"},
1153 {"call_incomplete_argument", "int m(ns::X); int i = m([[*x]]);"},
1154 {"switch_incomplete_class_type", "void a() { [[switch]](*x) {} }"},
1155 {"delete_incomplete_class_type", "void f() { [[delete]] *x; }"},
1156 {"-Wdelete-incomplete", "void f() { [[delete]] x; }"},
1157 {"dereference_incomplete_type",
1158 R"cpp(void f() { asm("" : "=r"([[*]]x)::); })cpp"},
1159 };
1160 for (auto Case : Tests) {
1161 Annotations Main(Case.second);
1162 TU.Code = Main.code().str() + "\n // error-ok";
1163 EXPECT_THAT(
1164 *TU.build().getDiagnostics(),
1165 ElementsAre(AllOf(diagName(Case.first), hasRange(Main.range()),
1166 withFix(Fix(Range{}, "#include \"x.h\"\n",
1167 "Include \"x.h\" for symbol ns::X")))))
1168 << Case.second;
1169 }
1170 }
1171
1172 TEST(IncludeFixerTest, IncompleteEnum) {
1173 Symbol Sym = enm("X");
1174 Sym.Flags |= Symbol::IndexedForCodeCompletion;
1175 Sym.CanonicalDeclaration.FileURI = Sym.Definition.FileURI = "unittest:///x.h";
1176 Sym.IncludeHeaders.emplace_back("\"x.h\"", 1, Symbol::Include);
1177 SymbolSlab::Builder Slab;
1178 Slab.insert(Sym);
1179 auto Index =
1180 MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
1181
1182 TestTU TU;
1183 TU.ExternalIndex = Index.get();
1184 TU.ExtraArgs.push_back("-std=c++20");
1185 TU.ExtraArgs.push_back("-fno-ms-compatibility"); // else incomplete enum is OK
1186
1187 std::vector<std::pair<llvm::StringRef, llvm::StringRef>> Tests{
1188 {"incomplete_enum", "enum class X : int; using enum [[X]];"},
1189 {"underlying_type_of_incomplete_enum",
1190 "[[__underlying_type]](enum X) i;"},
1191 };
1192 for (auto Case : Tests) {
1193 Annotations Main(Case.second);
1194 TU.Code = Main.code().str() + "\n // error-ok";
1195 EXPECT_THAT(*TU.build().getDiagnostics(),
1196 Contains(AllOf(diagName(Case.first), hasRange(Main.range()),
1197 withFix(Fix(Range{}, "#include \"x.h\"\n",
1198 "Include \"x.h\" for symbol X")))))
1199 << Case.second;
1200 }
1201 }
1202
1203 TEST(IncludeFixerTest, NoSuggestIncludeWhenNoDefinitionInHeader) {
1204 Annotations Test(R"cpp(// error-ok
1205 $insert[[]]namespace ns {
1206 class X;
1207 }
1208 class Y : $base[[public ns::X]] {};
1209 int main() {
1210 ns::X *x;
1211 x$access[[->]]f();
1212 }
1213 )cpp");
1214 auto TU = TestTU::withCode(Test.code());
1215 Symbol Sym = cls("ns::X");
1216 Sym.Flags |= Symbol::IndexedForCodeCompletion;
1217 Sym.CanonicalDeclaration.FileURI = "unittest:///x.h";
1218 Sym.Definition.FileURI = "unittest:///x.cc";
1219 Sym.IncludeHeaders.emplace_back("\"x.h\"", 1, Symbol::Include);
1220
1221 SymbolSlab::Builder Slab;
1222 Slab.insert(Sym);
1223 auto Index =
1224 MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
1225 TU.ExternalIndex = Index.get();
1226
1227 EXPECT_THAT(*TU.build().getDiagnostics(),
1228 UnorderedElementsAre(
1229 Diag(Test.range("base"), "base class has incomplete type"),
1230 Diag(Test.range("access"),
1231 "member access into incomplete type 'ns::X'")));
1232 }
1233
1234 TEST(IncludeFixerTest, Typo) {
1235 Annotations Test(R"cpp(// error-ok
1236 $insert[[]]namespace ns {
1237 void foo() {
1238 $unqualified1[[X]] x;
1239 // No fix if the unresolved type is used as specifier. (ns::)X::Nested will be
1240 // considered the unresolved type.
1241 $unqualified2[[X]]::Nested n;
1242 }
1243 struct S : $base[[X]] {};
1244 }
1245 void bar() {
1246 ns::$qualified1[[X]] x; // ns:: is valid.
1247 ns::$qualified2[[X]](); // Error: no member in namespace
1248
1249 ::$global[[Global]] glob;
1250 }
1251 using Type = ns::$template[[Foo]]<int>;
1252 )cpp");
1253 auto TU = TestTU::withCode(Test.code());
1254 auto Index = buildIndexWithSymbol(
1255 {SymbolWithHeader{"ns::X", "unittest:///x.h", "\"x.h\""},
1256 SymbolWithHeader{"Global", "unittest:///global.h", "\"global.h\""},
1257 SymbolWithHeader{"ns::Foo", "unittest:///foo.h", "\"foo.h\""}});
1258 TU.ExternalIndex = Index.get();
1259
1260 EXPECT_THAT(
1261 *TU.build().getDiagnostics(),
1262 UnorderedElementsAre(
1263 AllOf(Diag(Test.range("unqualified1"), "unknown type name 'X'"),
1264 diagName("unknown_typename"),
1265 withFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
1266 "Include \"x.h\" for symbol ns::X"))),
1267 Diag(Test.range("unqualified2"), "use of undeclared identifier 'X'"),
1268 AllOf(Diag(Test.range("qualified1"),
1269 "no type named 'X' in namespace 'ns'"),
1270 diagName("typename_nested_not_found"),
1271 withFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
1272 "Include \"x.h\" for symbol ns::X"))),
1273 AllOf(Diag(Test.range("qualified2"),
1274 "no member named 'X' in namespace 'ns'"),
1275 diagName("no_member"),
1276 withFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
1277 "Include \"x.h\" for symbol ns::X"))),
1278 AllOf(Diag(Test.range("global"),
1279 "no type named 'Global' in the global namespace"),
1280 diagName("typename_nested_not_found"),
1281 withFix(Fix(Test.range("insert"), "#include \"global.h\"\n",
1282 "Include \"global.h\" for symbol Global"))),
1283 AllOf(Diag(Test.range("template"),
1284 "no template named 'Foo' in namespace 'ns'"),
1285 diagName("no_member_template"),
1286 withFix(Fix(Test.range("insert"), "#include \"foo.h\"\n",
1287 "Include \"foo.h\" for symbol ns::Foo"))),
1288 AllOf(Diag(Test.range("base"), "expected class name"),
1289 diagName("expected_class_name"),
1290 withFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
1291 "Include \"x.h\" for symbol ns::X")))));
1292 }
1293
1294 TEST(IncludeFixerTest, TypoInMacro) {
1295 auto TU = TestTU::withCode(R"cpp(// error-ok
1296 #define ID(T) T
1297 X a1;
1298 ID(X a2);
1299 ns::X a3;
1300 ID(ns::X a4);
1301 namespace ns{};
1302 ns::X a5;
1303 ID(ns::X a6);
1304 )cpp");
1305 auto Index = buildIndexWithSymbol(
1306 {SymbolWithHeader{"X", "unittest:///x.h", "\"x.h\""},
1307 SymbolWithHeader{"ns::X", "unittest:///ns.h", "\"x.h\""}});
1308 TU.ExternalIndex = Index.get();
1309 // FIXME: -fms-compatibility (which is default on windows) breaks the
1310 // ns::X cases when the namespace is undeclared. Find out why!
1311 TU.ExtraArgs = {"-fno-ms-compatibility"};
1312 EXPECT_THAT(*TU.build().getDiagnostics(), Each(withFix(_)));
1313 }
1314
1315 TEST(IncludeFixerTest, MultipleMatchedSymbols) {
1316 Annotations Test(R"cpp(// error-ok
1317 $insert[[]]namespace na {
1318 namespace nb {
1319 void foo() {
1320 $unqualified[[X]] x;
1321 }
1322 }
1323 }
1324 )cpp");
1325 auto TU = TestTU::withCode(Test.code());
1326 auto Index = buildIndexWithSymbol(
1327 {SymbolWithHeader{"na::X", "unittest:///a.h", "\"a.h\""},
1328 SymbolWithHeader{"na::nb::X", "unittest:///b.h", "\"b.h\""}});
1329 TU.ExternalIndex = Index.get();
1330
1331 EXPECT_THAT(*TU.build().getDiagnostics(),
1332 UnorderedElementsAre(AllOf(
1333 Diag(Test.range("unqualified"), "unknown type name 'X'"),
1334 diagName("unknown_typename"),
1335 withFix(Fix(Test.range("insert"), "#include \"a.h\"\n",
1336 "Include \"a.h\" for symbol na::X"),
1337 Fix(Test.range("insert"), "#include \"b.h\"\n",
1338 "Include \"b.h\" for symbol na::nb::X")))));
1339 }
1340
1341 TEST(IncludeFixerTest, NoCrashMemberAccess) {
1342 Annotations Test(R"cpp(// error-ok
1343 struct X { int xyz; };
1344 void g() { X x; x.$[[xy]]; }
1345 )cpp");
1346 auto TU = TestTU::withCode(Test.code());
1347 auto Index = buildIndexWithSymbol(
1348 SymbolWithHeader{"na::X", "unittest:///a.h", "\"a.h\""});
1349 TU.ExternalIndex = Index.get();
1350
1351 EXPECT_THAT(
1352 *TU.build().getDiagnostics(),
1353 UnorderedElementsAre(Diag(Test.range(), "no member named 'xy' in 'X'")));
1354 }
1355
1356 TEST(IncludeFixerTest, UseCachedIndexResults) {
1357 // As index results for the identical request are cached, more than 5 fixes
1358 // are generated.
1359 Annotations Test(R"cpp(// error-ok
1360 $insert[[]]void foo() {
1361 $x1[[X]] x;
1362 $x2[[X]] x;
1363 $x3[[X]] x;
1364 $x4[[X]] x;
1365 $x5[[X]] x;
1366 $x6[[X]] x;
1367 $x7[[X]] x;
1368 }
1369
1370 class X;
1371 void bar(X *x) {
1372 x$a1[[->]]f();
1373 x$a2[[->]]f();
1374 x$a3[[->]]f();
1375 x$a4[[->]]f();
1376 x$a5[[->]]f();
1377 x$a6[[->]]f();
1378 x$a7[[->]]f();
1379 }
1380 )cpp");
1381 auto TU = TestTU::withCode(Test.code());
1382 auto Index =
1383 buildIndexWithSymbol(SymbolWithHeader{"X", "unittest:///a.h", "\"a.h\""});
1384 TU.ExternalIndex = Index.get();
1385
1386 auto Parsed = TU.build();
1387 for (const auto &D : *Parsed.getDiagnostics()) {
1388 if (D.Fixes.size() != 1) {
1389 ADD_FAILURE() << "D.Fixes.size() != 1";
1390 continue;
1391 }
1392 EXPECT_EQ(D.Fixes[0].Message, std::string("Include \"a.h\" for symbol X"));
1393 }
1394 }
1395
1396 TEST(IncludeFixerTest, UnresolvedNameAsSpecifier) {
1397 Annotations Test(R"cpp(// error-ok
1398 $insert[[]]namespace ns {
1399 }
1400 void g() { ns::$[[scope]]::X_Y(); }
1401 )cpp");
1402 TestTU TU;
1403 TU.Code = std::string(Test.code());
1404 // FIXME: Figure out why this is needed and remove it, PR43662.
1405 TU.ExtraArgs.push_back("-fno-ms-compatibility");
1406 auto Index = buildIndexWithSymbol(
1407 SymbolWithHeader{"ns::scope::X_Y", "unittest:///x.h", "\"x.h\""});
1408 TU.ExternalIndex = Index.get();
1409
1410 EXPECT_THAT(
1411 *TU.build().getDiagnostics(),
1412 UnorderedElementsAre(
1413 AllOf(Diag(Test.range(), "no member named 'scope' in namespace 'ns'"),
1414 diagName("no_member"),
1415 withFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
1416 "Include \"x.h\" for symbol ns::scope::X_Y")))));
1417 }
1418
1419 TEST(IncludeFixerTest, UnresolvedSpecifierWithSemaCorrection) {
1420 Annotations Test(R"cpp(// error-ok
1421 $insert[[]]namespace clang {
1422 void f() {
1423 // "clangd::" will be corrected to "clang::" by Sema.
1424 $q1[[clangd]]::$x[[X]] x;
1425 $q2[[clangd]]::$ns[[ns]]::Y y;
1426 }
1427 }
1428 )cpp");
1429 TestTU TU;
1430 TU.Code = std::string(Test.code());
1431 // FIXME: Figure out why this is needed and remove it, PR43662.
1432 TU.ExtraArgs.push_back("-fno-ms-compatibility");
1433 auto Index = buildIndexWithSymbol(
1434 {SymbolWithHeader{"clang::clangd::X", "unittest:///x.h", "\"x.h\""},
1435 SymbolWithHeader{"clang::clangd::ns::Y", "unittest:///y.h", "\"y.h\""}});
1436 TU.ExternalIndex = Index.get();
1437
1438 EXPECT_THAT(
1439 *TU.build().getDiagnostics(),
1440 UnorderedElementsAre(
1441 AllOf(Diag(Test.range("q1"), "use of undeclared identifier 'clangd'; "
1442 "did you mean 'clang'?"),
1443 diagName("undeclared_var_use_suggest"),
1444 withFix(_, // change clangd to clang
1445 Fix(Test.range("insert"), "#include \"x.h\"\n",
1446 "Include \"x.h\" for symbol clang::clangd::X"))),
1447 AllOf(Diag(Test.range("x"), "no type named 'X' in namespace 'clang'"),
1448 diagName("typename_nested_not_found"),
1449 withFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
1450 "Include \"x.h\" for symbol clang::clangd::X"))),
1451 AllOf(
1452 Diag(Test.range("q2"), "use of undeclared identifier 'clangd'; "
1453 "did you mean 'clang'?"),
1454 diagName("undeclared_var_use_suggest"),
1455 withFix(_, // change clangd to clang
1456 Fix(Test.range("insert"), "#include \"y.h\"\n",
1457 "Include \"y.h\" for symbol clang::clangd::ns::Y"))),
1458 AllOf(Diag(Test.range("ns"),
1459 "no member named 'ns' in namespace 'clang'"),
1460 diagName("no_member"),
1461 withFix(
1462 Fix(Test.range("insert"), "#include \"y.h\"\n",
1463 "Include \"y.h\" for symbol clang::clangd::ns::Y")))));
1464 }
1465
1466 TEST(IncludeFixerTest, SpecifiedScopeIsNamespaceAlias) {
1467 Annotations Test(R"cpp(// error-ok
1468 $insert[[]]namespace a {}
1469 namespace b = a;
1470 namespace c {
1471 b::$[[X]] x;
1472 }
1473 )cpp");
1474 auto TU = TestTU::withCode(Test.code());
1475 auto Index = buildIndexWithSymbol(
1476 SymbolWithHeader{"a::X", "unittest:///x.h", "\"x.h\""});
1477 TU.ExternalIndex = Index.get();
1478
1479 EXPECT_THAT(*TU.build().getDiagnostics(),
1480 UnorderedElementsAre(AllOf(
1481 Diag(Test.range(), "no type named 'X' in namespace 'a'"),
1482 diagName("typename_nested_not_found"),
1483 withFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
1484 "Include \"x.h\" for symbol a::X")))));
1485 }
1486
1487 TEST(IncludeFixerTest, NoCrashOnTemplateInstantiations) {
1488 Annotations Test(R"cpp(
1489 template <typename T> struct Templ {
1490 template <typename U>
1491 typename U::type operator=(const U &);
1492 };
1493
1494 struct A {
1495 Templ<char> s;
1496 A() { [[a]]; /*error-ok*/ } // crash if we compute scopes lazily.
1497 };
1498 )cpp");
1499
1500 auto TU = TestTU::withCode(Test.code());
1501 auto Index = buildIndexWithSymbol({});
1502 TU.ExternalIndex = Index.get();
1503
1504 EXPECT_THAT(
1505 *TU.build().getDiagnostics(),
1506 ElementsAre(Diag(Test.range(), "use of undeclared identifier 'a'")));
1507 }
1508
1509 TEST(IncludeFixerTest, HeaderNamedInDiag) {
1510 Annotations Test(R"cpp(
1511 $insert[[]]int main() {
1512 [[printf]]("");
1513 }
1514 )cpp");
1515 auto TU = TestTU::withCode(Test.code());
1516 TU.ExtraArgs = {"-xc", "-std=c99",
1517 "-Wno-error=implicit-function-declaration"};
1518 auto Index = buildIndexWithSymbol({});
1519 TU.ExternalIndex = Index.get();
1520
1521 EXPECT_THAT(
1522 *TU.build().getDiagnostics(),
1523 ElementsAre(AllOf(
1524 Diag(Test.range(), "call to undeclared library function 'printf' "
1525 "with type 'int (const char *, ...)'; ISO C99 "
1526 "and later do not support implicit function "
1527 "declarations"),
1528 withFix(Fix(Test.range("insert"), "#include <stdio.h>\n",
1529 "Include <stdio.h> for symbol printf")))));
1530
1531 TU.ExtraArgs = {"-xc", "-std=c89"};
1532 EXPECT_THAT(
1533 *TU.build().getDiagnostics(),
1534 ElementsAre(AllOf(
1535 Diag(Test.range(), "implicitly declaring library function 'printf' "
1536 "with type 'int (const char *, ...)'"),
1537 withFix(Fix(Test.range("insert"), "#include <stdio.h>\n",
1538 "Include <stdio.h> for symbol printf")))));
1539 }
1540
1541 TEST(IncludeFixerTest, CImplicitFunctionDecl) {
1542 Annotations Test("void x() { [[foo]](); }");
1543 auto TU = TestTU::withCode(Test.code());
1544 TU.Filename = "test.c";
1545 TU.ExtraArgs = {"-std=c99", "-Wno-error=implicit-function-declaration"};
1546
1547 Symbol Sym = func("foo");
1548 Sym.Flags |= Symbol::IndexedForCodeCompletion;
1549 Sym.CanonicalDeclaration.FileURI = "unittest:///foo.h";
1550 Sym.IncludeHeaders.emplace_back("\"foo.h\"", 1, Symbol::Include);
1551
1552 SymbolSlab::Builder Slab;
1553 Slab.insert(Sym);
1554 auto Index =
1555 MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
1556 TU.ExternalIndex = Index.get();
1557
1558 EXPECT_THAT(
1559 *TU.build().getDiagnostics(),
1560 ElementsAre(AllOf(
1561 Diag(Test.range(),
1562 "call to undeclared function 'foo'; ISO C99 and later do not "
1563 "support implicit function declarations"),
1564 withFix(Fix(Range{}, "#include \"foo.h\"\n",
1565 "Include \"foo.h\" for symbol foo")))));
1566
1567 TU.ExtraArgs = {"-std=c89", "-Wall"};
1568 EXPECT_THAT(*TU.build().getDiagnostics(),
1569 ElementsAre(AllOf(
1570 Diag(Test.range(), "implicit declaration of function 'foo'"),
1571 withFix(Fix(Range{}, "#include \"foo.h\"\n",
1572 "Include \"foo.h\" for symbol foo")))));
1573 }
1574
1575 TEST(DiagsInHeaders, DiagInsideHeader) {
1576 Annotations Main(R"cpp(
1577 #include [["a.h"]]
1578 void foo() {})cpp");
1579 Annotations Header("[[no_type_spec]]; // error-ok");
1580 TestTU TU = TestTU::withCode(Main.code());
1581 TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
1582 EXPECT_THAT(*TU.build().getDiagnostics(),
1583 UnorderedElementsAre(AllOf(
1584 Diag(Main.range(), "in included file: a type specifier is "
1585 "required for all declarations"),
1586 withNote(Diag(Header.range(), "error occurred here")))));
1587 }
1588
1589 TEST(DiagsInHeaders, DiagInTransitiveInclude) {
1590 Annotations Main(R"cpp(
1591 #include [["a.h"]]
1592 void foo() {})cpp");
1593 TestTU TU = TestTU::withCode(Main.code());
1594 TU.AdditionalFiles = {{"a.h", "#include \"b.h\""},
1595 {"b.h", "no_type_spec; // error-ok"}};
1596 EXPECT_THAT(*TU.build().getDiagnostics(),
1597 UnorderedElementsAre(
1598 Diag(Main.range(), "in included file: a type specifier is "
1599 "required for all declarations")));
1600 }
1601
1602 TEST(DiagsInHeaders, DiagInMultipleHeaders) {
1603 Annotations Main(R"cpp(
1604 #include $a[["a.h"]]
1605 #include $b[["b.h"]]
1606 void foo() {})cpp");
1607 TestTU TU = TestTU::withCode(Main.code());
1608 TU.AdditionalFiles = {{"a.h", "no_type_spec; // error-ok"},
1609 {"b.h", "no_type_spec; // error-ok"}};
1610 EXPECT_THAT(*TU.build().getDiagnostics(),
1611 UnorderedElementsAre(
1612 Diag(Main.range("a"), "in included file: a type specifier is "
1613 "required for all declarations"),
1614 Diag(Main.range("b"), "in included file: a type specifier is "
1615 "required for all declarations")));
1616 }
1617
1618 TEST(DiagsInHeaders, PreferExpansionLocation) {
1619 Annotations Main(R"cpp(
1620 #include [["a.h"]]
1621 #include "b.h"
1622 void foo() {})cpp");
1623 TestTU TU = TestTU::withCode(Main.code());
1624 TU.AdditionalFiles = {
1625 {"a.h", "#include \"b.h\"\n"},
1626 {"b.h", "#ifndef X\n#define X\nno_type_spec; // error-ok\n#endif"}};
1627 EXPECT_THAT(*TU.build().getDiagnostics(),
1628 UnorderedElementsAre(Diag(Main.range(),
1629 "in included file: a type specifier is "
1630 "required for all declarations")));
1631 }
1632
1633 TEST(DiagsInHeaders, PreferExpansionLocationMacros) {
1634 Annotations Main(R"cpp(
1635 #define X
1636 #include "a.h"
1637 #undef X
1638 #include [["b.h"]]
1639 void foo() {})cpp");
1640 TestTU TU = TestTU::withCode(Main.code());
1641 TU.AdditionalFiles = {
1642 {"a.h", "#include \"c.h\"\n"},
1643 {"b.h", "#include \"c.h\"\n"},
1644 {"c.h", "#ifndef X\n#define X\nno_type_spec; // error-ok\n#endif"}};
1645 EXPECT_THAT(*TU.build().getDiagnostics(),
1646 UnorderedElementsAre(
1647 Diag(Main.range(), "in included file: a type specifier is "
1648 "required for all declarations")));
1649 }
1650
1651 TEST(DiagsInHeaders, LimitDiagsOutsideMainFile) {
1652 Annotations Main(R"cpp(
1653 #include [["a.h"]]
1654 #include "b.h"
1655 void foo() {})cpp");
1656 TestTU TU = TestTU::withCode(Main.code());
1657 TU.AdditionalFiles = {{"a.h", "#include \"c.h\"\n"},
1658 {"b.h", "#include \"c.h\"\n"},
1659 {"c.h", R"cpp(
1660 #ifndef X
1661 #define X
1662 no_type_spec_0; // error-ok
1663 no_type_spec_1;
1664 no_type_spec_2;
1665 no_type_spec_3;
1666 no_type_spec_4;
1667 no_type_spec_5;
1668 no_type_spec_6;
1669 no_type_spec_7;
1670 no_type_spec_8;
1671 no_type_spec_9;
1672 no_type_spec_10;
1673 #endif)cpp"}};
1674 EXPECT_THAT(*TU.build().getDiagnostics(),
1675 UnorderedElementsAre(
1676 Diag(Main.range(), "in included file: a type specifier is "
1677 "required for all declarations")));
1678 }
1679
1680 TEST(DiagsInHeaders, OnlyErrorOrFatal) {
1681 Annotations Main(R"cpp(
1682 #include [["a.h"]]
1683 void foo() {})cpp");
1684 Annotations Header(R"cpp(
1685 [[no_type_spec]]; // error-ok
1686 int x = 5/0;)cpp");
1687 TestTU TU = TestTU::withCode(Main.code());
1688 TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
1689 EXPECT_THAT(*TU.build().getDiagnostics(),
1690 UnorderedElementsAre(AllOf(
1691 Diag(Main.range(), "in included file: a type specifier is "
1692 "required for all declarations"),
1693 withNote(Diag(Header.range(), "error occurred here")))));
1694 }
1695
1696 TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
1697 Annotations Main(R"cpp(
1698 #include [["a.h"]] // get unused "foo" warning when building preamble.
1699 )cpp");
1700 Annotations Header(R"cpp(
1701 namespace { void foo() {} }
1702 void func() {foo();} ;)cpp");
1703 TestTU TU = TestTU::withCode(Main.code());
1704 TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
1705 // promote warnings to errors.
1706 TU.ExtraArgs = {"-Werror", "-Wunused"};
1707 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
1708 }
1709
1710 TEST(DiagsInHeaders, FromNonWrittenSources) {
1711 Annotations Main(R"cpp(
1712 #include [["a.h"]]
1713 void foo() {})cpp");
1714 Annotations Header(R"cpp(
1715 int x = 5/0;
1716 int b = [[FOO]]; // error-ok)cpp");
1717 TestTU TU = TestTU::withCode(Main.code());
1718 TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
1719 TU.ExtraArgs = {"-DFOO=NOOO"};
1720 EXPECT_THAT(*TU.build().getDiagnostics(),
1721 UnorderedElementsAre(AllOf(
1722 Diag(Main.range(),
1723 "in included file: use of undeclared identifier 'NOOO'"),
1724 withNote(Diag(Header.range(), "error occurred here")))));
1725 }
1726
1727 TEST(DiagsInHeaders, ErrorFromMacroExpansion) {
1728 Annotations Main(R"cpp(
1729 void bar() {
1730 int fo; // error-ok
1731 #include [["a.h"]]
1732 })cpp");
1733 Annotations Header(R"cpp(
1734 #define X foo
1735 X;)cpp");
1736 TestTU TU = TestTU::withCode(Main.code());
1737 TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
1738 EXPECT_THAT(*TU.build().getDiagnostics(),
1739 UnorderedElementsAre(
1740 Diag(Main.range(), "in included file: use of undeclared "
1741 "identifier 'foo'; did you mean 'fo'?")));
1742 }
1743
1744 TEST(DiagsInHeaders, ErrorFromMacroArgument) {
1745 Annotations Main(R"cpp(
1746 void bar() {
1747 int fo; // error-ok
1748 #include [["a.h"]]
1749 })cpp");
1750 Annotations Header(R"cpp(
1751 #define X(arg) arg
1752 X(foo);)cpp");
1753 TestTU TU = TestTU::withCode(Main.code());
1754 TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
1755 EXPECT_THAT(*TU.build().getDiagnostics(),
1756 UnorderedElementsAre(
1757 Diag(Main.range(), "in included file: use of undeclared "
1758 "identifier 'foo'; did you mean 'fo'?")));
1759 }
1760
1761 TEST(IgnoreDiags, FromNonWrittenInclude) {
1762 TestTU TU;
1763 TU.ExtraArgs.push_back("--include=a.h");
1764 TU.AdditionalFiles = {{"a.h", "void main();"}};
1765 // The diagnostic "main must return int" is from the header, we don't attempt
1766 // to render it in the main file as there is no written location there.
1767 EXPECT_THAT(*TU.build().getDiagnostics(), UnorderedElementsAre());
1768 }
1769
1770 TEST(ToLSPDiag, RangeIsInMain) {
1771 ClangdDiagnosticOptions Opts;
1772 clangd::Diag D;
1773 D.Range = {pos(1, 2), pos(3, 4)};
1774 D.Notes.emplace_back();
1775 Note &N = D.Notes.back();
1776 N.Range = {pos(2, 3), pos(3, 4)};
1777
1778 D.InsideMainFile = true;
1779 N.InsideMainFile = false;
1780 toLSPDiags(D, {}, Opts,
1781 [&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix>) {
1782 EXPECT_EQ(LSPDiag.range, D.Range);
1783 });
1784
1785 D.InsideMainFile = false;
1786 N.InsideMainFile = true;
1787 toLSPDiags(D, {}, Opts,
1788 [&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix>) {
1789 EXPECT_EQ(LSPDiag.range, N.Range);
1790 });
1791 }
1792
1793 TEST(ParsedASTTest, ModuleSawDiag) {
1794 static constexpr const llvm::StringLiteral KDiagMsg = "StampedDiag";
1795 struct DiagModifierModule final : public FeatureModule {
1796 struct Listener : public FeatureModule::ASTListener {
1797 void sawDiagnostic(const clang::Diagnostic &Info,
1798 clangd::Diag &Diag) override {
1799 Diag.Message = KDiagMsg.str();
1800 }
1801 };
1802 std::unique_ptr<ASTListener> astListeners() override {
1803 return std::make_unique<Listener>();
1804 };
1805 };
1806 FeatureModuleSet FMS;
1807 FMS.add(std::make_unique<DiagModifierModule>());
1808
1809 Annotations Code("[[test]]; /* error-ok */");
1810 TestTU TU;
1811 TU.Code = Code.code().str();
1812 TU.FeatureModules = &FMS;
1813
1814 auto AST = TU.build();
1815 EXPECT_THAT(*AST.getDiagnostics(),
1816 testing::Contains(Diag(Code.range(), KDiagMsg.str())));
1817 }
1818
1819 TEST(Preamble, EndsOnNonEmptyLine) {
1820 TestTU TU;
1821 TU.ExtraArgs = {"-Wnewline-eof"};
1822
1823 {
1824 TU.Code = "#define FOO\n void bar();\n";
1825 auto AST = TU.build();
1826 EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
1827 }
1828 {
1829 Annotations Code("#define FOO[[]]");
1830 TU.Code = Code.code().str();
1831 auto AST = TU.build();
1832 EXPECT_THAT(
1833 *AST.getDiagnostics(),
1834 testing::Contains(Diag(Code.range(), "no newline at end of file")));
1835 }
1836 }
1837
1838 TEST(Diagnostics, Tags) {
1839 TestTU TU;
1840 TU.ExtraArgs = {"-Wunused", "-Wdeprecated"};
1841 Annotations Test(R"cpp(
1842 void bar() __attribute__((deprecated));
1843 void foo() {
1844 int $unused[[x]];
1845 $deprecated[[bar]]();
1846 })cpp");
1847 TU.Code = Test.code().str();
1848 EXPECT_THAT(*TU.build().getDiagnostics(),
1849 UnorderedElementsAre(
1850 AllOf(Diag(Test.range("unused"), "unused variable 'x'"),
1851 withTag(DiagnosticTag::Unnecessary)),
1852 AllOf(Diag(Test.range("deprecated"), "'bar' is deprecated"),
1853 withTag(DiagnosticTag::Deprecated))));
1854
1855 Test = Annotations(R"cpp(
1856 $typedef[[typedef int INT]];
1857 )cpp");
1858 TU.Code = Test.code();
1859 TU.ClangTidyProvider = addTidyChecks("modernize-use-using");
1860 EXPECT_THAT(
1861 *TU.build().getDiagnostics(),
1862 ifTidyChecks(UnorderedElementsAre(
1863 AllOf(Diag(Test.range("typedef"), "use 'using' instead of 'typedef'"),
1864 withTag(DiagnosticTag::Deprecated)))));
1865 }
1866
1867 TEST(DiagnosticsTest, IncludeCleaner) {
1868 Annotations Test(R"cpp(
1869 $fix[[ $diag[[#include "unused.h"]]
1870 ]]
1871 #include "used.h"
1872
1873 #include "ignore.h"
1874
1875 #include <system_header.h>
1876
1877 void foo() {
1878 used();
1879 }
1880 )cpp");
1881 TestTU TU;
1882 TU.Code = Test.code().str();
1883 TU.AdditionalFiles["unused.h"] = R"cpp(
1884 #pragma once
1885 void unused() {}
1886 )cpp";
1887 TU.AdditionalFiles["used.h"] = R"cpp(
1888 #pragma once
1889 void used() {}
1890 )cpp";
1891 TU.AdditionalFiles["ignore.h"] = R"cpp(
1892 #pragma once
1893 void ignore() {}
1894 )cpp";
1895 TU.AdditionalFiles["system/system_header.h"] = "";
1896 TU.ExtraArgs = {"-isystem" + testPath("system")};
1897 // Off by default.
1898 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
1899 Config Cfg;
1900 Cfg.Diagnostics.UnusedIncludes = Config::UnusedIncludesPolicy::Strict;
1901 // Set filtering.
1902 Cfg.Diagnostics.Includes.IgnoreHeader.emplace_back(
1903 [](llvm::StringRef Header) { return Header.endswith("ignore.h"); });
1904 WithContextValue WithCfg(Config::Key, std::move(Cfg));
1905 auto AST = TU.build();
1906 EXPECT_THAT(
1907 *AST.getDiagnostics(),
1908 UnorderedElementsAre(AllOf(
1909 Diag(Test.range("diag"),
1910 "included header unused.h is not used directly"),
1911 withTag(DiagnosticTag::Unnecessary), diagSource(Diag::Clangd),
1912 withFix(Fix(Test.range("fix"), "", "remove #include directive")))));
1913 auto &Diag = AST.getDiagnostics()->front();
1914 EXPECT_EQ(getDiagnosticDocURI(Diag.Source, Diag.ID, Diag.Name),
1915 std::string("https://clangd.llvm.org/guides/include-cleaner"));
1916 Cfg.Diagnostics.SuppressAll = true;
1917 WithContextValue SuppressAllWithCfg(Config::Key, std::move(Cfg));
1918 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
1919 Cfg.Diagnostics.SuppressAll = false;
1920 Cfg.Diagnostics.Suppress = {"unused-includes"};
1921 WithContextValue SuppressFilterWithCfg(Config::Key, std::move(Cfg));
1922 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
1923 }
1924
1925 TEST(DiagnosticsTest, FixItFromHeader) {
1926 llvm::StringLiteral Header(R"cpp(
1927 void foo(int *);
1928 void foo(int *, int);)cpp");
1929 Annotations Source(R"cpp(
1930 /*error-ok*/
1931 void bar() {
1932 int x;
1933 $diag[[foo]]($fix[[]]x, 1);
1934 })cpp");
1935 TestTU TU;
1936 TU.Code = Source.code().str();
1937 TU.HeaderCode = Header.str();
1938 EXPECT_THAT(
1939 *TU.build().getDiagnostics(),
1940 UnorderedElementsAre(AllOf(
1941 Diag(Source.range("diag"), "no matching function for call to 'foo'"),
1942 withFix(Fix(Source.range("fix"), "&",
1943 "candidate function not viable: no known conversion from "
1944 "'int' to 'int *' for 1st argument; take the address of "
1945 "the argument with &")))));
1946 }
1947
1948 TEST(DiagnosticsTest, UnusedInHeader) {
1949 // Clang diagnoses unused static inline functions outside headers.
1950 auto TU = TestTU::withCode("static inline void foo(void) {}");
1951 TU.ExtraArgs.push_back("-Wunused-function");
1952 TU.Filename = "test.c";
1953 EXPECT_THAT(*TU.build().getDiagnostics(),
1954 ElementsAre(withID(diag::warn_unused_function)));
1955 // Sema should recognize a *.h file open in clangd as a header.
1956 // https://github.com/clangd/vscode-clangd/issues/360
1957 TU.Filename = "test.h";
1958 EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
1959 }
1960
1961 } // namespace
1962 } // namespace clangd
1963 } // namespace clang