clang-tools 24.0.0git
InlayHintTests.cpp
Go to the documentation of this file.
1//===-- InlayHintTests.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#include "Annotations.h"
9#include "Config.h"
10#include "InlayHints.h"
11#include "Protocol.h"
12#include "TestTU.h"
13#include "TestWorkspace.h"
14#include "XRefs.h"
15#include "support/Context.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Support/ScopedPrinter.h"
18#include "llvm/Support/raw_ostream.h"
19#include "gmock/gmock.h"
20#include "gtest/gtest.h"
21#include <optional>
22#include <string>
23#include <utility>
24#include <vector>
25
26namespace clang {
27namespace clangd {
28
29llvm::raw_ostream &operator<<(llvm::raw_ostream &Stream,
30 const InlayHint &Hint) {
31 return Stream << Hint.joinLabels() << "@" << Hint.range;
32}
33
34namespace {
35
36using ::testing::ElementsAre;
37using ::testing::IsEmpty;
38
39constexpr InlayHintOptions DefaultOptsForTests{2};
40
41std::vector<InlayHint> hintsOfKind(ParsedAST &AST, InlayHintKind Kind,
42 InlayHintOptions Opts) {
43 std::vector<InlayHint> Result;
44 for (auto &Hint : inlayHints(AST, /*RestrictRange=*/std::nullopt, Opts)) {
45 if (Hint.kind == Kind)
46 Result.push_back(Hint);
47 }
48 return Result;
49}
50
51enum HintSide { Left, Right };
52
53struct ExpectedHint {
54 std::string Label;
55 std::string RangeName;
56 HintSide Side = Left;
57
58 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &Stream,
59 const ExpectedHint &Hint) {
60 return Stream << Hint.Label << "@$" << Hint.RangeName;
61 }
62};
63
64MATCHER_P2(HintMatcher, Expected, Code, llvm::to_string(Expected)) {
65 llvm::StringRef ExpectedView(Expected.Label);
66 std::string ResultLabel = arg.joinLabels();
67 if (ResultLabel != ExpectedView.trim(" ") ||
68 arg.paddingLeft != ExpectedView.starts_with(" ") ||
69 arg.paddingRight != ExpectedView.ends_with(" ")) {
70 *result_listener << "label is '" << ResultLabel << "'";
71 return false;
72 }
73 if (arg.range != Code.range(Expected.RangeName)) {
74 *result_listener << "range is " << llvm::to_string(arg.range) << " but $"
75 << Expected.RangeName << " is "
76 << llvm::to_string(Code.range(Expected.RangeName));
77 return false;
78 }
79 return true;
80}
81
82MATCHER_P(labelIs, Label, "") { return arg.joinLabels() == Label; }
83
84Config noHintsConfig() {
85 Config C;
86 C.InlayHints.Parameters = false;
87 C.InlayHints.DeducedTypes = false;
88 C.InlayHints.Designators = false;
89 C.InlayHints.BlockEnd = false;
90 C.InlayHints.DefaultArguments = false;
91 return C;
92}
93
94template <typename... ExpectedHints>
95void assertHintsWithHeader(InlayHintKind Kind, llvm::StringRef AnnotatedSource,
96 llvm::StringRef HeaderContent, InlayHintOptions Opts,
97 ExpectedHints... Expected) {
98 Annotations Source(AnnotatedSource);
99 TestTU TU = TestTU::withCode(Source.code());
100 TU.ExtraArgs.push_back("-std=c++23");
101 TU.HeaderCode = HeaderContent;
102 auto AST = TU.build();
103
104 EXPECT_THAT(hintsOfKind(AST, Kind, Opts),
105 ElementsAre(HintMatcher(Expected, Source)...));
106 // Sneak in a cross-cutting check that hints are disabled by config.
107 // We'll hit an assertion failure if addInlayHint still gets called.
108 WithContextValue WithCfg(Config::Key, noHintsConfig());
109 EXPECT_THAT(inlayHints(AST, std::nullopt, Opts), IsEmpty());
110}
111
112template <typename... ExpectedHints>
113void assertHints(InlayHintKind Kind, llvm::StringRef AnnotatedSource,
114 InlayHintOptions Opts, ExpectedHints... Expected) {
115 return assertHintsWithHeader(Kind, AnnotatedSource, "", Opts,
116 std::move(Expected)...);
117}
118
119// Hack to allow expression-statements operating on parameter packs in C++14.
120template <typename... T> void ignore(T &&...) {}
121
122template <typename... ExpectedHints>
123void assertParameterHints(llvm::StringRef AnnotatedSource,
124 ExpectedHints... Expected) {
125 ignore(Expected.Side = Left...);
126 assertHints(InlayHintKind::Parameter, AnnotatedSource, DefaultOptsForTests,
127 Expected...);
128}
129
130template <typename... ExpectedHints>
131void assertTypeHints(llvm::StringRef AnnotatedSource,
132 ExpectedHints... Expected) {
133 ignore(Expected.Side = Right...);
134 assertHints(InlayHintKind::Type, AnnotatedSource, DefaultOptsForTests,
135 Expected...);
136}
137
138template <typename... ExpectedHints>
139void assertDesignatorHints(llvm::StringRef AnnotatedSource,
140 ExpectedHints... Expected) {
141 Config Cfg;
142 Cfg.InlayHints.Designators = true;
143 WithContextValue WithCfg(Config::Key, std::move(Cfg));
144 assertHints(InlayHintKind::Designator, AnnotatedSource, DefaultOptsForTests,
145 Expected...);
146}
147
148template <typename... ExpectedHints>
149void assertBlockEndHintsWithOpts(llvm::StringRef AnnotatedSource,
150 InlayHintOptions Opts,
151 ExpectedHints... Expected) {
152 Config Cfg;
153 Cfg.InlayHints.BlockEnd = true;
154 WithContextValue WithCfg(Config::Key, std::move(Cfg));
155 assertHints(InlayHintKind::BlockEnd, AnnotatedSource, Opts, Expected...);
156}
157
158template <typename... ExpectedHints>
159void assertBlockEndHints(llvm::StringRef AnnotatedSource,
160 ExpectedHints... Expected) {
161 assertBlockEndHintsWithOpts(AnnotatedSource, DefaultOptsForTests,
162 Expected...);
163}
164
165TEST(ParameterHints, Smoke) {
166 assertParameterHints(R"cpp(
167 void foo(int param);
168 void bar() {
169 foo($param[[42]]);
170 }
171 )cpp",
172 ExpectedHint{"param: ", "param"});
173}
174
175TEST(ParameterHints, NoName) {
176 // No hint for anonymous parameter.
177 assertParameterHints(R"cpp(
178 void foo(int);
179 void bar() {
180 foo(42);
181 }
182 )cpp");
183}
184
185TEST(ParameterHints, NoNameConstReference) {
186 // No hint for anonymous const l-value ref parameter.
187 assertParameterHints(R"cpp(
188 void foo(const int&);
189 void bar() {
190 foo(42);
191 }
192 )cpp");
193}
194
195TEST(ParameterHints, NoNameReference) {
196 // Reference hint for anonymous l-value ref parameter.
197 assertParameterHints(R"cpp(
198 void foo(int&);
199 void bar() {
200 int i;
201 foo($param[[i]]);
202 }
203 )cpp",
204 ExpectedHint{"&: ", "param"});
205}
206
207TEST(ParameterHints, NoNameRValueReference) {
208 // No reference hint for anonymous r-value ref parameter.
209 assertParameterHints(R"cpp(
210 void foo(int&&);
211 void bar() {
212 foo(42);
213 }
214 )cpp");
215}
216
217TEST(ParameterHints, NoNameVariadicDeclaration) {
218 // No hint for anonymous variadic parameter
219 assertParameterHints(R"cpp(
220 template <typename... Args>
221 void foo(Args&& ...);
222 void bar() {
223 foo(42);
224 }
225 )cpp");
226}
227
228TEST(ParameterHints, NoNameVariadicForwarded) {
229 // No hint for anonymous variadic parameter
230 // This prototype of std::forward is sufficient for clang to recognize it
231 assertParameterHints(R"cpp(
232 namespace std { template <typename T> T&& forward(T&); }
233 void foo(int);
234 template <typename... Args>
235 void bar(Args&&... args) { return foo(std::forward<Args>(args)...); }
236 void baz() {
237 bar(42);
238 }
239 )cpp");
240}
241
242TEST(ParameterHints, NoNameVariadicPlain) {
243 // No hint for anonymous variadic parameter
244 assertParameterHints(R"cpp(
245 void foo(int);
246 template <typename... Args>
247 void bar(Args&&... args) { return foo(args...); }
248 void baz() {
249 bar(42);
250 }
251 )cpp");
252}
253
254TEST(ParameterHints, NameInDefinition) {
255 // Parameter name picked up from definition if necessary.
256 assertParameterHints(R"cpp(
257 void foo(int);
258 void bar() {
259 foo($param[[42]]);
260 }
261 void foo(int param) {};
262 )cpp",
263 ExpectedHint{"param: ", "param"});
264}
265
266TEST(ParameterHints, NamePartiallyInDefinition) {
267 // Parameter name picked up from definition if necessary.
268 assertParameterHints(R"cpp(
269 void foo(int, int b);
270 void bar() {
271 foo($param1[[42]], $param2[[42]]);
272 }
273 void foo(int a, int) {};
274 )cpp",
275 ExpectedHint{"a: ", "param1"},
276 ExpectedHint{"b: ", "param2"});
277}
278
279TEST(ParameterHints, NameInDefinitionVariadic) {
280 // Parameter name picked up from definition in a resolved forwarded parameter.
281 assertParameterHints(R"cpp(
282 void foo(int, int);
283 template <typename... Args>
284 void bar(Args... args) {
285 foo(args...);
286 }
287 void baz() {
288 bar($param1[[42]], $param2[[42]]);
289 }
290 void foo(int a, int b) {};
291 )cpp",
292 ExpectedHint{"a: ", "param1"},
293 ExpectedHint{"b: ", "param2"});
294}
295
296TEST(ParameterHints, NameMismatch) {
297 // Prefer name from declaration.
298 assertParameterHints(R"cpp(
299 void foo(int good);
300 void bar() {
301 foo($good[[42]]);
302 }
303 void foo(int bad) {};
304 )cpp",
305 ExpectedHint{"good: ", "good"});
306}
307
308TEST(ParameterHints, NameConstReference) {
309 // Only name hint for const l-value ref parameter.
310 assertParameterHints(R"cpp(
311 void foo(const int& param);
312 void bar() {
313 foo($param[[42]]);
314 }
315 )cpp",
316 ExpectedHint{"param: ", "param"});
317}
318
319TEST(ParameterHints, NameTypeAliasConstReference) {
320 // Only name hint for const l-value ref parameter via type alias.
321 assertParameterHints(R"cpp(
322 using alias = const int&;
323 void foo(alias param);
324 void bar() {
325 int i;
326 foo($param[[i]]);
327 }
328 )cpp",
329 ExpectedHint{"param: ", "param"});
330}
331
332TEST(ParameterHints, NameReference) {
333 // Reference and name hint for l-value ref parameter.
334 assertParameterHints(R"cpp(
335 void foo(int& param);
336 void bar() {
337 int i;
338 foo($param[[i]]);
339 }
340 )cpp",
341 ExpectedHint{"&param: ", "param"});
342}
343
344TEST(ParameterHints, NameTypeAliasReference) {
345 // Reference and name hint for l-value ref parameter via type alias.
346 assertParameterHints(R"cpp(
347 using alias = int&;
348 void foo(alias param);
349 void bar() {
350 int i;
351 foo($param[[i]]);
352 }
353 )cpp",
354 ExpectedHint{"&param: ", "param"});
355}
356
357TEST(ParameterHints, NameRValueReference) {
358 // Only name hint for r-value ref parameter.
359 assertParameterHints(R"cpp(
360 void foo(int&& param);
361 void bar() {
362 foo($param[[42]]);
363 }
364 )cpp",
365 ExpectedHint{"param: ", "param"});
366}
367
368TEST(ParameterHints, VariadicForwardedConstructor) {
369 // Name hint for variadic parameter using std::forward in a constructor call
370 // This prototype of std::forward is sufficient for clang to recognize it
371 assertParameterHints(R"cpp(
372 namespace std { template <typename T> T&& forward(T&); }
373 struct S { S(int a); };
374 template <typename T, typename... Args>
375 T bar(Args&&... args) { return T{std::forward<Args>(args)...}; }
376 void baz() {
377 int b;
378 bar<S>($param[[b]]);
379 }
380 )cpp",
381 ExpectedHint{"a: ", "param"});
382}
383
384TEST(ParameterHints, VariadicPlainConstructor) {
385 // Name hint for variadic parameter in a constructor call
386 assertParameterHints(R"cpp(
387 struct S { S(int a); };
388 template <typename T, typename... Args>
389 T bar(Args&&... args) { return T{args...}; }
390 void baz() {
391 int b;
392 bar<S>($param[[b]]);
393 }
394 )cpp",
395 ExpectedHint{"a: ", "param"});
396}
397
398TEST(ParameterHints, VariadicForwardedNewConstructor) {
399 // Name hint for variadic parameter using std::forward in a new expression
400 // This prototype of std::forward is sufficient for clang to recognize it
401 assertParameterHints(R"cpp(
402 namespace std { template <typename T> T&& forward(T&); }
403 struct S { S(int a); };
404 template <typename T, typename... Args>
405 T* bar(Args&&... args) { return new T{std::forward<Args>(args)...}; }
406 void baz() {
407 int b;
408 bar<S>($param[[b]]);
409 }
410 )cpp",
411 ExpectedHint{"a: ", "param"});
412}
413
414TEST(ParameterHints, VariadicPlainNewConstructor) {
415 // Name hint for variadic parameter in a new expression
416 assertParameterHints(R"cpp(
417 struct S { S(int a); };
418 template <typename T, typename... Args>
419 T* bar(Args&&... args) { return new T{args...}; }
420 void baz() {
421 int b;
422 bar<S>($param[[b]]);
423 }
424 )cpp",
425 ExpectedHint{"a: ", "param"});
426}
427
428TEST(ParameterHints, VariadicForwarded) {
429 // Name for variadic parameter using std::forward
430 // This prototype of std::forward is sufficient for clang to recognize it
431 assertParameterHints(R"cpp(
432 namespace std { template <typename T> T&& forward(T&); }
433 void foo(int a);
434 template <typename... Args>
435 void bar(Args&&... args) { return foo(std::forward<Args>(args)...); }
436 void baz() {
437 int b;
438 bar($param[[b]]);
439 }
440 )cpp",
441 ExpectedHint{"a: ", "param"});
442}
443
444TEST(ParameterHints, VariadicPlain) {
445 // Name hint for variadic parameter
446 assertParameterHints(R"cpp(
447 void foo(int a);
448 template <typename... Args>
449 void bar(Args&&... args) { return foo(args...); }
450 void baz() {
451 bar($param[[42]]);
452 }
453 )cpp",
454 ExpectedHint{"a: ", "param"});
455}
456
457TEST(ParameterHints, VariadicPlainWithPackFirst) {
458 // Name hint for variadic parameter when the parameter pack is not the last
459 // template parameter
460 assertParameterHints(R"cpp(
461 void foo(int a);
462 template <typename... Args, typename Arg>
463 void bar(Arg, Args&&... args) { return foo(args...); }
464 void baz() {
465 bar(1, $param[[42]]);
466 }
467 )cpp",
468 ExpectedHint{"a: ", "param"});
469}
470
471TEST(ParameterHints, VariadicSplitTwolevel) {
472 // Name for variadic parameter that involves both head and tail parameters to
473 // deal with.
474 // This prototype of std::forward is sufficient for clang to recognize it
475 assertParameterHints(R"cpp(
476 namespace std { template <typename T> T&& forward(T&); }
477 void baz(int, int b, double);
478 template <typename... Args>
479 void foo(int a, Args&&... args) {
480 return baz(1, std::forward<Args>(args)..., 1.0);
481 }
482 template <typename... Args>
483 void bar(Args&&... args) { return foo(std::forward<Args>(args)...); }
484 void bazz() {
485 bar($param1[[32]], $param2[[42]]);
486 }
487 )cpp",
488 ExpectedHint{"a: ", "param1"},
489 ExpectedHint{"b: ", "param2"});
490}
491
492TEST(ParameterHints, VariadicNameFromSpecialization) {
493 // We don't try to resolve forwarding parameters if the function call uses a
494 // specialization.
495 assertParameterHints(R"cpp(
496 void foo(int a);
497 template <typename... Args>
498 void bar(Args... args) {
499 foo(args...);
500 }
501 template <>
502 void bar<int>(int b);
503 void baz() {
504 bar($param[[42]]);
505 }
506 )cpp",
507 ExpectedHint{"b: ", "param"});
508}
509
510TEST(ParameterHints, VariadicNameFromSpecializationRecursive) {
511 // We don't try to resolve forwarding parameters inside a forwarding function
512 // call if that function call uses a specialization.
513 assertParameterHints(R"cpp(
514 void foo2(int a);
515 template <typename... Args>
516 void foo(Args... args) {
517 foo2(args...);
518 }
519 template <typename... Args>
520 void bar(Args... args) {
521 foo(args...);
522 }
523 template <>
524 void foo<int>(int b);
525 void baz() {
526 bar($param[[42]]);
527 }
528 )cpp",
529 ExpectedHint{"b: ", "param"});
530}
531
532TEST(ParameterHints, VariadicOverloaded) {
533 // Name for variadic parameter for an overloaded function with unique number
534 // of parameters.
535 // This prototype of std::forward is sufficient for clang to recognize it
536 assertParameterHints(
537 R"cpp(
538 namespace std { template <typename T> T&& forward(T&); }
539 void baz(int b, int c);
540 void baz(int bb, int cc, int dd);
541 template <typename... Args>
542 void foo(int a, Args&&... args) {
543 return baz(std::forward<Args>(args)...);
544 }
545 template <typename... Args>
546 void bar(Args&&... args) { return foo(std::forward<Args>(args)...); }
547 void bazz() {
548 bar($param1[[32]], $param2[[42]], $param3[[52]]);
549 bar($param4[[1]], $param5[[2]], $param6[[3]], $param7[[4]]);
550 }
551 )cpp",
552 ExpectedHint{"a: ", "param1"}, ExpectedHint{"b: ", "param2"},
553 ExpectedHint{"c: ", "param3"}, ExpectedHint{"a: ", "param4"},
554 ExpectedHint{"bb: ", "param5"}, ExpectedHint{"cc: ", "param6"},
555 ExpectedHint{"dd: ", "param7"});
556}
557
558TEST(ParameterHints, VariadicRecursive) {
559 // make_tuple-like recursive variadic call
560 assertParameterHints(
561 R"cpp(
562 void foo();
563
564 template <typename Head, typename... Tail>
565 void foo(Head head, Tail... tail) {
566 foo(tail...);
567 }
568
569 template <typename... Args>
570 void bar(Args... args) {
571 foo(args...);
572 }
573
574 int main() {
575 bar(1, 2, 3);
576 }
577 )cpp");
578}
579
580TEST(ParameterHints, VariadicVarargs) {
581 // variadic call involving varargs (to make sure we don't crash)
582 assertParameterHints(R"cpp(
583 void foo(int fixed, ...);
584 template <typename... Args>
585 void bar(Args&&... args) {
586 foo(args...);
587 }
588
589 void baz() {
590 bar($fixed[[41]], 42, 43);
591 }
592 )cpp");
593}
594
595TEST(ParameterHints, VariadicTwolevelUnresolved) {
596 // the same setting as VariadicVarargs, only with parameter pack
597 assertParameterHints(R"cpp(
598 template <typename... Args>
599 void foo(int fixed, Args&& ... args);
600 template <typename... Args>
601 void bar(Args&&... args) {
602 foo(args...);
603 }
604
605 void baz() {
606 bar($fixed[[41]], 42, 43);
607 }
608 )cpp",
609 ExpectedHint{"fixed: ", "fixed"});
610}
611
612TEST(ParameterHints, VariadicTwoCalls) {
613 // only the first call using the parameter pack should be picked up
614 assertParameterHints(
615 R"cpp(
616 void f1(int a, int b);
617 void f2(int c, int d);
618
619 bool cond;
620
621 template <typename... Args>
622 void foo(Args... args) {
623 if (cond) {
624 f1(args...);
625 } else {
626 f2(args...);
627 }
628 }
629
630 int main() {
631 foo($param1[[1]], $param2[[2]]);
632 }
633 )cpp",
634 ExpectedHint{"a: ", "param1"}, ExpectedHint{"b: ", "param2"});
635}
636
637TEST(ParameterHints, VariadicInfinite) {
638 // infinite recursion should not break clangd
639 assertParameterHints(
640 R"cpp(
641 template <typename... Args>
642 void foo(Args...);
643
644 template <typename... Args>
645 void bar(Args... args) {
646 foo(args...);
647 }
648
649 template <typename... Args>
650 void foo(Args... args) {
651 bar(args...);
652 }
653
654 int main() {
655 foo(1, 2);
656 }
657 )cpp");
658}
659
660TEST(ParameterHints, VariadicDuplicatePack) {
661 // edge cases with multiple adjacent packs should work
662 assertParameterHints(
663 R"cpp(
664 void foo(int a, int b, int c, int);
665
666 template <typename... Args>
667 void bar(int, Args... args, int d) {
668 foo(args..., d);
669 }
670
671 template <typename... Args>
672 void baz(Args... args, Args... args2) {
673 bar<Args..., int>(1, args..., args2...);
674 }
675
676 int main() {
677 baz<int, int>($p1[[1]], $p2[[2]], $p3[[3]], $p4[[4]]);
678 }
679 )cpp",
680 ExpectedHint{"a: ", "p1"}, ExpectedHint{"b: ", "p2"},
681 ExpectedHint{"c: ", "p3"}, ExpectedHint{"d: ", "p4"});
682}
683
684TEST(ParameterHints, VariadicEmplace) {
685 // emplace-like calls should forward constructor parameters
686 // This prototype of std::forward is sufficient for clang to recognize it
687 assertParameterHints(
688 R"cpp(
689 namespace std { template <typename T> T&& forward(T&); }
690 using size_t = decltype(sizeof(0));
691 void *operator new(size_t, void *);
692 struct S {
693 S(int A);
694 S(int B, int C);
695 };
696 struct alloc {
697 template <typename T>
698 T* allocate();
699 template <typename T, typename... Args>
700 void construct(T* ptr, Args&&... args) {
701 ::new ((void*)ptr) T{std::forward<Args>(args)...};
702 }
703 };
704 template <typename T>
705 struct container {
706 template <typename... Args>
707 void emplace(Args&&... args) {
708 alloc a;
709 auto ptr = a.template allocate<T>();
710 a.construct(ptr, std::forward<Args>(args)...);
711 }
712 };
713 void foo() {
714 container<S> c;
715 c.emplace($param1[[1]]);
716 c.emplace($param2[[2]], $param3[[3]]);
717 }
718 )cpp",
719 ExpectedHint{"A: ", "param1"}, ExpectedHint{"B: ", "param2"},
720 ExpectedHint{"C: ", "param3"});
721}
722
723TEST(ParameterHints, VariadicReferenceHint) {
724 assertParameterHints(R"cpp(
725 void foo(int&);
726 template <typename... Args>
727 void bar(Args... args) { return foo(args...); }
728 void baz() {
729 int a;
730 bar(a);
731 bar(1);
732 }
733 )cpp");
734}
735
736TEST(ParameterHints, VariadicReferenceHintForwardingRef) {
737 assertParameterHints(R"cpp(
738 void foo(int&);
739 template <typename... Args>
740 void bar(Args&&... args) { return foo(args...); }
741 void baz() {
742 int a;
743 bar($param[[a]]);
744 bar(1);
745 }
746 )cpp",
747 ExpectedHint{"&: ", "param"});
748}
749
750TEST(ParameterHints, VariadicReferenceHintForwardingRefStdForward) {
751 assertParameterHints(R"cpp(
752 namespace std { template <typename T> T&& forward(T&); }
753 void foo(int&);
754 template <typename... Args>
755 void bar(Args&&... args) { return foo(std::forward<Args>(args)...); }
756 void baz() {
757 int a;
758 bar($param[[a]]);
759 }
760 )cpp",
761 ExpectedHint{"&: ", "param"});
762}
763
764TEST(ParameterHints, VariadicNoReferenceHintForwardingRefStdForward) {
765 assertParameterHints(R"cpp(
766 namespace std { template <typename T> T&& forward(T&); }
767 void foo(int);
768 template <typename... Args>
769 void bar(Args&&... args) { return foo(std::forward<Args>(args)...); }
770 void baz() {
771 int a;
772 bar(a);
773 bar(1);
774 }
775 )cpp");
776}
777
778TEST(ParameterHints, VariadicNoReferenceHintUnresolvedForward) {
779 assertParameterHints(R"cpp(
780 template <typename... Args>
781 void foo(Args&&... args);
782 void bar() {
783 int a;
784 foo(a);
785 }
786 )cpp");
787}
788
789TEST(ParameterHints, MatchingNameVariadicForwarded) {
790 // No name hint for variadic parameter with matching name
791 // This prototype of std::forward is sufficient for clang to recognize it
792 assertParameterHints(R"cpp(
793 namespace std { template <typename T> T&& forward(T&); }
794 void foo(int a);
795 template <typename... Args>
796 void bar(Args&&... args) { return foo(std::forward<Args>(args)...); }
797 void baz() {
798 int a;
799 bar(a);
800 }
801 )cpp");
802}
803
804TEST(ParameterHints, MatchingNameVariadicPlain) {
805 // No name hint for variadic parameter with matching name
806 assertParameterHints(R"cpp(
807 void foo(int a);
808 template <typename... Args>
809 void bar(Args&&... args) { return foo(args...); }
810 void baz() {
811 int a;
812 bar(a);
813 }
814 )cpp");
815}
816
817TEST(ParameterHints, Operator) {
818 // No hint for operator call with operator syntax.
819 assertParameterHints(R"cpp(
820 struct S {};
821 void operator+(S lhs, S rhs);
822 void bar() {
823 S a, b;
824 a + b;
825 }
826 )cpp");
827}
828
829TEST(ParameterHints, FunctionCallOperator) {
830 assertParameterHints(R"cpp(
831 struct W {
832 void operator()(int x);
833 };
834 struct S : W {
835 using W::operator();
836 static void operator()(int x, int y);
837 };
838 void bar() {
839 auto l1 = [](int x) {};
840 auto l2 = [](int x) static {};
841
842 S s;
843 s($1[[1]]);
844 s.operator()($2[[1]]);
845 s.operator()($3[[1]], $4[[2]]);
846 S::operator()($5[[1]], $6[[2]]);
847
848 l1($7[[1]]);
849 l1.operator()($8[[1]]);
850 l2($9[[1]]);
851 l2.operator()($10[[1]]);
852
853 void (*ptr)(int a, int b) = &S::operator();
854 ptr($11[[1]], $12[[2]]);
855 }
856 )cpp",
857 ExpectedHint{"x: ", "1"}, ExpectedHint{"x: ", "2"},
858 ExpectedHint{"x: ", "3"}, ExpectedHint{"y: ", "4"},
859 ExpectedHint{"x: ", "5"}, ExpectedHint{"y: ", "6"},
860 ExpectedHint{"x: ", "7"}, ExpectedHint{"x: ", "8"},
861 ExpectedHint{"x: ", "9"}, ExpectedHint{"x: ", "10"},
862 ExpectedHint{"a: ", "11"}, ExpectedHint{"b: ", "12"});
863}
864
865TEST(ParameterHints, DeducingThis) {
866 assertParameterHints(R"cpp(
867 struct S {
868 template <typename This>
869 auto operator()(this This &&Self, int Param) {
870 return 42;
871 }
872
873 auto function(this auto &Self, int Param) {
874 return Param;
875 }
876 };
877 void work() {
878 S s;
879 s($1[[42]]);
880 s.function($2[[42]]);
881 S()($3[[42]]);
882 auto lambda = [](this auto &Self, char C) -> void {
883 return Self(C);
884 };
885 lambda($4[['A']]);
886 }
887 )cpp",
888 ExpectedHint{"Param: ", "1"},
889 ExpectedHint{"Param: ", "2"},
890 ExpectedHint{"Param: ", "3"}, ExpectedHint{"C: ", "4"});
891}
892
893TEST(ParameterHints, DependentDeducingThis) {
894 assertParameterHints(R"cpp(
895 template <typename T>
896 struct S {
897 void f1(this S& obj);
898 void f2(this S& obj, int x, int y);
899 void g(S s) {
900 s.f1(); // no crash
901 s.f2($x[[42]], $y[[43]]);
902 }
903 };
904 )cpp",
905 ExpectedHint{"x: ", "x"}, ExpectedHint{"y: ", "y"});
906}
907
908TEST(ParameterHints, Macros) {
909 // Handling of macros depends on where the call's argument list comes from.
910
911 // If it comes from a macro definition, there's nothing to hint
912 // at the invocation site.
913 assertParameterHints(R"cpp(
914 void foo(int param);
915 #define ExpandsToCall() foo(42)
916 void bar() {
917 ExpandsToCall();
918 }
919 )cpp");
920
921 // The argument expression being a macro invocation shouldn't interfere
922 // with hinting.
923 assertParameterHints(R"cpp(
924 #define PI 3.14
925 void foo(double param);
926 void bar() {
927 foo($param[[PI]]);
928 }
929 )cpp",
930 ExpectedHint{"param: ", "param"});
931
932 // If the whole argument list comes from a macro parameter, hint it.
933 assertParameterHints(R"cpp(
934 void abort();
935 #define ASSERT(expr) if (!expr) abort()
936 int foo(int param);
937 void bar() {
938 ASSERT(foo($param[[42]]) == 0);
939 }
940 )cpp",
941 ExpectedHint{"param: ", "param"});
942
943 // If the macro expands to multiple arguments, don't hint it.
944 assertParameterHints(R"cpp(
945 void foo(double x, double y);
946 #define CONSTANTS 3.14, 2.72
947 void bar() {
948 foo(CONSTANTS);
949 }
950 )cpp");
951}
952
953TEST(ParameterHints, ConstructorParens) {
954 assertParameterHints(R"cpp(
955 struct S {
956 S(int param);
957 };
958 void bar() {
959 S obj($param[[42]]);
960 }
961 )cpp",
962 ExpectedHint{"param: ", "param"});
963}
964
965TEST(ParameterHints, ConstructorBraces) {
966 assertParameterHints(R"cpp(
967 struct S {
968 S(int param);
969 };
970 void bar() {
971 S obj{$param[[42]]};
972 }
973 )cpp",
974 ExpectedHint{"param: ", "param"});
975}
976
977TEST(ParameterHints, ConstructorStdInitList) {
978 // Do not show hints for std::initializer_list constructors.
979 assertParameterHints(R"cpp(
980 namespace std {
981 template <typename E> class initializer_list { const E *a, *b; };
982 }
983 struct S {
984 S(std::initializer_list<int> param);
985 };
986 void bar() {
987 S obj{42, 43};
988 }
989 )cpp");
990}
991
992TEST(ParameterHints, MemberInit) {
993 assertParameterHints(R"cpp(
994 struct S {
995 S(int param);
996 };
997 struct T {
998 S member;
999 T() : member($param[[42]]) {}
1000 };
1001 )cpp",
1002 ExpectedHint{"param: ", "param"});
1003}
1004
1005TEST(ParameterHints, ImplicitConstructor) {
1006 assertParameterHints(R"cpp(
1007 struct S {
1008 S(int param);
1009 };
1010 void bar(S);
1011 S foo() {
1012 // Do not show hint for implicit constructor call in argument.
1013 bar(42);
1014 // Do not show hint for implicit constructor call in return.
1015 return 42;
1016 }
1017 )cpp");
1018}
1019
1020TEST(ParameterHints, FunctionPointer) {
1021 assertParameterHints(
1022 R"cpp(
1023 void (*f1)(int param);
1024 void (__stdcall *f2)(int param);
1025 using f3_t = void(*)(int param);
1026 f3_t f3;
1027 using f4_t = void(__stdcall *)(int param);
1028 f4_t f4;
1029 __attribute__((noreturn)) f4_t f5;
1030 void bar() {
1031 f1($f1[[42]]);
1032 f2($f2[[42]]);
1033 f3($f3[[42]]);
1034 f4($f4[[42]]);
1035 // This one runs into an edge case in clang's type model
1036 // and we can't extract the parameter name. But at least
1037 // we shouldn't crash.
1038 f5(42);
1039 }
1040 )cpp",
1041 ExpectedHint{"param: ", "f1"}, ExpectedHint{"param: ", "f2"},
1042 ExpectedHint{"param: ", "f3"}, ExpectedHint{"param: ", "f4"});
1043}
1044
1045TEST(ParameterHints, ArgMatchesParam) {
1046 assertParameterHints(R"cpp(
1047 void foo(int param);
1048 struct S {
1049 static const int param = 42;
1050 };
1051 void bar() {
1052 int param = 42;
1053 // Do not show redundant "param: param".
1054 foo(param);
1055 // But show it if the argument is qualified.
1056 foo($param[[S::param]]);
1057 }
1058 struct A {
1059 int param;
1060 void bar() {
1061 // Do not show "param: param" for member-expr.
1062 foo(param);
1063 }
1064 };
1065 )cpp",
1066 ExpectedHint{"param: ", "param"});
1067}
1068
1069TEST(ParameterHints, ArgMatchesParamReference) {
1070 assertParameterHints(R"cpp(
1071 void foo(int& param);
1072 void foo2(const int& param);
1073 void bar() {
1074 int param;
1075 // show reference hint on mutable reference
1076 foo($param[[param]]);
1077 // but not on const reference
1078 foo2(param);
1079 }
1080 )cpp",
1081 ExpectedHint{"&: ", "param"});
1082}
1083
1084TEST(ParameterHints, LeadingUnderscore) {
1085 assertParameterHints(R"cpp(
1086 void foo(int p1, int _p2, int __p3);
1087 void bar() {
1088 foo($p1[[41]], $p2[[42]], $p3[[43]]);
1089 }
1090 )cpp",
1091 ExpectedHint{"p1: ", "p1"}, ExpectedHint{"p2: ", "p2"},
1092 ExpectedHint{"p3: ", "p3"});
1093}
1094
1095TEST(ParameterHints, DependentCalls) {
1096 assertParameterHints(R"cpp(
1097 template <typename T>
1098 void nonmember(T par1);
1099
1100 template <typename T>
1101 struct A {
1102 void member(T par2);
1103 static void static_member(T par3);
1104 };
1105
1106 void overload(int anInt);
1107 void overload(double aDouble);
1108
1109 template <typename T>
1110 struct S {
1111 void bar(A<T> a, T t) {
1112 nonmember($par1[[t]]);
1113 a.member($par2[[t]]);
1114 A<T>::static_member($par3[[t]]);
1115 // We don't want to arbitrarily pick between
1116 // "anInt" or "aDouble", so just show no hint.
1117 overload(T{});
1118 }
1119 };
1120 )cpp",
1121 ExpectedHint{"par1: ", "par1"},
1122 ExpectedHint{"par2: ", "par2"},
1123 ExpectedHint{"par3: ", "par3"});
1124}
1125
1126TEST(ParameterHints, VariadicFunction) {
1127 assertParameterHints(R"cpp(
1128 template <typename... T>
1129 void foo(int fixed, T... variadic);
1130
1131 void bar() {
1132 foo($fixed[[41]], 42, 43);
1133 }
1134 )cpp",
1135 ExpectedHint{"fixed: ", "fixed"});
1136}
1137
1138TEST(ParameterHints, VarargsFunction) {
1139 assertParameterHints(R"cpp(
1140 void foo(int fixed, ...);
1141
1142 void bar() {
1143 foo($fixed[[41]], 42, 43);
1144 }
1145 )cpp",
1146 ExpectedHint{"fixed: ", "fixed"});
1147}
1148
1149TEST(ParameterHints, CopyOrMoveConstructor) {
1150 // Do not show hint for parameter of copy or move constructor.
1151 assertParameterHints(R"cpp(
1152 struct S {
1153 S();
1154 S(const S& other);
1155 S(S&& other);
1156 };
1157 void bar() {
1158 S a;
1159 S b(a); // copy
1160 S c(S()); // move
1161 }
1162 )cpp");
1163}
1164
1165TEST(ParameterHints, UserDefinedLiteral) {
1166 // Do not hint call to user-defined literal operator.
1167 assertParameterHints(R"cpp(
1168 long double operator"" _w(long double param);
1169 void bar() {
1170 1.2_w;
1171 }
1172 )cpp");
1173}
1174
1175TEST(ParameterHints, ParamNameComment) {
1176 // Do not hint an argument which already has a comment
1177 // with the parameter name preceding it.
1178 assertParameterHints(R"cpp(
1179 void foo(int param);
1180 void bar() {
1181 foo(/*param*/42);
1182 foo( /* param = */ 42);
1183#define X 42
1184#define Y X
1185#define Z(...) Y
1186 foo(/*param=*/Z(a));
1187 foo($macro[[Z(a)]]);
1188 foo(/* the answer */$param[[42]]);
1189 }
1190 )cpp",
1191 ExpectedHint{"param: ", "macro"},
1192 ExpectedHint{"param: ", "param"});
1193}
1194
1195TEST(ParameterHints, SetterFunctions) {
1196 assertParameterHints(R"cpp(
1197 struct S {
1198 void setParent(S* parent);
1199 void set_parent(S* parent);
1200 void setTimeout(int timeoutMillis);
1201 void setTimeoutMillis(int timeout_millis);
1202 };
1203 void bar() {
1204 S s;
1205 // Parameter name matches setter name - omit hint.
1206 s.setParent(nullptr);
1207 // Support snake_case
1208 s.set_parent(nullptr);
1209 // Parameter name may contain extra info - show hint.
1210 s.setTimeout($timeoutMillis[[120]]);
1211 // FIXME: Ideally we'd want to omit this.
1212 s.setTimeoutMillis($timeout_millis[[120]]);
1213 }
1214 )cpp",
1215 ExpectedHint{"timeoutMillis: ", "timeoutMillis"},
1216 ExpectedHint{"timeout_millis: ", "timeout_millis"});
1217}
1218
1219TEST(ParameterHints, BuiltinFunctions) {
1220 // This prototype of std::forward is sufficient for clang to recognize it
1221 assertParameterHints(R"cpp(
1222 namespace std { template <typename T> T&& forward(T&); }
1223 void foo() {
1224 int i;
1225 std::forward(i);
1226 }
1227 )cpp");
1228}
1229
1230TEST(ParameterHints, IncludeAtNonGlobalScope) {
1231 Annotations FooInc(R"cpp(
1232 void bar() { foo(42); }
1233 )cpp");
1234 Annotations FooCC(R"cpp(
1235 struct S {
1236 void foo(int param);
1237 #include "foo.inc"
1238 };
1239 )cpp");
1240
1241 TestWorkspace Workspace;
1242 Workspace.addSource("foo.inc", FooInc.code());
1243 Workspace.addMainFile("foo.cc", FooCC.code());
1244
1245 auto AST = Workspace.openFile("foo.cc");
1246 ASSERT_TRUE(bool(AST));
1247
1248 // Ensure the hint for the call in foo.inc is NOT materialized in foo.cc.
1249 EXPECT_EQ(
1250 hintsOfKind(*AST, InlayHintKind::Parameter, DefaultOptsForTests).size(),
1251 0u);
1252}
1253
1254TEST(ParameterHints, Issue220359_NoCrash) {
1255 assertParameterHints(R"cpp(
1256 struct S {
1257 S(int, ...);
1258 };
1259 template <typename... Args>
1260 void f(Args... args) {
1261 S s(1, args...);
1262 }
1263 void c() {
1264 f(2);
1265 }
1266 )cpp");
1267}
1268
1269TEST(TypeHints, Smoke) {
1270 assertTypeHints(R"cpp(
1271 auto $waldo[[waldo]] = 42;
1272 )cpp",
1273 ExpectedHint{": int", "waldo"});
1274}
1275
1276TEST(TypeHints, Decorations) {
1277 assertTypeHints(R"cpp(
1278 int x = 42;
1279 auto* $var1[[var1]] = &x;
1280 auto&& $var2[[var2]] = x;
1281 const auto& $var3[[var3]] = x;
1282 )cpp",
1283 ExpectedHint{": int *", "var1"},
1284 ExpectedHint{": int &", "var2"},
1285 ExpectedHint{": const int &", "var3"});
1286}
1287
1288TEST(TypeHints, DecltypeAuto) {
1289 assertTypeHints(R"cpp(
1290 int x = 42;
1291 int& y = x;
1292 decltype(auto) $z[[z]] = y;
1293 )cpp",
1294 ExpectedHint{": int &", "z"});
1295}
1296
1297TEST(TypeHints, NoQualifiers) {
1298 assertTypeHints(R"cpp(
1299 namespace A {
1300 namespace B {
1301 struct S1 {};
1302 S1 foo();
1303 auto $x[[x]] = foo();
1304
1305 struct S2 {
1306 template <typename T>
1307 struct Inner {};
1308 };
1309 S2::Inner<int> bar();
1310 auto $y[[y]] = bar();
1311 }
1312 }
1313 )cpp",
1314 ExpectedHint{": S1", "x"}, ExpectedHint{": Inner<int>", "y"});
1315}
1316
1317TEST(TypeHints, Lambda) {
1318 // Do not print something overly verbose like the lambda's location.
1319 // Show hints for init-captures (but not regular captures).
1320 assertTypeHints(R"cpp(
1321 void f() {
1322 int cap = 42;
1323 auto $L[[L]] = [cap, $init[[init]] = 1 + 1](int a$ret[[)]] {
1324 return a + cap + init;
1325 };
1326 }
1327 )cpp",
1328 ExpectedHint{": (lambda)", "L"},
1329 ExpectedHint{": int", "init"}, ExpectedHint{"-> int", "ret"});
1330
1331 // Lambda return hint shown even if no param list.
1332 // (The digraph :> is just a ] that doesn't conflict with the annotations).
1333 assertTypeHints("auto $L[[x]] = <:$ret[[:>]]{return 42;};",
1334 ExpectedHint{": (lambda)", "L"},
1335 ExpectedHint{"-> int", "ret"});
1336}
1337
1338// Structured bindings tests.
1339// Note, we hint the individual bindings, not the aggregate.
1340
1341TEST(TypeHints, StructuredBindings_PublicStruct) {
1342 assertTypeHints(R"cpp(
1343 // Struct with public fields.
1344 struct Point {
1345 int x;
1346 int y;
1347 };
1348 Point foo();
1349 auto [$x[[x]], $y[[y]]] = foo();
1350 )cpp",
1351 ExpectedHint{": int", "x"}, ExpectedHint{": int", "y"});
1352}
1353
1354TEST(TypeHints, StructuredBindings_Array) {
1355 assertTypeHints(R"cpp(
1356 int arr[2];
1357 auto [$x[[x]], $y[[y]]] = arr;
1358 )cpp",
1359 ExpectedHint{": int", "x"}, ExpectedHint{": int", "y"});
1360}
1361
1362TEST(TypeHints, StructuredBindings_TupleLike) {
1363 assertTypeHints(R"cpp(
1364 // Tuple-like type.
1365 struct IntPair {
1366 int a;
1367 int b;
1368 };
1369 namespace std {
1370 template <typename T>
1371 struct tuple_size {};
1372 template <>
1373 struct tuple_size<IntPair> {
1374 constexpr static unsigned value = 2;
1375 };
1376 template <unsigned I, typename T>
1377 struct tuple_element {};
1378 template <unsigned I>
1379 struct tuple_element<I, IntPair> {
1380 using type = int;
1381 };
1382 }
1383 template <unsigned I>
1384 int get(const IntPair& p) {
1385 if constexpr (I == 0) {
1386 return p.a;
1387 } else if constexpr (I == 1) {
1388 return p.b;
1389 }
1390 }
1391 IntPair bar();
1392 auto [$x[[x]], $y[[y]]] = bar();
1393 )cpp",
1394 ExpectedHint{": int", "x"}, ExpectedHint{": int", "y"});
1395}
1396
1397TEST(TypeHints, StructuredBindings_NoInitializer) {
1398 assertTypeHints(R"cpp(
1399 // No initializer (ill-formed).
1400 // Do not show useless "NULL TYPE" hint.
1401 auto [x, y]; /*error-ok*/
1402 )cpp");
1403}
1404
1405TEST(TypeHints, InvalidType) {
1406 assertTypeHints(R"cpp(
1407 auto x = (unknown_type)42; /*error-ok*/
1408 auto *y = (unknown_ptr)nullptr;
1409 )cpp");
1410}
1411
1412TEST(TypeHints, ReturnTypeDeduction) {
1413 assertTypeHints(
1414 R"cpp(
1415 auto f1(int x$ret1a[[)]]; // Hint forward declaration too
1416 auto f1(int x$ret1b[[)]] { return x + 1; }
1417
1418 // Include pointer operators in hint
1419 int s;
1420 auto& f2($ret2[[)]] { return s; }
1421
1422 // Do not hint `auto` for trailing return type.
1423 auto f3() -> int;
1424
1425 // Do not hint when a trailing return type is specified.
1426 auto f4() -> auto* { return "foo"; }
1427
1428 auto f5($noreturn[[)]] {}
1429
1430 // `auto` conversion operator
1431 struct A {
1432 operator auto($retConv[[)]] { return 42; }
1433 };
1434
1435 // FIXME: Dependent types do not work yet.
1436 template <typename T>
1437 struct S {
1438 auto method() { return T(); }
1439 };
1440 )cpp",
1441 ExpectedHint{"-> int", "ret1a"}, ExpectedHint{"-> int", "ret1b"},
1442 ExpectedHint{"-> int &", "ret2"}, ExpectedHint{"-> void", "noreturn"},
1443 ExpectedHint{"-> int", "retConv"});
1444}
1445
1446TEST(TypeHints, DependentType) {
1447 assertTypeHints(R"cpp(
1448 template <typename T>
1449 void foo(T arg) {
1450 // The hint would just be "auto" and we can't do any better.
1451 auto var1 = arg.method();
1452 // FIXME: It would be nice to show "T" as the hint.
1453 auto $var2[[var2]] = arg;
1454 }
1455
1456 template <typename T>
1457 void bar(T arg) {
1458 auto [a, b] = arg;
1459 }
1460 )cpp",
1461 ExpectedHint{": T", "var2"});
1462}
1463
1464TEST(TypeHints, LongTypeName) {
1465 assertTypeHints(R"cpp(
1466 template <typename, typename, typename>
1467 struct A {};
1468 struct MultipleWords {};
1469 A<MultipleWords, MultipleWords, MultipleWords> foo();
1470 // Omit type hint past a certain length (currently 32)
1471 auto var = foo();
1472 )cpp");
1473
1474 Config Cfg;
1475 Cfg.InlayHints.TypeNameLimit = 0;
1476 WithContextValue WithCfg(Config::Key, std::move(Cfg));
1477
1478 assertTypeHints(
1479 R"cpp(
1480 template <typename, typename, typename>
1481 struct A {};
1482 struct MultipleWords {};
1483 A<MultipleWords, MultipleWords, MultipleWords> foo();
1484 // Should have type hint with TypeNameLimit = 0
1485 auto $var[[var]] = foo();
1486 )cpp",
1487 ExpectedHint{": A<MultipleWords, MultipleWords, MultipleWords>", "var"});
1488}
1489
1490TEST(TypeHints, DefaultTemplateArgs) {
1491 assertTypeHints(R"cpp(
1492 template <typename, typename = int>
1493 struct A {};
1494 A<float> foo();
1495 auto $var[[var]] = foo();
1496 A<float> bar[1];
1497 auto [$binding[[value]]] = bar;
1498 )cpp",
1499 ExpectedHint{": A<float>", "var"},
1500 ExpectedHint{": A<float>", "binding"});
1501}
1502
1503TEST(DefaultArguments, Smoke) {
1504 Config Cfg;
1506 true; // To test interplay of parameters and default parameters
1507 Cfg.InlayHints.DeducedTypes = false;
1508 Cfg.InlayHints.Designators = false;
1509 Cfg.InlayHints.BlockEnd = false;
1510
1511 Cfg.InlayHints.DefaultArguments = true;
1512 WithContextValue WithCfg(Config::Key, std::move(Cfg));
1513
1514 const auto *Code = R"cpp(
1515 int foo(int A = 4) { return A; }
1516 int bar(int A, int B = 1, bool C = foo($default1[[)]]) { return A; }
1517 int A = bar($explicit[[2]]$default2[[)]];
1518
1519 void baz(int = 5) { if (false) baz($unnamed[[)]]; };
1520 )cpp";
1521
1522 assertHints(InlayHintKind::DefaultArgument, Code, DefaultOptsForTests,
1523 ExpectedHint{"A: 4", "default1", Left},
1524 ExpectedHint{", B: 1, C: foo()", "default2", Left},
1525 ExpectedHint{"5", "unnamed", Left});
1526
1527 assertHints(InlayHintKind::Parameter, Code, DefaultOptsForTests,
1528 ExpectedHint{"A: ", "explicit", Left});
1529}
1530
1531TEST(DefaultArguments, WithoutParameterNames) {
1532 Config Cfg;
1533 Cfg.InlayHints.Parameters = false; // To test just default args this time
1534 Cfg.InlayHints.DeducedTypes = false;
1535 Cfg.InlayHints.Designators = false;
1536 Cfg.InlayHints.BlockEnd = false;
1537
1538 Cfg.InlayHints.DefaultArguments = true;
1539 WithContextValue WithCfg(Config::Key, std::move(Cfg));
1540
1541 const auto *Code = R"cpp(
1542 struct Baz {
1543 Baz(float a = 3 //
1544 + 2);
1545 };
1546 struct Foo {
1547 Foo(int, Baz baz = //
1548 Baz{$abbreviated[[}]]
1549
1550 //
1551 ) {}
1552 };
1553
1554 int main() {
1555 Foo foo1(1$paren[[)]];
1556 Foo foo2{2$brace1[[}]];
1557 Foo foo3 = {3$brace2[[}]];
1558 auto foo4 = Foo{4$brace3[[}]];
1559 }
1560 )cpp";
1561
1562 assertHints(InlayHintKind::DefaultArgument, Code, DefaultOptsForTests,
1563 ExpectedHint{"...", "abbreviated", Left},
1564 ExpectedHint{", Baz{}", "paren", Left},
1565 ExpectedHint{", Baz{}", "brace1", Left},
1566 ExpectedHint{", Baz{}", "brace2", Left},
1567 ExpectedHint{", Baz{}", "brace3", Left});
1568
1569 assertHints(InlayHintKind::Parameter, Code, DefaultOptsForTests);
1570}
1571
1572TEST(TypeHints, Deduplication) {
1573 assertTypeHints(R"cpp(
1574 template <typename T>
1575 void foo() {
1576 auto $var[[var]] = 42;
1577 }
1578 template void foo<int>();
1579 template void foo<float>();
1580 )cpp",
1581 ExpectedHint{": int", "var"});
1582}
1583
1584TEST(TypeHints, SinglyInstantiatedTemplate) {
1585 assertTypeHints(R"cpp(
1586 auto $lambda[[x]] = [](auto *$param[[y]], auto) { return 42; };
1587 int m = x("foo", 3);
1588 )cpp",
1589 ExpectedHint{": (lambda)", "lambda"},
1590 ExpectedHint{": const char *", "param"});
1591
1592 // No hint for packs, or auto params following packs
1593 assertTypeHints(R"cpp(
1594 int x(auto $a[[a]], auto... b, auto c) { return 42; }
1595 int m = x<void*, char, float>(nullptr, 'c', 2.0, 2);
1596 )cpp",
1597 ExpectedHint{": void *", "a"});
1598}
1599
1600TEST(TypeHints, Aliased) {
1601 // Check that we don't crash for functions without a FunctionTypeLoc.
1602 // https://github.com/clangd/clangd/issues/1140
1603 TestTU TU = TestTU::withCode("void foo(void){} extern typeof(foo) foo;");
1604 TU.ExtraArgs.push_back("-xc");
1605 auto AST = TU.build();
1606
1607 EXPECT_THAT(hintsOfKind(AST, InlayHintKind::Type, DefaultOptsForTests),
1608 IsEmpty());
1609}
1610
1611TEST(TypeHints, CallingConvention) {
1612 // Check that we don't crash for lambdas with an annotation
1613 // https://github.com/clangd/clangd/issues/2223
1614 Annotations Source(R"cpp(
1615 void test() {
1616 []($lambda[[)]]__cdecl {};
1617 }
1618 )cpp");
1619 TestTU TU = TestTU::withCode(Source.code());
1620 TU.ExtraArgs.push_back("--target=x86_64-w64-mingw32");
1621 TU.PredefineMacros = true; // for the __cdecl
1622 auto AST = TU.build();
1623
1624 EXPECT_THAT(
1625 hintsOfKind(AST, InlayHintKind::Type, DefaultOptsForTests),
1626 ElementsAre(HintMatcher(ExpectedHint{"-> void", "lambda"}, Source)));
1627}
1628
1629TEST(TypeHints, Decltype) {
1630 assertTypeHints(R"cpp(
1631 $a[[decltype(0)]] a;
1632 $b[[decltype(a)]] b;
1633 const $c[[decltype(0)]] &c = b;
1634
1635 // Don't show for dependent type
1636 template <class T>
1637 constexpr decltype(T{}) d;
1638
1639 $e[[decltype(0)]] e();
1640 auto f() -> $f[[decltype(0)]];
1641
1642 template <class, class> struct Foo;
1643 using G = Foo<$g[[decltype(0)]], float>;
1644
1645 auto $h[[h]] = $i[[decltype(0)]]{};
1646
1647 // No crash
1648 /* error-ok */
1649 auto $j[[s]];
1650 )cpp",
1651 ExpectedHint{": int", "a"}, ExpectedHint{": int", "b"},
1652 ExpectedHint{": int", "c"}, ExpectedHint{": int", "e"},
1653 ExpectedHint{": int", "f"}, ExpectedHint{": int", "g"},
1654 ExpectedHint{": int", "h"}, ExpectedHint{": int", "i"});
1655}
1656
1657TEST(TypeHints, SubstTemplateParameterAliases) {
1658 llvm::StringRef Header = R"cpp(
1659 template <class T> struct allocator {};
1660
1661 template <class T, class A>
1662 struct vector_base {
1663 using pointer = T*;
1664 };
1665
1666 template <class T, class A>
1667 struct internal_iterator_type_template_we_dont_expect {};
1668
1669 struct my_iterator {};
1670
1671 template <class T, class A = allocator<T>>
1672 struct vector : vector_base<T, A> {
1673 using base = vector_base<T, A>;
1674 typedef T value_type;
1675 typedef base::pointer pointer;
1676 using allocator_type = A;
1677 using size_type = int;
1678 using iterator = internal_iterator_type_template_we_dont_expect<T, A>;
1679 using non_template_iterator = my_iterator;
1680
1681 value_type& operator[](int index) { return elements[index]; }
1682 const value_type& at(int index) const { return elements[index]; }
1683 pointer data() { return &elements[0]; }
1684 allocator_type get_allocator() { return A(); }
1685 size_type size() const { return 10; }
1686 iterator begin() { return iterator(); }
1687 non_template_iterator end() { return non_template_iterator(); }
1688
1689 T elements[10];
1690 };
1691 )cpp";
1692
1693 llvm::StringRef VectorIntPtr = R"cpp(
1694 vector<int *> array;
1695 auto $no_modifier[[x]] = array[3];
1696 auto* $ptr_modifier[[ptr]] = &array[3];
1697 auto& $ref_modifier[[ref]] = array[3];
1698 auto& $at[[immutable]] = array.at(3);
1699
1700 auto $data[[data]] = array.data();
1701 auto $allocator[[alloc]] = array.get_allocator();
1702 auto $size[[size]] = array.size();
1703 auto $begin[[begin]] = array.begin();
1704 auto $end[[end]] = array.end();
1705 )cpp";
1706
1707 assertHintsWithHeader(
1708 InlayHintKind::Type, VectorIntPtr, Header, DefaultOptsForTests,
1709 ExpectedHint{": int *", "no_modifier"},
1710 ExpectedHint{": int **", "ptr_modifier"},
1711 ExpectedHint{": int *&", "ref_modifier"},
1712 ExpectedHint{": int *const &", "at"}, ExpectedHint{": int **", "data"},
1713 ExpectedHint{": allocator<int *>", "allocator"},
1714 ExpectedHint{": size_type", "size"}, ExpectedHint{": iterator", "begin"},
1715 ExpectedHint{": non_template_iterator", "end"});
1716
1717 llvm::StringRef VectorInt = R"cpp(
1718 vector<int> array;
1719 auto $no_modifier[[by_value]] = array[3];
1720 auto* $ptr_modifier[[ptr]] = &array[3];
1721 auto& $ref_modifier[[ref]] = array[3];
1722 auto& $at[[immutable]] = array.at(3);
1723
1724 auto $data[[data]] = array.data();
1725 auto $allocator[[alloc]] = array.get_allocator();
1726 auto $size[[size]] = array.size();
1727 auto $begin[[begin]] = array.begin();
1728 auto $end[[end]] = array.end();
1729 )cpp";
1730
1731 assertHintsWithHeader(
1732 InlayHintKind::Type, VectorInt, Header, DefaultOptsForTests,
1733 ExpectedHint{": int", "no_modifier"},
1734 ExpectedHint{": int *", "ptr_modifier"},
1735 ExpectedHint{": int &", "ref_modifier"},
1736 ExpectedHint{": const int &", "at"}, ExpectedHint{": int *", "data"},
1737 ExpectedHint{": allocator<int>", "allocator"},
1738 ExpectedHint{": size_type", "size"}, ExpectedHint{": iterator", "begin"},
1739 ExpectedHint{": non_template_iterator", "end"});
1740
1741 llvm::StringRef TypeAlias = R"cpp(
1742 // If the type alias is not of substituted template parameter type,
1743 // do not show desugared type.
1744 using VeryLongLongTypeName = my_iterator;
1745 using Short = VeryLongLongTypeName;
1746
1747 auto $short_name[[my_value]] = Short();
1748
1749 // Same applies with templates.
1750 template <typename T, typename A>
1751 using basic_static_vector = vector<T, A>;
1752 template <typename T>
1753 using static_vector = basic_static_vector<T, allocator<T>>;
1754
1755 auto $vector_name[[vec]] = static_vector<int>();
1756 )cpp";
1757
1758 assertHintsWithHeader(InlayHintKind::Type, TypeAlias, Header,
1759 DefaultOptsForTests,
1760 ExpectedHint{": Short", "short_name"},
1761 ExpectedHint{": static_vector<int>", "vector_name"});
1762}
1763
1764TEST(DesignatorHints, Basic) {
1765 assertDesignatorHints(R"cpp(
1766 struct S { int x, y, z; };
1767 S s {$x[[1]], $y[[2+2]]};
1768
1769 int x[] = {$0[[0]], $1[[1]]};
1770 )cpp",
1771 ExpectedHint{".x=", "x"}, ExpectedHint{".y=", "y"},
1772 ExpectedHint{"[0]=", "0"}, ExpectedHint{"[1]=", "1"});
1773}
1774
1775TEST(DesignatorHints, Nested) {
1776 assertDesignatorHints(R"cpp(
1777 struct Inner { int x, y; };
1778 struct Outer { Inner a, b; };
1779 Outer o{ $a[[{ $x[[1]], $y[[2]] }]], $bx[[3]] };
1780 )cpp",
1781 ExpectedHint{".a=", "a"}, ExpectedHint{".x=", "x"},
1782 ExpectedHint{".y=", "y"}, ExpectedHint{".b.x=", "bx"});
1783}
1784
1785TEST(DesignatorHints, AnonymousRecord) {
1786 assertDesignatorHints(R"cpp(
1787 struct S {
1788 union {
1789 struct {
1790 struct {
1791 int y;
1792 };
1793 } x;
1794 };
1795 };
1796 S s{$xy[[42]]};
1797 )cpp",
1798 ExpectedHint{".x.y=", "xy"});
1799}
1800
1801TEST(DesignatorHints, Suppression) {
1802 assertDesignatorHints(R"cpp(
1803 struct Point { int a, b, c, d, e, f, g, h; };
1804 Point p{/*a=*/1, .c=2, /* .d = */3, $e[[4]]};
1805 )cpp",
1806 ExpectedHint{".e=", "e"});
1807}
1808
1809TEST(DesignatorHints, StdArray) {
1810 // Designators for std::array should be [0] rather than .__elements[0].
1811 // While technically correct, the designator is useless and horrible to read.
1812 assertDesignatorHints(R"cpp(
1813 template <typename T, int N> struct Array { T __elements[N]; };
1814 Array<int, 2> x = {$0[[0]], $1[[1]]};
1815 )cpp",
1816 ExpectedHint{"[0]=", "0"}, ExpectedHint{"[1]=", "1"});
1817}
1818
1819TEST(DesignatorHints, OnlyAggregateInit) {
1820 assertDesignatorHints(R"cpp(
1821 struct Copyable { int x; } c;
1822 Copyable d{c};
1823
1824 struct Constructible { Constructible(int x); };
1825 Constructible x{42};
1826 )cpp" /*no designator hints expected (but param hints!)*/);
1827}
1828
1829TEST(DesignatorHints, NoCrash) {
1830 assertDesignatorHints(R"cpp(
1831 /*error-ok*/
1832 struct A {};
1833 struct Foo {int a; int b;};
1834 void test() {
1835 Foo f{A(), $b[[1]]};
1836 }
1837 )cpp",
1838 ExpectedHint{".b=", "b"});
1839}
1840
1841TEST(DesignatorHints, ParenInit) {
1842 assertDesignatorHints(R"cpp(
1843 struct S {
1844 int x;
1845 int y;
1846 int z;
1847 };
1848 S s ($x[[1]], $y[[2+2]], $z[[4]]);
1849 )cpp",
1850 ExpectedHint{".x=", "x"}, ExpectedHint{".y=", "y"},
1851 ExpectedHint{".z=", "z"});
1852}
1853
1854TEST(DesignatorHints, ParenInitDerived) {
1855 assertDesignatorHints(R"cpp(
1856 struct S1 {
1857 int a;
1858 int b;
1859 };
1860
1861 struct S2 : S1 {
1862 int c;
1863 int d;
1864 };
1865 S2 s2 ({$a[[0]], $b[[0]]}, $c[[0]], $d[[0]]);
1866 )cpp",
1867 // ExpectedHint{"S1:", "S1"},
1868 ExpectedHint{".a=", "a"}, ExpectedHint{".b=", "b"},
1869 ExpectedHint{".c=", "c"}, ExpectedHint{".d=", "d"});
1870}
1871
1872TEST(DesignatorHints, ParenInitTemplate) {
1873 assertDesignatorHints(R"cpp(
1874 template <typename T>
1875 struct S1 {
1876 int a;
1877 int b;
1878 T* ptr;
1879 };
1880
1881 struct S2 : S1<S2> {
1882 int c;
1883 int d;
1884 S1<int> mem;
1885 };
1886
1887 int main() {
1888 S2 sa ({$a1[[0]], $b1[[0]]}, $c[[0]], $d[[0]], $mem[[S1<int>($a2[[1]], $b2[[2]], $ptr[[nullptr]])]]);
1889 }
1890 )cpp",
1891 ExpectedHint{".a=", "a1"}, ExpectedHint{".b=", "b1"},
1892 ExpectedHint{".c=", "c"}, ExpectedHint{".d=", "d"},
1893 ExpectedHint{".mem=", "mem"}, ExpectedHint{".a=", "a2"},
1894 ExpectedHint{".b=", "b2"},
1895 ExpectedHint{".ptr=", "ptr"});
1896}
1897
1898TEST(InlayHints, RestrictRange) {
1899 Annotations Code(R"cpp(
1900 auto a = false;
1901 [[auto b = 1;
1902 auto c = '2';]]
1903 auto d = 3.f;
1904 )cpp");
1905 auto AST = TestTU::withCode(Code.code()).build();
1906 EXPECT_THAT(inlayHints(AST, Code.range()),
1907 ElementsAre(labelIs(": int"), labelIs(": char")));
1908}
1909
1910TEST(ParameterHints, PseudoObjectExpr) {
1911 Annotations Code(R"cpp(
1912 struct S {
1913 __declspec(property(get=GetX, put=PutX)) int x[];
1914 int GetX(int y, int z) { return 42 + y; }
1915 void PutX(int) { }
1916
1917 // This is a PseudoObjectExpression whose syntactic form is a binary
1918 // operator.
1919 void Work(int y) { x = y; } // Not `x = y: y`.
1920 };
1921
1922 int printf(const char *Format, ...);
1923
1924 int main() {
1925 S s;
1926 __builtin_dump_struct(&s, printf); // Not `Format: __builtin_dump_struct()`
1927 printf($Param[["Hello, %d"]], 42); // Normal calls are not affected.
1928 // This builds a PseudoObjectExpr, but here it's useful for showing the
1929 // arguments from the semantic form.
1930 return s.x[ $one[[1]] ][ $two[[2]] ]; // `x[y: 1][z: 2]`
1931 }
1932 )cpp");
1933 auto TU = TestTU::withCode(Code.code());
1934 TU.ExtraArgs.push_back("-fms-extensions");
1935 auto AST = TU.build();
1936 EXPECT_THAT(inlayHints(AST, std::nullopt),
1937 ElementsAre(HintMatcher(ExpectedHint{"Format: ", "Param"}, Code),
1938 HintMatcher(ExpectedHint{"y: ", "one"}, Code),
1939 HintMatcher(ExpectedHint{"z: ", "two"}, Code)));
1940}
1941
1942TEST(ParameterHints, ArgPacksAndConstructors) {
1943 assertParameterHints(
1944 R"cpp(
1945 struct Foo{ Foo(); Foo(int x); };
1946 void foo(Foo a, int b);
1947 template <typename... Args>
1948 void bar(Args... args) {
1949 foo(args...);
1950 }
1951 template <typename... Args>
1952 void baz(Args... args) { foo($param1[[Foo{args...}]], $param2[[1]]); }
1953
1954 template <typename... Args>
1955 void bax(Args... args) { foo($param3[[{args...}]], args...); }
1956
1957 void foo() {
1958 bar($param4[[Foo{}]], $param5[[42]]);
1959 bar($param6[[42]], $param7[[42]]);
1960 baz($param8[[42]]);
1961 bax($param9[[42]]);
1962 }
1963 )cpp",
1964 ExpectedHint{"a: ", "param1"}, ExpectedHint{"b: ", "param2"},
1965 ExpectedHint{"a: ", "param3"}, ExpectedHint{"a: ", "param4"},
1966 ExpectedHint{"b: ", "param5"}, ExpectedHint{"a: ", "param6"},
1967 ExpectedHint{"b: ", "param7"}, ExpectedHint{"x: ", "param8"},
1968 ExpectedHint{"b: ", "param9"});
1969}
1970
1971TEST(ParameterHints, DoesntExpandAllArgs) {
1972 assertParameterHints(
1973 R"cpp(
1974 void foo(int x, int y);
1975 int id(int a, int b, int c);
1976 template <typename... Args>
1977 void bar(Args... args) {
1978 foo(id($param1[[args]], $param2[[1]], $param3[[args]])...);
1979 }
1980 void foo() {
1981 bar(1, 2); // FIXME: We could have `bar(a: 1, a: 2)` here.
1982 }
1983 )cpp",
1984 ExpectedHint{"a: ", "param1"}, ExpectedHint{"b: ", "param2"},
1985 ExpectedHint{"c: ", "param3"});
1986}
1987
1988TEST(BlockEndHints, Functions) {
1989 assertBlockEndHints(R"cpp(
1990 int foo() {
1991 return 41;
1992 $foo[[}]]
1993
1994 template<int X>
1995 int bar() {
1996 // No hint for lambda for now
1997 auto f = []() {
1998 return X;
1999 };
2000 return f();
2001 $bar[[}]]
2002
2003 // No hint because this isn't a definition
2004 int buz();
2005
2006 struct S{};
2007 bool operator==(S, S) {
2008 return true;
2009 $opEqual[[}]]
2010 )cpp",
2011 ExpectedHint{" // foo", "foo"},
2012 ExpectedHint{" // bar", "bar"},
2013 ExpectedHint{" // operator==", "opEqual"});
2014}
2015
2016TEST(BlockEndHints, Methods) {
2017 assertBlockEndHints(R"cpp(
2018 struct Test {
2019 // No hint because there's no function body
2020 Test() = default;
2021
2022 ~Test() {
2023 $dtor[[}]]
2024
2025 void method1() {
2026 $method1[[}]]
2027
2028 // No hint because this isn't a definition
2029 void method2();
2030
2031 template <typename T>
2032 void method3() {
2033 $method3[[}]]
2034
2035 // No hint because this isn't a definition
2036 template <typename T>
2037 void method4();
2038
2039 Test operator+(int) const {
2040 return *this;
2041 $opIdentity[[}]]
2042
2043 operator bool() const {
2044 return true;
2045 $opBool[[}]]
2046
2047 // No hint because there's no function body
2048 operator int() const = delete;
2049 } x;
2050
2051 void Test::method2() {
2052 $method2[[}]]
2053
2054 template <typename T>
2055 void Test::method4() {
2056 $method4[[}]]
2057 )cpp",
2058 ExpectedHint{" // ~Test", "dtor"},
2059 ExpectedHint{" // method1", "method1"},
2060 ExpectedHint{" // method3", "method3"},
2061 ExpectedHint{" // operator+", "opIdentity"},
2062 ExpectedHint{" // operator bool", "opBool"},
2063 ExpectedHint{" // Test::method2", "method2"},
2064 ExpectedHint{" // Test::method4", "method4"});
2065}
2066
2067TEST(BlockEndHints, Namespaces) {
2068 assertBlockEndHints(
2069 R"cpp(
2070 namespace {
2071 void foo();
2072 $anon[[}]]
2073
2074 namespace ns {
2075 void bar();
2076 $ns[[}]]
2077 )cpp",
2078 ExpectedHint{" // namespace", "anon"},
2079 ExpectedHint{" // namespace ns", "ns"});
2080}
2081
2082TEST(BlockEndHints, Types) {
2083 assertBlockEndHints(
2084 R"cpp(
2085 struct S {
2086 $S[[};]]
2087
2088 class C {
2089 $C[[};]]
2090
2091 union U {
2092 $U[[};]]
2093
2094 enum E1 {
2095 $E1[[};]]
2096
2097 enum class E2 {
2098 $E2[[};]]
2099 )cpp",
2100 ExpectedHint{" // struct S", "S"}, ExpectedHint{" // class C", "C"},
2101 ExpectedHint{" // union U", "U"}, ExpectedHint{" // enum E1", "E1"},
2102 ExpectedHint{" // enum class E2", "E2"});
2103}
2104
2105TEST(BlockEndHints, If) {
2106 assertBlockEndHints(
2107 R"cpp(
2108 void foo(bool cond) {
2109 void* ptr;
2110 if (cond)
2111 ;
2112
2113 if (cond) {
2114 $simple[[}]]
2115
2116 if (cond) {
2117 } else {
2118 $ifelse[[}]]
2119
2120 if (cond) {
2121 } else if (!cond) {
2122 $elseif[[}]]
2123
2124 if (cond) {
2125 } else {
2126 if (!cond) {
2127 $inner[[}]]
2128 $outer[[}]]
2129
2130 if (auto X = cond) {
2131 $init[[}]]
2132
2133 if (int i = 0; i > 10) {
2134 $init_cond[[}]]
2135
2136 if (ptr != nullptr) {
2137 $null_check[[}]]
2138 } // suppress
2139 )cpp",
2140 ExpectedHint{" // if cond", "simple"},
2141 ExpectedHint{" // if cond", "ifelse"}, ExpectedHint{" // if", "elseif"},
2142 ExpectedHint{" // if !cond", "inner"},
2143 ExpectedHint{" // if cond", "outer"}, ExpectedHint{" // if X", "init"},
2144 ExpectedHint{" // if i > 10", "init_cond"},
2145 ExpectedHint{" // if ptr != nullptr", "null_check"});
2146}
2147
2148TEST(BlockEndHints, Loops) {
2149 assertBlockEndHints(
2150 R"cpp(
2151 void foo() {
2152 while (true)
2153 ;
2154
2155 while (true) {
2156 $while[[}]]
2157
2158 do {
2159 } while (true);
2160
2161 for (;true;) {
2162 $forcond[[}]]
2163
2164 for (int I = 0; I < 10; ++I) {
2165 $forvar[[}]]
2166
2167 int Vs[] = {1,2,3};
2168 for (auto V : Vs) {
2169 $foreach[[}]]
2170 } // suppress
2171 )cpp",
2172 ExpectedHint{" // while true", "while"},
2173 ExpectedHint{" // for true", "forcond"},
2174 ExpectedHint{" // for I", "forvar"},
2175 ExpectedHint{" // for V", "foreach"});
2176}
2177
2178TEST(BlockEndHints, Switch) {
2179 assertBlockEndHints(
2180 R"cpp(
2181 void foo(int I) {
2182 switch (I) {
2183 case 0: break;
2184 $switch[[}]]
2185 } // suppress
2186 )cpp",
2187 ExpectedHint{" // switch I", "switch"});
2188}
2189
2190TEST(BlockEndHints, PrintLiterals) {
2191 assertBlockEndHints(
2192 R"cpp(
2193 void foo() {
2194 while ("foo") {
2195 $string[[}]]
2196
2197 while ("foo but this time it is very long") {
2198 $string_long[[}]]
2199
2200 while (true) {
2201 $boolean[[}]]
2202
2203 while (1) {
2204 $integer[[}]]
2205
2206 while (1.5) {
2207 $float[[}]]
2208 } // suppress
2209 )cpp",
2210 ExpectedHint{" // while \"foo\"", "string"},
2211 ExpectedHint{" // while \"foo but...\"", "string_long"},
2212 ExpectedHint{" // while true", "boolean"},
2213 ExpectedHint{" // while 1", "integer"},
2214 ExpectedHint{" // while 1.5", "float"});
2215}
2216
2217TEST(BlockEndHints, PrintRefs) {
2218 assertBlockEndHints(
2219 R"cpp(
2220 namespace ns {
2221 int Var;
2222 int func1();
2223 int func2(int, int);
2224 struct S {
2225 int Field;
2226 int method1() const;
2227 int method2(int, int) const;
2228 }; // suppress
2229 } // suppress
2230 void foo() {
2231 int int_a {};
2232 while (ns::Var) {
2233 $var[[}]]
2234
2235 while (ns::func1()) {
2236 $func1[[}]]
2237
2238 while (ns::func2(int_a, int_a)) {
2239 $func2[[}]]
2240
2241 while (ns::S{}.Field) {
2242 $field[[}]]
2243
2244 while (ns::S{}.method1()) {
2245 $method1[[}]]
2246
2247 while (ns::S{}.method2(int_a, int_a)) {
2248 $method2[[}]]
2249 } // suppress
2250 )cpp",
2251 ExpectedHint{" // while Var", "var"},
2252 ExpectedHint{" // while func1()", "func1"},
2253 ExpectedHint{" // while func2(...)", "func2"},
2254 ExpectedHint{" // while Field", "field"},
2255 ExpectedHint{" // while method1()", "method1"},
2256 ExpectedHint{" // while method2(...)", "method2"});
2257}
2258
2259TEST(BlockEndHints, PrintConversions) {
2260 assertBlockEndHints(
2261 R"cpp(
2262 struct S {
2263 S(int);
2264 S(int, int);
2265 explicit operator bool();
2266 }; // suppress
2267 void foo(int I) {
2268 while (float(I)) {
2269 $convert_primitive[[}]]
2270
2271 while (S(I)) {
2272 $convert_class[[}]]
2273
2274 while (S(I, I)) {
2275 $construct_class[[}]]
2276 } // suppress
2277 )cpp",
2278 ExpectedHint{" // while float", "convert_primitive"},
2279 ExpectedHint{" // while S", "convert_class"},
2280 ExpectedHint{" // while S", "construct_class"});
2281}
2282
2283TEST(BlockEndHints, PrintOperators) {
2284 std::string AnnotatedCode = R"cpp(
2285 void foo(Integer I) {
2286 while(++I){
2287 $preinc[[}]]
2288
2289 while(I++){
2290 $postinc[[}]]
2291
2292 while(+(I + I)){
2293 $unary_complex[[}]]
2294
2295 while(I < 0){
2296 $compare[[}]]
2297
2298 while((I + I) < I){
2299 $lhs_complex[[}]]
2300
2301 while(I < (I + I)){
2302 $rhs_complex[[}]]
2303
2304 while((I + I) < (I + I)){
2305 $binary_complex[[}]]
2306 } // suppress
2307 )cpp";
2308
2309 // We can't store shared expectations in a vector, assertHints uses varargs.
2310 auto AssertExpectedHints = [&](llvm::StringRef Code) {
2311 assertBlockEndHints(Code, ExpectedHint{" // while ++I", "preinc"},
2312 ExpectedHint{" // while I++", "postinc"},
2313 ExpectedHint{" // while", "unary_complex"},
2314 ExpectedHint{" // while I < 0", "compare"},
2315 ExpectedHint{" // while ... < I", "lhs_complex"},
2316 ExpectedHint{" // while I < ...", "rhs_complex"},
2317 ExpectedHint{" // while", "binary_complex"});
2318 };
2319
2320 // First with built-in operators.
2321 AssertExpectedHints("using Integer = int;" + AnnotatedCode);
2322 // And now with overloading!
2323 AssertExpectedHints(R"cpp(
2324 struct Integer {
2325 explicit operator bool();
2326 Integer operator++();
2327 Integer operator++(int);
2328 Integer operator+(Integer);
2329 Integer operator+();
2330 bool operator<(Integer);
2331 bool operator<(int);
2332 }; // suppress
2333 )cpp" + AnnotatedCode);
2334}
2335
2336TEST(BlockEndHints, TrailingSemicolon) {
2337 assertBlockEndHints(R"cpp(
2338 // The hint is placed after the trailing ';'
2339 struct S1 {
2340 $S1[[} ;]]
2341
2342 // The hint is always placed in the same line with the closing '}'.
2343 // So in this case where ';' is missing, it is attached to '}'.
2344 struct S2 {
2345 $S2[[}]]
2346
2347 ;
2348
2349 // No hint because only one trailing ';' is allowed
2350 struct S3 {
2351 };;
2352
2353 // No hint because trailing ';' is only allowed for class/struct/union/enum
2354 void foo() {
2355 };
2356
2357 // Rare case, but yes we'll have a hint here.
2358 struct {
2359 int x;
2360 $anon[[}]]
2361
2362 s2;
2363 )cpp",
2364 ExpectedHint{" // struct S1", "S1"},
2365 ExpectedHint{" // struct S2", "S2"},
2366 ExpectedHint{" // struct", "anon"});
2367}
2368
2369TEST(BlockEndHints, TrailingText) {
2370 assertBlockEndHints(R"cpp(
2371 struct S1 {
2372 $S1[[} ;]]
2373
2374 // No hint for S2 because of the trailing comment
2375 struct S2 {
2376 }; /* Put anything here */
2377
2378 struct S3 {
2379 // No hint for S4 because of the trailing source code
2380 struct S4 {
2381 };$S3[[};]]
2382
2383 // No hint for ns because of the trailing comment
2384 namespace ns {
2385 } // namespace ns
2386 )cpp",
2387 ExpectedHint{" // struct S1", "S1"},
2388 ExpectedHint{" // struct S3", "S3"});
2389}
2390
2391TEST(BlockEndHints, Macro) {
2392 assertBlockEndHints(R"cpp(
2393 #define DECL_STRUCT(NAME) struct NAME {
2394 #define RBRACE }
2395
2396 DECL_STRUCT(S1)
2397 $S1[[};]]
2398
2399 // No hint because we require a '}'
2400 DECL_STRUCT(S2)
2401 RBRACE;
2402 )cpp",
2403 ExpectedHint{" // struct S1", "S1"});
2404}
2405
2406TEST(BlockEndHints, PointerToMemberFunction) {
2407 // Do not crash trying to summarize `a->*p`.
2408 assertBlockEndHints(R"cpp(
2409 class A {};
2410 using Predicate = bool(A::*)();
2411 void foo(A* a, Predicate p) {
2412 if ((a->*p)()) {
2413 $ptrmem[[}]]
2414 } // suppress
2415 )cpp",
2416 ExpectedHint{" // if ()", "ptrmem"});
2417}
2418
2419TEST(BlockEndHints, MinLineLimit) {
2420 InlayHintOptions Opts;
2421 Opts.HintMinLineLimit = 10;
2422
2423 // namespace ns below is exactly 10 lines
2424 assertBlockEndHintsWithOpts(
2425 R"cpp(
2426 namespace ns {
2427 int Var;
2428 int func1();
2429 int func2(int, int);
2430 struct S {
2431 int Field;
2432 int method1() const;
2433 int method2(int, int) const;
2434 };
2435 $namespace[[}]]
2436 void foo() {
2437 int int_a {};
2438 while (ns::Var) {
2439 }
2440
2441 while (ns::func1()) {
2442 }
2443
2444 while (ns::func2(int_a, int_a)) {
2445 }
2446
2447 while (ns::S{}.Field) {
2448 }
2449
2450 while (ns::S{}.method1()) {
2451 }
2452
2453 while (ns::S{}.method2(int_a, int_a)) {
2454 }
2455 $foo[[}]]
2456 )cpp",
2457 Opts, ExpectedHint{" // namespace ns", "namespace"},
2458 ExpectedHint{" // foo", "foo"});
2459}
2460
2461// FIXME: Low-hanging fruit where we could omit a type hint:
2462// - auto x = TypeName(...);
2463// - auto x = (TypeName) (...);
2464// - auto x = static_cast<TypeName>(...); // and other built-in casts
2465
2466// Annoyances for which a heuristic is not obvious:
2467// - auto x = llvm::dyn_cast<LongTypeName>(y); // and similar
2468// - stdlib algos return unwieldy __normal_iterator<X*, ...> type
2469// (For this one, perhaps we should omit type hints that start
2470// with a double underscore.)
2471
2472} // namespace
2473} // namespace clangd
2474} // namespace clang
Same as llvm::Annotations, but adjusts functions to LSP-specific types for positions and ranges.
Definition Annotations.h:23
void addSource(llvm::StringRef Filename, llvm::StringRef Code)
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
MATCHER_P2(hasFlag, Flag, Path, "")
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
MATCHER_P(named, N, "")
TEST(BackgroundQueueTest, Priority)
InlayHintKind
Inlay hint kinds.
Definition Protocol.h:1739
@ BlockEnd
A hint after function, type or namespace definition, indicating the defined symbol name of the defini...
Definition Protocol.h:1769
@ DefaultArgument
An inlay hint that is for a default argument.
Definition Protocol.h:1778
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1752
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1745
@ Designator
A hint before an element of an aggregate braced initializer list, indicating what it is initializing.
Definition Protocol.h:1759
std::vector< InlayHint > inlayHints(ParsedAST &AST, std::optional< Range > RestrictRange, InlayHintOptions HintOptions)
Compute and return inlay hints for a file.
===– 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
struct clang::clangd::Config::@041344304366110202143331236314370324353035136032 InlayHints
uint32_t TypeNameLimit
Definition Config.h:202
Inlay hint information.
Definition Protocol.h:1831
std::string joinLabels() const
Join the label[].value together.
Range range
The range of source code to which the hint applies.
Definition Protocol.h:1864
ParsedAST build() const
Definition TestTU.cpp:115
static TestTU withCode(llvm::StringRef Code)
Definition TestTU.h:36