DiagnosticsTests.cpp
42.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
//===--- DiagnosticsTests.cpp ------------------------------------*- C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Annotations.h"
#include "Diagnostics.h"
#include "ParsedAST.h"
#include "Protocol.h"
#include "SourceCode.h"
#include "TestFS.h"
#include "TestIndex.h"
#include "TestTU.h"
#include "index/MemIndex.h"
#include "support/Path.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticSema.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/TargetSelect.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <algorithm>
namespace clang {
namespace clangd {
namespace {
using ::testing::_;
using ::testing::AllOf;
using ::testing::Contains;
using ::testing::ElementsAre;
using ::testing::Field;
using ::testing::IsEmpty;
using ::testing::Pair;
using testing::SizeIs;
using ::testing::UnorderedElementsAre;
::testing::Matcher<const Diag &> WithFix(::testing::Matcher<Fix> FixMatcher) {
return Field(&Diag::Fixes, ElementsAre(FixMatcher));
}
::testing::Matcher<const Diag &> WithFix(::testing::Matcher<Fix> FixMatcher1,
::testing::Matcher<Fix> FixMatcher2) {
return Field(&Diag::Fixes, UnorderedElementsAre(FixMatcher1, FixMatcher2));
}
::testing::Matcher<const Diag &>
WithNote(::testing::Matcher<Note> NoteMatcher) {
return Field(&Diag::Notes, ElementsAre(NoteMatcher));
}
::testing::Matcher<const Diag &>
WithNote(::testing::Matcher<Note> NoteMatcher1,
::testing::Matcher<Note> NoteMatcher2) {
return Field(&Diag::Notes, UnorderedElementsAre(NoteMatcher1, NoteMatcher2));
}
MATCHER_P2(Diag, Range, Message,
"Diag at " + llvm::to_string(Range) + " = [" + Message + "]") {
return arg.Range == Range && arg.Message == Message;
}
MATCHER_P3(Fix, Range, Replacement, Message,
"Fix " + llvm::to_string(Range) + " => " +
::testing::PrintToString(Replacement) + " = [" + Message + "]") {
return arg.Message == Message && arg.Edits.size() == 1 &&
arg.Edits[0].range == Range && arg.Edits[0].newText == Replacement;
}
MATCHER_P(FixMessage, Message, "") { return arg.Message == Message; }
MATCHER_P(EqualToLSPDiag, LSPDiag,
"LSP diagnostic " + llvm::to_string(LSPDiag)) {
if (toJSON(arg) != toJSON(LSPDiag)) {
*result_listener << llvm::formatv("expected:\n{0:2}\ngot\n{1:2}",
toJSON(LSPDiag), toJSON(arg))
.str();
return false;
}
return true;
}
MATCHER_P(DiagSource, S, "") { return arg.Source == S; }
MATCHER_P(DiagName, N, "") { return arg.Name == N; }
MATCHER_P(DiagSeverity, S, "") { return arg.Severity == S; }
MATCHER_P(EqualToFix, Fix, "LSP fix " + llvm::to_string(Fix)) {
if (arg.Message != Fix.Message)
return false;
if (arg.Edits.size() != Fix.Edits.size())
return false;
for (std::size_t I = 0; I < arg.Edits.size(); ++I) {
if (arg.Edits[I].range != Fix.Edits[I].range ||
arg.Edits[I].newText != Fix.Edits[I].newText)
return false;
}
return true;
}
// Helper function to make tests shorter.
Position pos(int line, int character) {
Position Res;
Res.line = line;
Res.character = character;
return Res;
}
TEST(DiagnosticsTest, DiagnosticRanges) {
// Check we report correct ranges, including various edge-cases.
Annotations Test(R"cpp(
// error-ok
#define ID(X) X
namespace test{};
void $decl[[foo]]();
class T{$explicit[[]]$constructor[[T]](int a);};
int main() {
$typo[[go\
o]]();
foo()$semicolon[[]]//with comments
$unk[[unknown]]();
double $type[[bar]] = "foo";
struct Foo { int x; }; Foo a;
a.$nomember[[y]];
test::$nomembernamespace[[test]];
$macro[[ID($macroarg[[fod]])]]();
}
)cpp");
auto TU = TestTU::withCode(Test.code());
TU.ClangTidyChecks = "-*,google-explicit-constructor";
EXPECT_THAT(
TU.build().getDiagnostics(),
ElementsAre(
// This range spans lines.
AllOf(Diag(Test.range("typo"),
"use of undeclared identifier 'goo'; did you mean 'foo'?"),
DiagSource(Diag::Clang), DiagName("undeclared_var_use_suggest"),
WithFix(
Fix(Test.range("typo"), "foo", "change 'go\\…' to 'foo'")),
// This is a pretty normal range.
WithNote(Diag(Test.range("decl"), "'foo' declared here"))),
// This range is zero-width and insertion. Therefore make sure we are
// not expanding it into other tokens. Since we are not going to
// replace those.
AllOf(Diag(Test.range("semicolon"), "expected ';' after expression"),
WithFix(Fix(Test.range("semicolon"), ";", "insert ';'"))),
// This range isn't provided by clang, we expand to the token.
Diag(Test.range("unk"), "use of undeclared identifier 'unknown'"),
Diag(Test.range("type"),
"cannot initialize a variable of type 'double' with an lvalue "
"of type 'const char [4]'"),
Diag(Test.range("nomember"), "no member named 'y' in 'Foo'"),
Diag(Test.range("nomembernamespace"),
"no member named 'test' in namespace 'test'"),
AllOf(Diag(Test.range("macro"),
"use of undeclared identifier 'fod'; did you mean 'foo'?"),
WithFix(Fix(Test.range("macroarg"), "foo",
"change 'fod' to 'foo'"))),
// We make sure here that the entire token is highlighted
AllOf(Diag(Test.range("constructor"),
"single-argument constructors must be marked explicit to "
"avoid unintentional implicit conversions"),
WithFix(Fix(Test.range("explicit"), "explicit ",
"insert 'explicit '")))));
}
TEST(DiagnosticsTest, FlagsMatter) {
Annotations Test("[[void]] main() {} // error-ok");
auto TU = TestTU::withCode(Test.code());
EXPECT_THAT(TU.build().getDiagnostics(),
ElementsAre(AllOf(Diag(Test.range(), "'main' must return 'int'"),
WithFix(Fix(Test.range(), "int",
"change 'void' to 'int'")))));
// Same code built as C gets different diagnostics.
TU.Filename = "Plain.c";
EXPECT_THAT(
TU.build().getDiagnostics(),
ElementsAre(AllOf(
Diag(Test.range(), "return type of 'main' is not 'int'"),
WithFix(Fix(Test.range(), "int", "change return type to 'int'")))));
}
TEST(DiagnosticsTest, DiagnosticPreamble) {
Annotations Test(R"cpp(
#include $[["not-found.h"]] // error-ok
)cpp");
auto TU = TestTU::withCode(Test.code());
EXPECT_THAT(TU.build().getDiagnostics(),
ElementsAre(::testing::AllOf(
Diag(Test.range(), "'not-found.h' file not found"),
DiagSource(Diag::Clang), DiagName("pp_file_not_found"))));
}
TEST(DiagnosticsTest, DeduplicatedClangTidyDiagnostics) {
Annotations Test(R"cpp(
float foo = [[0.1f]];
)cpp");
auto TU = TestTU::withCode(Test.code());
// Enable alias clang-tidy checks, these check emits the same diagnostics
// (except the check name).
TU.ClangTidyChecks = "-*, readability-uppercase-literal-suffix, "
"hicpp-uppercase-literal-suffix";
// Verify that we filter out the duplicated diagnostic message.
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(::testing::AllOf(
Diag(Test.range(),
"floating point literal has suffix 'f', which is not uppercase"),
DiagSource(Diag::ClangTidy))));
Test = Annotations(R"cpp(
template<typename T>
void func(T) {
float f = [[0.3f]];
}
void k() {
func(123);
func(2.0);
}
)cpp");
TU.Code = std::string(Test.code());
// The check doesn't handle template instantiations which ends up emitting
// duplicated messages, verify that we deduplicate them.
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(::testing::AllOf(
Diag(Test.range(),
"floating point literal has suffix 'f', which is not uppercase"),
DiagSource(Diag::ClangTidy))));
}
TEST(DiagnosticsTest, ClangTidy) {
Annotations Test(R"cpp(
#include $deprecated[["assert.h"]]
#define $macrodef[[SQUARE]](X) (X)*(X)
int $main[[main]]() {
int y = 4;
return SQUARE($macroarg[[++]]y);
return $doubled[[sizeof]](sizeof(int));
}
)cpp");
auto TU = TestTU::withCode(Test.code());
TU.HeaderFilename = "assert.h"; // Suppress "not found" error.
TU.ClangTidyChecks =
"-*, bugprone-sizeof-expression, bugprone-macro-repeated-side-effects, "
"modernize-deprecated-headers, modernize-use-trailing-return-type";
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(
AllOf(Diag(Test.range("deprecated"),
"inclusion of deprecated C++ header 'assert.h'; consider "
"using 'cassert' instead"),
DiagSource(Diag::ClangTidy),
DiagName("modernize-deprecated-headers"),
WithFix(Fix(Test.range("deprecated"), "<cassert>",
"change '\"assert.h\"' to '<cassert>'"))),
Diag(Test.range("doubled"),
"suspicious usage of 'sizeof(sizeof(...))'"),
AllOf(
Diag(Test.range("macroarg"),
"side effects in the 1st macro argument 'X' are repeated in "
"macro expansion"),
DiagSource(Diag::ClangTidy),
DiagName("bugprone-macro-repeated-side-effects"),
WithNote(
Diag(Test.range("macrodef"), "macro 'SQUARE' defined here"))),
Diag(Test.range("macroarg"),
"multiple unsequenced modifications to 'y'"),
AllOf(
Diag(Test.range("main"),
"use a trailing return type for this function"),
DiagSource(Diag::ClangTidy),
DiagName("modernize-use-trailing-return-type"),
// Verify that we don't have "[check-name]" suffix in the message.
WithFix(FixMessage(
"use a trailing return type for this function")))));
}
TEST(DiagnosticsTest, ClangTidyEOF) {
// clang-format off
Annotations Test(R"cpp(
[[#]]include <b.h>
#include "a.h")cpp");
// clang-format on
auto TU = TestTU::withCode(Test.code());
TU.ExtraArgs = {"-isystem."};
TU.AdditionalFiles["a.h"] = TU.AdditionalFiles["b.h"] = "";
TU.ClangTidyChecks = "-*, llvm-include-order";
EXPECT_THAT(
TU.build().getDiagnostics(),
Contains(AllOf(Diag(Test.range(), "#includes are not sorted properly"),
DiagSource(Diag::ClangTidy),
DiagName("llvm-include-order"))));
}
TEST(DiagnosticTest, TemplatesInHeaders) {
// Diagnostics from templates defined in headers are placed at the expansion.
Annotations Main(R"cpp(
Derived<int> [[y]]; // error-ok
)cpp");
Annotations Header(R"cpp(
template <typename T>
struct Derived : [[T]] {};
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.HeaderCode = Header.code().str();
EXPECT_THAT(
TU.build().getDiagnostics(),
ElementsAre(AllOf(
Diag(Main.range(), "in template: base specifier must name a class"),
WithNote(Diag(Header.range(), "error occurred here"),
Diag(Main.range(), "in instantiation of template class "
"'Derived<int>' requested here")))));
}
TEST(DiagnosticTest, MakeUnique) {
// We usually miss diagnostics from header functions as we don't parse them.
// std::make_unique is an exception.
Annotations Main(R"cpp(
struct S { S(char*); };
auto x = std::[[make_unique]]<S>(42); // error-ok
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.HeaderCode = R"cpp(
namespace std {
// These mocks aren't quite right - we omit unique_ptr for simplicity.
// forward is included to show its body is not needed to get the diagnostic.
template <typename T> T&& forward(T& t) { return static_cast<T&&>(t); }
template <typename T, typename... A> T* make_unique(A&&... args) {
return new T(std::forward<A>(args)...);
}
}
)cpp";
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Main.range(),
"in template: "
"no matching constructor for initialization of 'S'")));
}
TEST(DiagnosticTest, NoMultipleDiagnosticInFlight) {
Annotations Main(R"cpp(
template <typename T> struct Foo {
T *begin();
T *end();
};
struct LabelInfo {
int a;
bool b;
};
void f() {
Foo<LabelInfo> label_info_map;
[[for]] (auto it = label_info_map.begin(); it != label_info_map.end(); ++it) {
auto S = *it;
}
}
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.ClangTidyChecks = "modernize-loop-convert";
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(::testing::AllOf(
Diag(Main.range(), "use range-based for loop instead"),
DiagSource(Diag::ClangTidy), DiagName("modernize-loop-convert"))));
}
TEST(DiagnosticTest, ClangTidySuppressionComment) {
Annotations Main(R"cpp(
int main() {
int i = 3;
double d = 8 / i; // NOLINT
// NOLINTNEXTLINE
double e = 8 / i;
#define BAD 8 / i
double f = BAD; // NOLINT
double g = [[8]] / i;
#define BAD2 BAD
double h = BAD2; // NOLINT
}
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.ClangTidyChecks = "bugprone-integer-division";
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(::testing::AllOf(
Diag(Main.range(), "result of integer division used in a floating "
"point context; possible loss of precision"),
DiagSource(Diag::ClangTidy), DiagName("bugprone-integer-division"))));
}
TEST(DiagnosticTest, ClangTidyWarningAsError) {
Annotations Main(R"cpp(
int main() {
int i = 3;
double f = [[8]] / i; // error-ok
}
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.ClangTidyChecks = "bugprone-integer-division";
TU.ClangTidyWarningsAsErrors = "bugprone-integer-division";
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(::testing::AllOf(
Diag(Main.range(), "result of integer division used in a floating "
"point context; possible loss of precision"),
DiagSource(Diag::ClangTidy), DiagName("bugprone-integer-division"),
DiagSeverity(DiagnosticsEngine::Error))));
}
TEST(DiagnosticTest, LongFixMessages) {
// We limit the size of printed code.
Annotations Source(R"cpp(
int main() {
// error-ok
int somereallyreallyreallyreallyreallyreallyreallyreallylongidentifier;
[[omereallyreallyreallyreallyreallyreallyreallyreallylongidentifier]]= 10;
}
)cpp");
TestTU TU = TestTU::withCode(Source.code());
EXPECT_THAT(
TU.build().getDiagnostics(),
ElementsAre(WithFix(Fix(
Source.range(),
"somereallyreallyreallyreallyreallyreallyreallyreallylongidentifier",
"change 'omereallyreallyreallyreallyreallyreallyreallyreall…' to "
"'somereallyreallyreallyreallyreallyreallyreallyreal…'"))));
// Only show changes up to a first newline.
Source = Annotations(R"cpp(
// error-ok
int main() {
int ident;
[[ide\
n]] = 10; // error-ok
}
)cpp");
TU.Code = std::string(Source.code());
EXPECT_THAT(TU.build().getDiagnostics(),
ElementsAre(WithFix(
Fix(Source.range(), "ident", "change 'ide\\…' to 'ident'"))));
}
TEST(DiagnosticTest, ClangTidySuppressionCommentTrumpsWarningAsError) {
Annotations Main(R"cpp(
int main() {
int i = 3;
double f = [[8]] / i; // NOLINT
}
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.ClangTidyChecks = "bugprone-integer-division";
TU.ClangTidyWarningsAsErrors = "bugprone-integer-division";
EXPECT_THAT(TU.build().getDiagnostics(), UnorderedElementsAre());
}
TEST(DiagnosticTest, ClangTidyNoLiteralDataInMacroToken) {
Annotations Main(R"cpp(
#define SIGTERM 15
using pthread_t = int;
int pthread_kill(pthread_t thread, int sig);
int func() {
pthread_t thread;
return pthread_kill(thread, 0);
}
)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.ClangTidyChecks = "-*,bugprone-bad-signal-to-kill-thread";
EXPECT_THAT(TU.build().getDiagnostics(), UnorderedElementsAre()); // no-crash
}
TEST(DiagnosticsTest, Preprocessor) {
// This looks like a preamble, but there's an #else in the middle!
// Check that:
// - the #else doesn't generate diagnostics (we had this bug)
// - we get diagnostics from the taken branch
// - we get no diagnostics from the not taken branch
Annotations Test(R"cpp(
#ifndef FOO
#define FOO
int a = [[b]]; // error-ok
#else
int x = y;
#endif
)cpp");
EXPECT_THAT(
TestTU::withCode(Test.code()).build().getDiagnostics(),
ElementsAre(Diag(Test.range(), "use of undeclared identifier 'b'")));
}
// Recursive main-file include is diagnosed, and doesn't crash.
TEST(DiagnosticsTest, RecursivePreamble) {
auto TU = TestTU::withCode(R"cpp(
#include "foo.h" // error-ok
int symbol;
)cpp");
TU.Filename = "foo.h";
EXPECT_THAT(TU.build().getDiagnostics(),
ElementsAre(DiagName("pp_including_mainfile_in_preamble")));
EXPECT_THAT(TU.build().getLocalTopLevelDecls(), SizeIs(1));
}
// Recursive main-file include with #pragma once guard is OK.
TEST(DiagnosticsTest, RecursivePreamblePragmaOnce) {
auto TU = TestTU::withCode(R"cpp(
#pragma once
#include "foo.h"
int symbol;
)cpp");
TU.Filename = "foo.h";
EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
EXPECT_THAT(TU.build().getLocalTopLevelDecls(), SizeIs(1));
}
// Recursive main-file include with #ifndef guard should be OK.
// However, it's not yet recognized (incomplete at end of preamble).
TEST(DiagnosticsTest, RecursivePreambleIfndefGuard) {
auto TU = TestTU::withCode(R"cpp(
#ifndef FOO
#define FOO
#include "foo.h" // error-ok
int symbol;
#endif
)cpp");
TU.Filename = "foo.h";
// FIXME: should be no errors here.
EXPECT_THAT(TU.build().getDiagnostics(),
ElementsAre(DiagName("pp_including_mainfile_in_preamble")));
EXPECT_THAT(TU.build().getLocalTopLevelDecls(), SizeIs(1));
}
TEST(DiagnosticsTest, InsideMacros) {
Annotations Test(R"cpp(
#define TEN 10
#define RET(x) return x + 10
int* foo() {
RET($foo[[0]]); // error-ok
}
int* bar() {
return $bar[[TEN]];
}
)cpp");
EXPECT_THAT(TestTU::withCode(Test.code()).build().getDiagnostics(),
ElementsAre(Diag(Test.range("foo"),
"cannot initialize return object of type "
"'int *' with an rvalue of type 'int'"),
Diag(Test.range("bar"),
"cannot initialize return object of type "
"'int *' with an rvalue of type 'int'")));
}
TEST(DiagnosticsTest, NoFixItInMacro) {
Annotations Test(R"cpp(
#define Define(name) void name() {}
[[Define]](main) // error-ok
)cpp");
auto TU = TestTU::withCode(Test.code());
EXPECT_THAT(TU.build().getDiagnostics(),
ElementsAre(AllOf(Diag(Test.range(), "'main' must return 'int'"),
Not(WithFix(_)))));
}
TEST(ClangdTest, MSAsm) {
// Parsing MS assembly tries to use the target MCAsmInfo, which we don't link.
// We used to crash here. Now clang emits a diagnostic, which we filter out.
llvm::InitializeAllTargetInfos(); // As in ClangdMain
auto TU = TestTU::withCode("void fn() { __asm { cmp cl,64 } }");
TU.ExtraArgs = {"-fms-extensions"};
EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
}
TEST(DiagnosticsTest, ToLSP) {
URIForFile MainFile =
URIForFile::canonicalize(testPath("foo/bar/main.cpp"), "");
URIForFile HeaderFile =
URIForFile::canonicalize(testPath("foo/bar/header.h"), "");
clangd::Diag D;
D.ID = clang::diag::err_undeclared_var_use;
D.Name = "undeclared_var_use";
D.Source = clangd::Diag::Clang;
D.Message = "something terrible happened";
D.Range = {pos(1, 2), pos(3, 4)};
D.InsideMainFile = true;
D.Severity = DiagnosticsEngine::Error;
D.File = "foo/bar/main.cpp";
D.AbsFile = std::string(MainFile.file());
clangd::Note NoteInMain;
NoteInMain.Message = "declared somewhere in the main file";
NoteInMain.Range = {pos(5, 6), pos(7, 8)};
NoteInMain.Severity = DiagnosticsEngine::Remark;
NoteInMain.File = "../foo/bar/main.cpp";
NoteInMain.InsideMainFile = true;
NoteInMain.AbsFile = std::string(MainFile.file());
D.Notes.push_back(NoteInMain);
clangd::Note NoteInHeader;
NoteInHeader.Message = "declared somewhere in the header file";
NoteInHeader.Range = {pos(9, 10), pos(11, 12)};
NoteInHeader.Severity = DiagnosticsEngine::Note;
NoteInHeader.File = "../foo/baz/header.h";
NoteInHeader.InsideMainFile = false;
NoteInHeader.AbsFile = std::string(HeaderFile.file());
D.Notes.push_back(NoteInHeader);
clangd::Fix F;
F.Message = "do something";
D.Fixes.push_back(F);
// Diagnostics should turn into these:
clangd::Diagnostic MainLSP;
MainLSP.range = D.Range;
MainLSP.severity = getSeverity(DiagnosticsEngine::Error);
MainLSP.code = "undeclared_var_use";
MainLSP.source = "clang";
MainLSP.message =
R"(Something terrible happened (fix available)
main.cpp:6:7: remark: declared somewhere in the main file
../foo/baz/header.h:10:11:
note: declared somewhere in the header file)";
clangd::Diagnostic NoteInMainLSP;
NoteInMainLSP.range = NoteInMain.Range;
NoteInMainLSP.severity = getSeverity(DiagnosticsEngine::Remark);
NoteInMainLSP.message = R"(Declared somewhere in the main file
main.cpp:2:3: error: something terrible happened)";
ClangdDiagnosticOptions Opts;
// Transform diagnostics and check the results.
std::vector<std::pair<clangd::Diagnostic, std::vector<clangd::Fix>>> LSPDiags;
toLSPDiags(D, MainFile, Opts,
[&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix> Fixes) {
LSPDiags.push_back(
{std::move(LSPDiag),
std::vector<clangd::Fix>(Fixes.begin(), Fixes.end())});
});
EXPECT_THAT(
LSPDiags,
ElementsAre(Pair(EqualToLSPDiag(MainLSP), ElementsAre(EqualToFix(F))),
Pair(EqualToLSPDiag(NoteInMainLSP), IsEmpty())));
EXPECT_EQ(LSPDiags[0].first.code, "undeclared_var_use");
EXPECT_EQ(LSPDiags[0].first.source, "clang");
EXPECT_EQ(LSPDiags[1].first.code, "");
EXPECT_EQ(LSPDiags[1].first.source, "");
// Same thing, but don't flatten notes into the main list.
LSPDiags.clear();
Opts.EmitRelatedLocations = true;
toLSPDiags(D, MainFile, Opts,
[&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix> Fixes) {
LSPDiags.push_back(
{std::move(LSPDiag),
std::vector<clangd::Fix>(Fixes.begin(), Fixes.end())});
});
MainLSP.message = "Something terrible happened (fix available)";
DiagnosticRelatedInformation NoteInMainDRI;
NoteInMainDRI.message = "Declared somewhere in the main file";
NoteInMainDRI.location.range = NoteInMain.Range;
NoteInMainDRI.location.uri = MainFile;
MainLSP.relatedInformation = {NoteInMainDRI};
DiagnosticRelatedInformation NoteInHeaderDRI;
NoteInHeaderDRI.message = "Declared somewhere in the header file";
NoteInHeaderDRI.location.range = NoteInHeader.Range;
NoteInHeaderDRI.location.uri = HeaderFile;
MainLSP.relatedInformation = {NoteInMainDRI, NoteInHeaderDRI};
EXPECT_THAT(LSPDiags, ElementsAre(Pair(EqualToLSPDiag(MainLSP),
ElementsAre(EqualToFix(F)))));
}
struct SymbolWithHeader {
std::string QName;
std::string DeclaringFile;
std::string IncludeHeader;
};
std::unique_ptr<SymbolIndex>
buildIndexWithSymbol(llvm::ArrayRef<SymbolWithHeader> Syms) {
SymbolSlab::Builder Slab;
for (const auto &S : Syms) {
Symbol Sym = cls(S.QName);
Sym.Flags |= Symbol::IndexedForCodeCompletion;
Sym.CanonicalDeclaration.FileURI = S.DeclaringFile.c_str();
Sym.Definition.FileURI = S.DeclaringFile.c_str();
Sym.IncludeHeaders.emplace_back(S.IncludeHeader, 1);
Slab.insert(Sym);
}
return MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
}
TEST(IncludeFixerTest, IncompleteType) {
Annotations Test(R"cpp(// error-ok
$insert[[]]namespace ns {
class X;
$nested[[X::]]Nested n;
}
class Y : $base[[public ns::X]] {};
int main() {
ns::X *x;
x$access[[->]]f();
}
)cpp");
auto TU = TestTU::withCode(Test.code());
auto Index = buildIndexWithSymbol(
{SymbolWithHeader{"ns::X", "unittest:///x.h", "\"x.h\""}});
TU.ExternalIndex = Index.get();
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(
AllOf(Diag(Test.range("nested"),
"incomplete type 'ns::X' named in nested name specifier"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol ns::X"))),
AllOf(Diag(Test.range("base"), "base class has incomplete type"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol ns::X"))),
AllOf(Diag(Test.range("access"),
"member access into incomplete type 'ns::X'"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol ns::X")))));
}
TEST(IncludeFixerTest, NoSuggestIncludeWhenNoDefinitionInHeader) {
Annotations Test(R"cpp(// error-ok
$insert[[]]namespace ns {
class X;
}
class Y : $base[[public ns::X]] {};
int main() {
ns::X *x;
x$access[[->]]f();
}
)cpp");
auto TU = TestTU::withCode(Test.code());
Symbol Sym = cls("ns::X");
Sym.Flags |= Symbol::IndexedForCodeCompletion;
Sym.CanonicalDeclaration.FileURI = "unittest:///x.h";
Sym.Definition.FileURI = "unittest:///x.cc";
Sym.IncludeHeaders.emplace_back("\"x.h\"", 1);
SymbolSlab::Builder Slab;
Slab.insert(Sym);
auto Index =
MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
TU.ExternalIndex = Index.get();
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Test.range("base"), "base class has incomplete type"),
Diag(Test.range("access"),
"member access into incomplete type 'ns::X'")));
}
TEST(IncludeFixerTest, Typo) {
Annotations Test(R"cpp(// error-ok
$insert[[]]namespace ns {
void foo() {
$unqualified1[[X]] x;
// No fix if the unresolved type is used as specifier. (ns::)X::Nested will be
// considered the unresolved type.
$unqualified2[[X]]::Nested n;
}
}
void bar() {
ns::$qualified1[[X]] x; // ns:: is valid.
ns::$qualified2[[X]](); // Error: no member in namespace
::$global[[Global]] glob;
}
)cpp");
auto TU = TestTU::withCode(Test.code());
auto Index = buildIndexWithSymbol(
{SymbolWithHeader{"ns::X", "unittest:///x.h", "\"x.h\""},
SymbolWithHeader{"Global", "unittest:///global.h", "\"global.h\""}});
TU.ExternalIndex = Index.get();
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(
AllOf(Diag(Test.range("unqualified1"), "unknown type name 'X'"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol ns::X"))),
Diag(Test.range("unqualified2"), "use of undeclared identifier 'X'"),
AllOf(Diag(Test.range("qualified1"),
"no type named 'X' in namespace 'ns'"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol ns::X"))),
AllOf(Diag(Test.range("qualified2"),
"no member named 'X' in namespace 'ns'"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol ns::X"))),
AllOf(Diag(Test.range("global"),
"no type named 'Global' in the global namespace"),
WithFix(Fix(Test.range("insert"), "#include \"global.h\"\n",
"Add include \"global.h\" for symbol Global")))));
}
TEST(IncludeFixerTest, MultipleMatchedSymbols) {
Annotations Test(R"cpp(// error-ok
$insert[[]]namespace na {
namespace nb {
void foo() {
$unqualified[[X]] x;
}
}
}
)cpp");
auto TU = TestTU::withCode(Test.code());
auto Index = buildIndexWithSymbol(
{SymbolWithHeader{"na::X", "unittest:///a.h", "\"a.h\""},
SymbolWithHeader{"na::nb::X", "unittest:///b.h", "\"b.h\""}});
TU.ExternalIndex = Index.get();
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(AllOf(
Diag(Test.range("unqualified"), "unknown type name 'X'"),
WithFix(Fix(Test.range("insert"), "#include \"a.h\"\n",
"Add include \"a.h\" for symbol na::X"),
Fix(Test.range("insert"), "#include \"b.h\"\n",
"Add include \"b.h\" for symbol na::nb::X")))));
}
TEST(IncludeFixerTest, NoCrashMemebrAccess) {
Annotations Test(R"cpp(// error-ok
struct X { int xyz; };
void g() { X x; x.$[[xy]]; }
)cpp");
auto TU = TestTU::withCode(Test.code());
auto Index = buildIndexWithSymbol(
SymbolWithHeader{"na::X", "unittest:///a.h", "\"a.h\""});
TU.ExternalIndex = Index.get();
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(Diag(Test.range(), "no member named 'xy' in 'X'")));
}
TEST(IncludeFixerTest, UseCachedIndexResults) {
// As index results for the identical request are cached, more than 5 fixes
// are generated.
Annotations Test(R"cpp(// error-ok
$insert[[]]void foo() {
$x1[[X]] x;
$x2[[X]] x;
$x3[[X]] x;
$x4[[X]] x;
$x5[[X]] x;
$x6[[X]] x;
$x7[[X]] x;
}
class X;
void bar(X *x) {
x$a1[[->]]f();
x$a2[[->]]f();
x$a3[[->]]f();
x$a4[[->]]f();
x$a5[[->]]f();
x$a6[[->]]f();
x$a7[[->]]f();
}
)cpp");
auto TU = TestTU::withCode(Test.code());
auto Index =
buildIndexWithSymbol(SymbolWithHeader{"X", "unittest:///a.h", "\"a.h\""});
TU.ExternalIndex = Index.get();
auto Parsed = TU.build();
for (const auto &D : Parsed.getDiagnostics()) {
if (D.Fixes.size() != 1) {
ADD_FAILURE() << "D.Fixes.size() != 1";
continue;
}
EXPECT_EQ(D.Fixes[0].Message,
std::string("Add include \"a.h\" for symbol X"));
}
}
TEST(IncludeFixerTest, UnresolvedNameAsSpecifier) {
Annotations Test(R"cpp(// error-ok
$insert[[]]namespace ns {
}
void g() { ns::$[[scope]]::X_Y(); }
)cpp");
TestTU TU;
TU.Code = std::string(Test.code());
// FIXME: Figure out why this is needed and remove it, PR43662.
TU.ExtraArgs.push_back("-fno-ms-compatibility");
auto Index = buildIndexWithSymbol(
SymbolWithHeader{"ns::scope::X_Y", "unittest:///x.h", "\"x.h\""});
TU.ExternalIndex = Index.get();
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(AllOf(
Diag(Test.range(), "no member named 'scope' in namespace 'ns'"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol ns::scope::X_Y")))));
}
TEST(IncludeFixerTest, UnresolvedSpecifierWithSemaCorrection) {
Annotations Test(R"cpp(// error-ok
$insert[[]]namespace clang {
void f() {
// "clangd::" will be corrected to "clang::" by Sema.
$q1[[clangd]]::$x[[X]] x;
$q2[[clangd]]::$ns[[ns]]::Y y;
}
}
)cpp");
TestTU TU;
TU.Code = std::string(Test.code());
// FIXME: Figure out why this is needed and remove it, PR43662.
TU.ExtraArgs.push_back("-fno-ms-compatibility");
auto Index = buildIndexWithSymbol(
{SymbolWithHeader{"clang::clangd::X", "unittest:///x.h", "\"x.h\""},
SymbolWithHeader{"clang::clangd::ns::Y", "unittest:///y.h", "\"y.h\""}});
TU.ExternalIndex = Index.get();
EXPECT_THAT(
TU.build().getDiagnostics(),
UnorderedElementsAre(
AllOf(
Diag(Test.range("q1"), "use of undeclared identifier 'clangd'; "
"did you mean 'clang'?"),
WithFix(_, // change clangd to clang
Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol clang::clangd::X"))),
AllOf(
Diag(Test.range("x"), "no type named 'X' in namespace 'clang'"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol clang::clangd::X"))),
AllOf(
Diag(Test.range("q2"), "use of undeclared identifier 'clangd'; "
"did you mean 'clang'?"),
WithFix(
_, // change clangd to clangd
Fix(Test.range("insert"), "#include \"y.h\"\n",
"Add include \"y.h\" for symbol clang::clangd::ns::Y"))),
AllOf(Diag(Test.range("ns"),
"no member named 'ns' in namespace 'clang'"),
WithFix(Fix(
Test.range("insert"), "#include \"y.h\"\n",
"Add include \"y.h\" for symbol clang::clangd::ns::Y")))));
}
TEST(IncludeFixerTest, SpecifiedScopeIsNamespaceAlias) {
Annotations Test(R"cpp(// error-ok
$insert[[]]namespace a {}
namespace b = a;
namespace c {
b::$[[X]] x;
}
)cpp");
auto TU = TestTU::withCode(Test.code());
auto Index = buildIndexWithSymbol(
SymbolWithHeader{"a::X", "unittest:///x.h", "\"x.h\""});
TU.ExternalIndex = Index.get();
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(AllOf(
Diag(Test.range(), "no type named 'X' in namespace 'a'"),
WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
"Add include \"x.h\" for symbol a::X")))));
}
TEST(IncludeFixerTest, NoCrashOnTemplateInstantiations) {
Annotations Test(R"cpp(
template <typename T> struct Templ {
template <typename U>
typename U::type operator=(const U &);
};
struct A {
Templ<char> s;
A() { [[a]]; /*error-ok*/ } // crash if we compute scopes lazily.
};
)cpp");
auto TU = TestTU::withCode(Test.code());
auto Index = buildIndexWithSymbol({});
TU.ExternalIndex = Index.get();
EXPECT_THAT(
TU.build().getDiagnostics(),
ElementsAre(Diag(Test.range(), "use of undeclared identifier 'a'")));
}
TEST(DiagsInHeaders, DiagInsideHeader) {
Annotations Main(R"cpp(
#include [["a.h"]]
void foo() {})cpp");
Annotations Header("[[no_type_spec]]; // error-ok");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(AllOf(
Diag(Main.range(), "in included file: C++ requires a "
"type specifier for all declarations"),
WithNote(Diag(Header.range(), "error occurred here")))));
}
TEST(DiagsInHeaders, DiagInTransitiveInclude) {
Annotations Main(R"cpp(
#include [["a.h"]]
void foo() {})cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", "#include \"b.h\""},
{"b.h", "no_type_spec; // error-ok"}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Main.range(), "in included file: C++ requires a "
"type specifier for all declarations")));
}
TEST(DiagsInHeaders, DiagInMultipleHeaders) {
Annotations Main(R"cpp(
#include $a[["a.h"]]
#include $b[["b.h"]]
void foo() {})cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", "no_type_spec; // error-ok"},
{"b.h", "no_type_spec; // error-ok"}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Main.range("a"), "in included file: C++ requires a type "
"specifier for all declarations"),
Diag(Main.range("b"), "in included file: C++ requires a type "
"specifier for all declarations")));
}
TEST(DiagsInHeaders, PreferExpansionLocation) {
Annotations Main(R"cpp(
#include [["a.h"]]
#include "b.h"
void foo() {})cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {
{"a.h", "#include \"b.h\"\n"},
{"b.h", "#ifndef X\n#define X\nno_type_spec; // error-ok\n#endif"}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(Diag(Main.range(),
"in included file: C++ requires a type "
"specifier for all declarations")));
}
TEST(DiagsInHeaders, PreferExpansionLocationMacros) {
Annotations Main(R"cpp(
#define X
#include "a.h"
#undef X
#include [["b.h"]]
void foo() {})cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {
{"a.h", "#include \"c.h\"\n"},
{"b.h", "#include \"c.h\"\n"},
{"c.h", "#ifndef X\n#define X\nno_type_spec; // error-ok\n#endif"}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Main.range(), "in included file: C++ requires a "
"type specifier for all declarations")));
}
TEST(DiagsInHeaders, LimitDiagsOutsideMainFile) {
Annotations Main(R"cpp(
#include [["a.h"]]
#include "b.h"
void foo() {})cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", "#include \"c.h\"\n"},
{"b.h", "#include \"c.h\"\n"},
{"c.h", R"cpp(
#ifndef X
#define X
no_type_spec_0; // error-ok
no_type_spec_1;
no_type_spec_2;
no_type_spec_3;
no_type_spec_4;
no_type_spec_5;
no_type_spec_6;
no_type_spec_7;
no_type_spec_8;
no_type_spec_9;
no_type_spec_10;
#endif)cpp"}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Main.range(), "in included file: C++ requires a "
"type specifier for all declarations")));
}
TEST(DiagsInHeaders, OnlyErrorOrFatal) {
Annotations Main(R"cpp(
#include [["a.h"]]
void foo() {})cpp");
Annotations Header(R"cpp(
[[no_type_spec]]; // error-ok
int x = 5/0;)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(AllOf(
Diag(Main.range(), "in included file: C++ requires "
"a type specifier for all declarations"),
WithNote(Diag(Header.range(), "error occurred here")))));
}
TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
Annotations Main(R"cpp(
#include [["a.h"]] // get unused "foo" warning when building preamble.
)cpp");
Annotations Header(R"cpp(
namespace { void foo() {} }
void func() {foo();} ;)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
// promote warnings to errors.
TU.ExtraArgs = {"-Werror", "-Wunused"};
EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
}
TEST(DiagsInHeaders, FromNonWrittenSources) {
Annotations Main(R"cpp(
#include [["a.h"]]
void foo() {})cpp");
Annotations Header(R"cpp(
int x = 5/0;
int b = [[FOO]]; // error-ok)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
TU.ExtraArgs = {"-DFOO=NOOO"};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(AllOf(
Diag(Main.range(),
"in included file: use of undeclared identifier 'NOOO'"),
WithNote(Diag(Header.range(), "error occurred here")))));
}
TEST(DiagsInHeaders, ErrorFromMacroExpansion) {
Annotations Main(R"cpp(
void bar() {
int fo; // error-ok
#include [["a.h"]]
})cpp");
Annotations Header(R"cpp(
#define X foo
X;)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Main.range(), "in included file: use of undeclared "
"identifier 'foo'; did you mean 'fo'?")));
}
TEST(DiagsInHeaders, ErrorFromMacroArgument) {
Annotations Main(R"cpp(
void bar() {
int fo; // error-ok
#include [["a.h"]]
})cpp");
Annotations Header(R"cpp(
#define X(arg) arg
X(foo);)cpp");
TestTU TU = TestTU::withCode(Main.code());
TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
EXPECT_THAT(TU.build().getDiagnostics(),
UnorderedElementsAre(
Diag(Main.range(), "in included file: use of undeclared "
"identifier 'foo'; did you mean 'fo'?")));
}
TEST(IgnoreDiags, FromNonWrittenInclude) {
TestTU TU;
TU.ExtraArgs.push_back("--include=a.h");
TU.AdditionalFiles = {{"a.h", "void main();"}};
// The diagnostic "main must return int" is from the header, we don't attempt
// to render it in the main file as there is no written location there.
EXPECT_THAT(TU.build().getDiagnostics(), UnorderedElementsAre());
}
TEST(ToLSPDiag, RangeIsInMain) {
ClangdDiagnosticOptions Opts;
clangd::Diag D;
D.Range = {pos(1, 2), pos(3, 4)};
D.Notes.emplace_back();
Note &N = D.Notes.back();
N.Range = {pos(2, 3), pos(3, 4)};
D.InsideMainFile = true;
N.InsideMainFile = false;
toLSPDiags(D, {}, Opts,
[&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix>) {
EXPECT_EQ(LSPDiag.range, D.Range);
});
D.InsideMainFile = false;
N.InsideMainFile = true;
toLSPDiags(D, {}, Opts,
[&](clangd::Diagnostic LSPDiag, ArrayRef<clangd::Fix>) {
EXPECT_EQ(LSPDiag.range, N.Range);
});
}
} // namespace
} // namespace clangd
} // namespace clang