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