clang-tools 23.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, Macros) {
894 // Handling of macros depends on where the call's argument list comes from.
895
896 // If it comes from a macro definition, there's nothing to hint
897 // at the invocation site.
898 assertParameterHints(R"cpp(
899 void foo(int param);
900 #define ExpandsToCall() foo(42)
901 void bar() {
902 ExpandsToCall();
903 }
904 )cpp");
905
906 // The argument expression being a macro invocation shouldn't interfere
907 // with hinting.
908 assertParameterHints(R"cpp(
909 #define PI 3.14
910 void foo(double param);
911 void bar() {
912 foo($param[[PI]]);
913 }
914 )cpp",
915 ExpectedHint{"param: ", "param"});
916
917 // If the whole argument list comes from a macro parameter, hint it.
918 assertParameterHints(R"cpp(
919 void abort();
920 #define ASSERT(expr) if (!expr) abort()
921 int foo(int param);
922 void bar() {
923 ASSERT(foo($param[[42]]) == 0);
924 }
925 )cpp",
926 ExpectedHint{"param: ", "param"});
927
928 // If the macro expands to multiple arguments, don't hint it.
929 assertParameterHints(R"cpp(
930 void foo(double x, double y);
931 #define CONSTANTS 3.14, 2.72
932 void bar() {
933 foo(CONSTANTS);
934 }
935 )cpp");
936}
937
938TEST(ParameterHints, ConstructorParens) {
939 assertParameterHints(R"cpp(
940 struct S {
941 S(int param);
942 };
943 void bar() {
944 S obj($param[[42]]);
945 }
946 )cpp",
947 ExpectedHint{"param: ", "param"});
948}
949
950TEST(ParameterHints, ConstructorBraces) {
951 assertParameterHints(R"cpp(
952 struct S {
953 S(int param);
954 };
955 void bar() {
956 S obj{$param[[42]]};
957 }
958 )cpp",
959 ExpectedHint{"param: ", "param"});
960}
961
962TEST(ParameterHints, ConstructorStdInitList) {
963 // Do not show hints for std::initializer_list constructors.
964 assertParameterHints(R"cpp(
965 namespace std {
966 template <typename E> class initializer_list { const E *a, *b; };
967 }
968 struct S {
969 S(std::initializer_list<int> param);
970 };
971 void bar() {
972 S obj{42, 43};
973 }
974 )cpp");
975}
976
977TEST(ParameterHints, MemberInit) {
978 assertParameterHints(R"cpp(
979 struct S {
980 S(int param);
981 };
982 struct T {
983 S member;
984 T() : member($param[[42]]) {}
985 };
986 )cpp",
987 ExpectedHint{"param: ", "param"});
988}
989
990TEST(ParameterHints, ImplicitConstructor) {
991 assertParameterHints(R"cpp(
992 struct S {
993 S(int param);
994 };
995 void bar(S);
996 S foo() {
997 // Do not show hint for implicit constructor call in argument.
998 bar(42);
999 // Do not show hint for implicit constructor call in return.
1000 return 42;
1001 }
1002 )cpp");
1003}
1004
1005TEST(ParameterHints, FunctionPointer) {
1006 assertParameterHints(
1007 R"cpp(
1008 void (*f1)(int param);
1009 void (__stdcall *f2)(int param);
1010 using f3_t = void(*)(int param);
1011 f3_t f3;
1012 using f4_t = void(__stdcall *)(int param);
1013 f4_t f4;
1014 __attribute__((noreturn)) f4_t f5;
1015 void bar() {
1016 f1($f1[[42]]);
1017 f2($f2[[42]]);
1018 f3($f3[[42]]);
1019 f4($f4[[42]]);
1020 // This one runs into an edge case in clang's type model
1021 // and we can't extract the parameter name. But at least
1022 // we shouldn't crash.
1023 f5(42);
1024 }
1025 )cpp",
1026 ExpectedHint{"param: ", "f1"}, ExpectedHint{"param: ", "f2"},
1027 ExpectedHint{"param: ", "f3"}, ExpectedHint{"param: ", "f4"});
1028}
1029
1030TEST(ParameterHints, ArgMatchesParam) {
1031 assertParameterHints(R"cpp(
1032 void foo(int param);
1033 struct S {
1034 static const int param = 42;
1035 };
1036 void bar() {
1037 int param = 42;
1038 // Do not show redundant "param: param".
1039 foo(param);
1040 // But show it if the argument is qualified.
1041 foo($param[[S::param]]);
1042 }
1043 struct A {
1044 int param;
1045 void bar() {
1046 // Do not show "param: param" for member-expr.
1047 foo(param);
1048 }
1049 };
1050 )cpp",
1051 ExpectedHint{"param: ", "param"});
1052}
1053
1054TEST(ParameterHints, ArgMatchesParamReference) {
1055 assertParameterHints(R"cpp(
1056 void foo(int& param);
1057 void foo2(const int& param);
1058 void bar() {
1059 int param;
1060 // show reference hint on mutable reference
1061 foo($param[[param]]);
1062 // but not on const reference
1063 foo2(param);
1064 }
1065 )cpp",
1066 ExpectedHint{"&: ", "param"});
1067}
1068
1069TEST(ParameterHints, LeadingUnderscore) {
1070 assertParameterHints(R"cpp(
1071 void foo(int p1, int _p2, int __p3);
1072 void bar() {
1073 foo($p1[[41]], $p2[[42]], $p3[[43]]);
1074 }
1075 )cpp",
1076 ExpectedHint{"p1: ", "p1"}, ExpectedHint{"p2: ", "p2"},
1077 ExpectedHint{"p3: ", "p3"});
1078}
1079
1080TEST(ParameterHints, DependentCalls) {
1081 assertParameterHints(R"cpp(
1082 template <typename T>
1083 void nonmember(T par1);
1084
1085 template <typename T>
1086 struct A {
1087 void member(T par2);
1088 static void static_member(T par3);
1089 };
1090
1091 void overload(int anInt);
1092 void overload(double aDouble);
1093
1094 template <typename T>
1095 struct S {
1096 void bar(A<T> a, T t) {
1097 nonmember($par1[[t]]);
1098 a.member($par2[[t]]);
1099 A<T>::static_member($par3[[t]]);
1100 // We don't want to arbitrarily pick between
1101 // "anInt" or "aDouble", so just show no hint.
1102 overload(T{});
1103 }
1104 };
1105 )cpp",
1106 ExpectedHint{"par1: ", "par1"},
1107 ExpectedHint{"par2: ", "par2"},
1108 ExpectedHint{"par3: ", "par3"});
1109}
1110
1111TEST(ParameterHints, VariadicFunction) {
1112 assertParameterHints(R"cpp(
1113 template <typename... T>
1114 void foo(int fixed, T... variadic);
1115
1116 void bar() {
1117 foo($fixed[[41]], 42, 43);
1118 }
1119 )cpp",
1120 ExpectedHint{"fixed: ", "fixed"});
1121}
1122
1123TEST(ParameterHints, VarargsFunction) {
1124 assertParameterHints(R"cpp(
1125 void foo(int fixed, ...);
1126
1127 void bar() {
1128 foo($fixed[[41]], 42, 43);
1129 }
1130 )cpp",
1131 ExpectedHint{"fixed: ", "fixed"});
1132}
1133
1134TEST(ParameterHints, CopyOrMoveConstructor) {
1135 // Do not show hint for parameter of copy or move constructor.
1136 assertParameterHints(R"cpp(
1137 struct S {
1138 S();
1139 S(const S& other);
1140 S(S&& other);
1141 };
1142 void bar() {
1143 S a;
1144 S b(a); // copy
1145 S c(S()); // move
1146 }
1147 )cpp");
1148}
1149
1150TEST(ParameterHints, UserDefinedLiteral) {
1151 // Do not hint call to user-defined literal operator.
1152 assertParameterHints(R"cpp(
1153 long double operator"" _w(long double param);
1154 void bar() {
1155 1.2_w;
1156 }
1157 )cpp");
1158}
1159
1160TEST(ParameterHints, ParamNameComment) {
1161 // Do not hint an argument which already has a comment
1162 // with the parameter name preceding it.
1163 assertParameterHints(R"cpp(
1164 void foo(int param);
1165 void bar() {
1166 foo(/*param*/42);
1167 foo( /* param = */ 42);
1168#define X 42
1169#define Y X
1170#define Z(...) Y
1171 foo(/*param=*/Z(a));
1172 foo($macro[[Z(a)]]);
1173 foo(/* the answer */$param[[42]]);
1174 }
1175 )cpp",
1176 ExpectedHint{"param: ", "macro"},
1177 ExpectedHint{"param: ", "param"});
1178}
1179
1180TEST(ParameterHints, SetterFunctions) {
1181 assertParameterHints(R"cpp(
1182 struct S {
1183 void setParent(S* parent);
1184 void set_parent(S* parent);
1185 void setTimeout(int timeoutMillis);
1186 void setTimeoutMillis(int timeout_millis);
1187 };
1188 void bar() {
1189 S s;
1190 // Parameter name matches setter name - omit hint.
1191 s.setParent(nullptr);
1192 // Support snake_case
1193 s.set_parent(nullptr);
1194 // Parameter name may contain extra info - show hint.
1195 s.setTimeout($timeoutMillis[[120]]);
1196 // FIXME: Ideally we'd want to omit this.
1197 s.setTimeoutMillis($timeout_millis[[120]]);
1198 }
1199 )cpp",
1200 ExpectedHint{"timeoutMillis: ", "timeoutMillis"},
1201 ExpectedHint{"timeout_millis: ", "timeout_millis"});
1202}
1203
1204TEST(ParameterHints, BuiltinFunctions) {
1205 // This prototype of std::forward is sufficient for clang to recognize it
1206 assertParameterHints(R"cpp(
1207 namespace std { template <typename T> T&& forward(T&); }
1208 void foo() {
1209 int i;
1210 std::forward(i);
1211 }
1212 )cpp");
1213}
1214
1215TEST(ParameterHints, IncludeAtNonGlobalScope) {
1216 Annotations FooInc(R"cpp(
1217 void bar() { foo(42); }
1218 )cpp");
1219 Annotations FooCC(R"cpp(
1220 struct S {
1221 void foo(int param);
1222 #include "foo.inc"
1223 };
1224 )cpp");
1225
1226 TestWorkspace Workspace;
1227 Workspace.addSource("foo.inc", FooInc.code());
1228 Workspace.addMainFile("foo.cc", FooCC.code());
1229
1230 auto AST = Workspace.openFile("foo.cc");
1231 ASSERT_TRUE(bool(AST));
1232
1233 // Ensure the hint for the call in foo.inc is NOT materialized in foo.cc.
1234 EXPECT_EQ(
1235 hintsOfKind(*AST, InlayHintKind::Parameter, DefaultOptsForTests).size(),
1236 0u);
1237}
1238
1239TEST(TypeHints, Smoke) {
1240 assertTypeHints(R"cpp(
1241 auto $waldo[[waldo]] = 42;
1242 )cpp",
1243 ExpectedHint{": int", "waldo"});
1244}
1245
1246TEST(TypeHints, Decorations) {
1247 assertTypeHints(R"cpp(
1248 int x = 42;
1249 auto* $var1[[var1]] = &x;
1250 auto&& $var2[[var2]] = x;
1251 const auto& $var3[[var3]] = x;
1252 )cpp",
1253 ExpectedHint{": int *", "var1"},
1254 ExpectedHint{": int &", "var2"},
1255 ExpectedHint{": const int &", "var3"});
1256}
1257
1258TEST(TypeHints, DecltypeAuto) {
1259 assertTypeHints(R"cpp(
1260 int x = 42;
1261 int& y = x;
1262 decltype(auto) $z[[z]] = y;
1263 )cpp",
1264 ExpectedHint{": int &", "z"});
1265}
1266
1267TEST(TypeHints, NoQualifiers) {
1268 assertTypeHints(R"cpp(
1269 namespace A {
1270 namespace B {
1271 struct S1 {};
1272 S1 foo();
1273 auto $x[[x]] = foo();
1274
1275 struct S2 {
1276 template <typename T>
1277 struct Inner {};
1278 };
1279 S2::Inner<int> bar();
1280 auto $y[[y]] = bar();
1281 }
1282 }
1283 )cpp",
1284 ExpectedHint{": S1", "x"}, ExpectedHint{": Inner<int>", "y"});
1285}
1286
1287TEST(TypeHints, Lambda) {
1288 // Do not print something overly verbose like the lambda's location.
1289 // Show hints for init-captures (but not regular captures).
1290 assertTypeHints(R"cpp(
1291 void f() {
1292 int cap = 42;
1293 auto $L[[L]] = [cap, $init[[init]] = 1 + 1](int a$ret[[)]] {
1294 return a + cap + init;
1295 };
1296 }
1297 )cpp",
1298 ExpectedHint{": (lambda)", "L"},
1299 ExpectedHint{": int", "init"}, ExpectedHint{"-> int", "ret"});
1300
1301 // Lambda return hint shown even if no param list.
1302 // (The digraph :> is just a ] that doesn't conflict with the annotations).
1303 assertTypeHints("auto $L[[x]] = <:$ret[[:>]]{return 42;};",
1304 ExpectedHint{": (lambda)", "L"},
1305 ExpectedHint{"-> int", "ret"});
1306}
1307
1308// Structured bindings tests.
1309// Note, we hint the individual bindings, not the aggregate.
1310
1311TEST(TypeHints, StructuredBindings_PublicStruct) {
1312 assertTypeHints(R"cpp(
1313 // Struct with public fields.
1314 struct Point {
1315 int x;
1316 int y;
1317 };
1318 Point foo();
1319 auto [$x[[x]], $y[[y]]] = foo();
1320 )cpp",
1321 ExpectedHint{": int", "x"}, ExpectedHint{": int", "y"});
1322}
1323
1324TEST(TypeHints, StructuredBindings_Array) {
1325 assertTypeHints(R"cpp(
1326 int arr[2];
1327 auto [$x[[x]], $y[[y]]] = arr;
1328 )cpp",
1329 ExpectedHint{": int", "x"}, ExpectedHint{": int", "y"});
1330}
1331
1332TEST(TypeHints, StructuredBindings_TupleLike) {
1333 assertTypeHints(R"cpp(
1334 // Tuple-like type.
1335 struct IntPair {
1336 int a;
1337 int b;
1338 };
1339 namespace std {
1340 template <typename T>
1341 struct tuple_size {};
1342 template <>
1343 struct tuple_size<IntPair> {
1344 constexpr static unsigned value = 2;
1345 };
1346 template <unsigned I, typename T>
1347 struct tuple_element {};
1348 template <unsigned I>
1349 struct tuple_element<I, IntPair> {
1350 using type = int;
1351 };
1352 }
1353 template <unsigned I>
1354 int get(const IntPair& p) {
1355 if constexpr (I == 0) {
1356 return p.a;
1357 } else if constexpr (I == 1) {
1358 return p.b;
1359 }
1360 }
1361 IntPair bar();
1362 auto [$x[[x]], $y[[y]]] = bar();
1363 )cpp",
1364 ExpectedHint{": int", "x"}, ExpectedHint{": int", "y"});
1365}
1366
1367TEST(TypeHints, StructuredBindings_NoInitializer) {
1368 assertTypeHints(R"cpp(
1369 // No initializer (ill-formed).
1370 // Do not show useless "NULL TYPE" hint.
1371 auto [x, y]; /*error-ok*/
1372 )cpp");
1373}
1374
1375TEST(TypeHints, InvalidType) {
1376 assertTypeHints(R"cpp(
1377 auto x = (unknown_type)42; /*error-ok*/
1378 auto *y = (unknown_ptr)nullptr;
1379 )cpp");
1380}
1381
1382TEST(TypeHints, ReturnTypeDeduction) {
1383 assertTypeHints(
1384 R"cpp(
1385 auto f1(int x$ret1a[[)]]; // Hint forward declaration too
1386 auto f1(int x$ret1b[[)]] { return x + 1; }
1387
1388 // Include pointer operators in hint
1389 int s;
1390 auto& f2($ret2[[)]] { return s; }
1391
1392 // Do not hint `auto` for trailing return type.
1393 auto f3() -> int;
1394
1395 // Do not hint when a trailing return type is specified.
1396 auto f4() -> auto* { return "foo"; }
1397
1398 auto f5($noreturn[[)]] {}
1399
1400 // `auto` conversion operator
1401 struct A {
1402 operator auto($retConv[[)]] { return 42; }
1403 };
1404
1405 // FIXME: Dependent types do not work yet.
1406 template <typename T>
1407 struct S {
1408 auto method() { return T(); }
1409 };
1410 )cpp",
1411 ExpectedHint{"-> int", "ret1a"}, ExpectedHint{"-> int", "ret1b"},
1412 ExpectedHint{"-> int &", "ret2"}, ExpectedHint{"-> void", "noreturn"},
1413 ExpectedHint{"-> int", "retConv"});
1414}
1415
1416TEST(TypeHints, DependentType) {
1417 assertTypeHints(R"cpp(
1418 template <typename T>
1419 void foo(T arg) {
1420 // The hint would just be "auto" and we can't do any better.
1421 auto var1 = arg.method();
1422 // FIXME: It would be nice to show "T" as the hint.
1423 auto $var2[[var2]] = arg;
1424 }
1425
1426 template <typename T>
1427 void bar(T arg) {
1428 auto [a, b] = arg;
1429 }
1430 )cpp",
1431 ExpectedHint{": T", "var2"});
1432}
1433
1434TEST(TypeHints, LongTypeName) {
1435 assertTypeHints(R"cpp(
1436 template <typename, typename, typename>
1437 struct A {};
1438 struct MultipleWords {};
1439 A<MultipleWords, MultipleWords, MultipleWords> foo();
1440 // Omit type hint past a certain length (currently 32)
1441 auto var = foo();
1442 )cpp");
1443
1444 Config Cfg;
1445 Cfg.InlayHints.TypeNameLimit = 0;
1446 WithContextValue WithCfg(Config::Key, std::move(Cfg));
1447
1448 assertTypeHints(
1449 R"cpp(
1450 template <typename, typename, typename>
1451 struct A {};
1452 struct MultipleWords {};
1453 A<MultipleWords, MultipleWords, MultipleWords> foo();
1454 // Should have type hint with TypeNameLimit = 0
1455 auto $var[[var]] = foo();
1456 )cpp",
1457 ExpectedHint{": A<MultipleWords, MultipleWords, MultipleWords>", "var"});
1458}
1459
1460TEST(TypeHints, DefaultTemplateArgs) {
1461 assertTypeHints(R"cpp(
1462 template <typename, typename = int>
1463 struct A {};
1464 A<float> foo();
1465 auto $var[[var]] = foo();
1466 A<float> bar[1];
1467 auto [$binding[[value]]] = bar;
1468 )cpp",
1469 ExpectedHint{": A<float>", "var"},
1470 ExpectedHint{": A<float>", "binding"});
1471}
1472
1473TEST(DefaultArguments, Smoke) {
1474 Config Cfg;
1476 true; // To test interplay of parameters and default parameters
1477 Cfg.InlayHints.DeducedTypes = false;
1478 Cfg.InlayHints.Designators = false;
1479 Cfg.InlayHints.BlockEnd = false;
1480
1481 Cfg.InlayHints.DefaultArguments = true;
1482 WithContextValue WithCfg(Config::Key, std::move(Cfg));
1483
1484 const auto *Code = R"cpp(
1485 int foo(int A = 4) { return A; }
1486 int bar(int A, int B = 1, bool C = foo($default1[[)]]) { return A; }
1487 int A = bar($explicit[[2]]$default2[[)]];
1488
1489 void baz(int = 5) { if (false) baz($unnamed[[)]]; };
1490 )cpp";
1491
1492 assertHints(InlayHintKind::DefaultArgument, Code, DefaultOptsForTests,
1493 ExpectedHint{"A: 4", "default1", Left},
1494 ExpectedHint{", B: 1, C: foo()", "default2", Left},
1495 ExpectedHint{"5", "unnamed", Left});
1496
1497 assertHints(InlayHintKind::Parameter, Code, DefaultOptsForTests,
1498 ExpectedHint{"A: ", "explicit", Left});
1499}
1500
1501TEST(DefaultArguments, WithoutParameterNames) {
1502 Config Cfg;
1503 Cfg.InlayHints.Parameters = false; // To test just default args this time
1504 Cfg.InlayHints.DeducedTypes = false;
1505 Cfg.InlayHints.Designators = false;
1506 Cfg.InlayHints.BlockEnd = false;
1507
1508 Cfg.InlayHints.DefaultArguments = true;
1509 WithContextValue WithCfg(Config::Key, std::move(Cfg));
1510
1511 const auto *Code = R"cpp(
1512 struct Baz {
1513 Baz(float a = 3 //
1514 + 2);
1515 };
1516 struct Foo {
1517 Foo(int, Baz baz = //
1518 Baz{$abbreviated[[}]]
1519
1520 //
1521 ) {}
1522 };
1523
1524 int main() {
1525 Foo foo1(1$paren[[)]];
1526 Foo foo2{2$brace1[[}]];
1527 Foo foo3 = {3$brace2[[}]];
1528 auto foo4 = Foo{4$brace3[[}]];
1529 }
1530 )cpp";
1531
1532 assertHints(InlayHintKind::DefaultArgument, Code, DefaultOptsForTests,
1533 ExpectedHint{"...", "abbreviated", Left},
1534 ExpectedHint{", Baz{}", "paren", Left},
1535 ExpectedHint{", Baz{}", "brace1", Left},
1536 ExpectedHint{", Baz{}", "brace2", Left},
1537 ExpectedHint{", Baz{}", "brace3", Left});
1538
1539 assertHints(InlayHintKind::Parameter, Code, DefaultOptsForTests);
1540}
1541
1542TEST(TypeHints, Deduplication) {
1543 assertTypeHints(R"cpp(
1544 template <typename T>
1545 void foo() {
1546 auto $var[[var]] = 42;
1547 }
1548 template void foo<int>();
1549 template void foo<float>();
1550 )cpp",
1551 ExpectedHint{": int", "var"});
1552}
1553
1554TEST(TypeHints, SinglyInstantiatedTemplate) {
1555 assertTypeHints(R"cpp(
1556 auto $lambda[[x]] = [](auto *$param[[y]], auto) { return 42; };
1557 int m = x("foo", 3);
1558 )cpp",
1559 ExpectedHint{": (lambda)", "lambda"},
1560 ExpectedHint{": const char *", "param"});
1561
1562 // No hint for packs, or auto params following packs
1563 assertTypeHints(R"cpp(
1564 int x(auto $a[[a]], auto... b, auto c) { return 42; }
1565 int m = x<void*, char, float>(nullptr, 'c', 2.0, 2);
1566 )cpp",
1567 ExpectedHint{": void *", "a"});
1568}
1569
1570TEST(TypeHints, Aliased) {
1571 // Check that we don't crash for functions without a FunctionTypeLoc.
1572 // https://github.com/clangd/clangd/issues/1140
1573 TestTU TU = TestTU::withCode("void foo(void){} extern typeof(foo) foo;");
1574 TU.ExtraArgs.push_back("-xc");
1575 auto AST = TU.build();
1576
1577 EXPECT_THAT(hintsOfKind(AST, InlayHintKind::Type, DefaultOptsForTests),
1578 IsEmpty());
1579}
1580
1581TEST(TypeHints, CallingConvention) {
1582 // Check that we don't crash for lambdas with an annotation
1583 // https://github.com/clangd/clangd/issues/2223
1584 Annotations Source(R"cpp(
1585 void test() {
1586 []($lambda[[)]]__cdecl {};
1587 }
1588 )cpp");
1589 TestTU TU = TestTU::withCode(Source.code());
1590 TU.ExtraArgs.push_back("--target=x86_64-w64-mingw32");
1591 TU.PredefineMacros = true; // for the __cdecl
1592 auto AST = TU.build();
1593
1594 EXPECT_THAT(
1595 hintsOfKind(AST, InlayHintKind::Type, DefaultOptsForTests),
1596 ElementsAre(HintMatcher(ExpectedHint{"-> void", "lambda"}, Source)));
1597}
1598
1599TEST(TypeHints, Decltype) {
1600 assertTypeHints(R"cpp(
1601 $a[[decltype(0)]] a;
1602 $b[[decltype(a)]] b;
1603 const $c[[decltype(0)]] &c = b;
1604
1605 // Don't show for dependent type
1606 template <class T>
1607 constexpr decltype(T{}) d;
1608
1609 $e[[decltype(0)]] e();
1610 auto f() -> $f[[decltype(0)]];
1611
1612 template <class, class> struct Foo;
1613 using G = Foo<$g[[decltype(0)]], float>;
1614
1615 auto $h[[h]] = $i[[decltype(0)]]{};
1616
1617 // No crash
1618 /* error-ok */
1619 auto $j[[s]];
1620 )cpp",
1621 ExpectedHint{": int", "a"}, ExpectedHint{": int", "b"},
1622 ExpectedHint{": int", "c"}, ExpectedHint{": int", "e"},
1623 ExpectedHint{": int", "f"}, ExpectedHint{": int", "g"},
1624 ExpectedHint{": int", "h"}, ExpectedHint{": int", "i"});
1625}
1626
1627TEST(TypeHints, SubstTemplateParameterAliases) {
1628 llvm::StringRef Header = R"cpp(
1629 template <class T> struct allocator {};
1630
1631 template <class T, class A>
1632 struct vector_base {
1633 using pointer = T*;
1634 };
1635
1636 template <class T, class A>
1637 struct internal_iterator_type_template_we_dont_expect {};
1638
1639 struct my_iterator {};
1640
1641 template <class T, class A = allocator<T>>
1642 struct vector : vector_base<T, A> {
1643 using base = vector_base<T, A>;
1644 typedef T value_type;
1645 typedef base::pointer pointer;
1646 using allocator_type = A;
1647 using size_type = int;
1648 using iterator = internal_iterator_type_template_we_dont_expect<T, A>;
1649 using non_template_iterator = my_iterator;
1650
1651 value_type& operator[](int index) { return elements[index]; }
1652 const value_type& at(int index) const { return elements[index]; }
1653 pointer data() { return &elements[0]; }
1654 allocator_type get_allocator() { return A(); }
1655 size_type size() const { return 10; }
1656 iterator begin() { return iterator(); }
1657 non_template_iterator end() { return non_template_iterator(); }
1658
1659 T elements[10];
1660 };
1661 )cpp";
1662
1663 llvm::StringRef VectorIntPtr = R"cpp(
1664 vector<int *> array;
1665 auto $no_modifier[[x]] = array[3];
1666 auto* $ptr_modifier[[ptr]] = &array[3];
1667 auto& $ref_modifier[[ref]] = array[3];
1668 auto& $at[[immutable]] = array.at(3);
1669
1670 auto $data[[data]] = array.data();
1671 auto $allocator[[alloc]] = array.get_allocator();
1672 auto $size[[size]] = array.size();
1673 auto $begin[[begin]] = array.begin();
1674 auto $end[[end]] = array.end();
1675 )cpp";
1676
1677 assertHintsWithHeader(
1678 InlayHintKind::Type, VectorIntPtr, Header, DefaultOptsForTests,
1679 ExpectedHint{": int *", "no_modifier"},
1680 ExpectedHint{": int **", "ptr_modifier"},
1681 ExpectedHint{": int *&", "ref_modifier"},
1682 ExpectedHint{": int *const &", "at"}, ExpectedHint{": int **", "data"},
1683 ExpectedHint{": allocator<int *>", "allocator"},
1684 ExpectedHint{": size_type", "size"}, ExpectedHint{": iterator", "begin"},
1685 ExpectedHint{": non_template_iterator", "end"});
1686
1687 llvm::StringRef VectorInt = R"cpp(
1688 vector<int> array;
1689 auto $no_modifier[[by_value]] = array[3];
1690 auto* $ptr_modifier[[ptr]] = &array[3];
1691 auto& $ref_modifier[[ref]] = array[3];
1692 auto& $at[[immutable]] = array.at(3);
1693
1694 auto $data[[data]] = array.data();
1695 auto $allocator[[alloc]] = array.get_allocator();
1696 auto $size[[size]] = array.size();
1697 auto $begin[[begin]] = array.begin();
1698 auto $end[[end]] = array.end();
1699 )cpp";
1700
1701 assertHintsWithHeader(
1702 InlayHintKind::Type, VectorInt, Header, DefaultOptsForTests,
1703 ExpectedHint{": int", "no_modifier"},
1704 ExpectedHint{": int *", "ptr_modifier"},
1705 ExpectedHint{": int &", "ref_modifier"},
1706 ExpectedHint{": const int &", "at"}, ExpectedHint{": int *", "data"},
1707 ExpectedHint{": allocator<int>", "allocator"},
1708 ExpectedHint{": size_type", "size"}, ExpectedHint{": iterator", "begin"},
1709 ExpectedHint{": non_template_iterator", "end"});
1710
1711 llvm::StringRef TypeAlias = R"cpp(
1712 // If the type alias is not of substituted template parameter type,
1713 // do not show desugared type.
1714 using VeryLongLongTypeName = my_iterator;
1715 using Short = VeryLongLongTypeName;
1716
1717 auto $short_name[[my_value]] = Short();
1718
1719 // Same applies with templates.
1720 template <typename T, typename A>
1721 using basic_static_vector = vector<T, A>;
1722 template <typename T>
1723 using static_vector = basic_static_vector<T, allocator<T>>;
1724
1725 auto $vector_name[[vec]] = static_vector<int>();
1726 )cpp";
1727
1728 assertHintsWithHeader(InlayHintKind::Type, TypeAlias, Header,
1729 DefaultOptsForTests,
1730 ExpectedHint{": Short", "short_name"},
1731 ExpectedHint{": static_vector<int>", "vector_name"});
1732}
1733
1734TEST(DesignatorHints, Basic) {
1735 assertDesignatorHints(R"cpp(
1736 struct S { int x, y, z; };
1737 S s {$x[[1]], $y[[2+2]]};
1738
1739 int x[] = {$0[[0]], $1[[1]]};
1740 )cpp",
1741 ExpectedHint{".x=", "x"}, ExpectedHint{".y=", "y"},
1742 ExpectedHint{"[0]=", "0"}, ExpectedHint{"[1]=", "1"});
1743}
1744
1745TEST(DesignatorHints, Nested) {
1746 assertDesignatorHints(R"cpp(
1747 struct Inner { int x, y; };
1748 struct Outer { Inner a, b; };
1749 Outer o{ $a[[{ $x[[1]], $y[[2]] }]], $bx[[3]] };
1750 )cpp",
1751 ExpectedHint{".a=", "a"}, ExpectedHint{".x=", "x"},
1752 ExpectedHint{".y=", "y"}, ExpectedHint{".b.x=", "bx"});
1753}
1754
1755TEST(DesignatorHints, AnonymousRecord) {
1756 assertDesignatorHints(R"cpp(
1757 struct S {
1758 union {
1759 struct {
1760 struct {
1761 int y;
1762 };
1763 } x;
1764 };
1765 };
1766 S s{$xy[[42]]};
1767 )cpp",
1768 ExpectedHint{".x.y=", "xy"});
1769}
1770
1771TEST(DesignatorHints, Suppression) {
1772 assertDesignatorHints(R"cpp(
1773 struct Point { int a, b, c, d, e, f, g, h; };
1774 Point p{/*a=*/1, .c=2, /* .d = */3, $e[[4]]};
1775 )cpp",
1776 ExpectedHint{".e=", "e"});
1777}
1778
1779TEST(DesignatorHints, StdArray) {
1780 // Designators for std::array should be [0] rather than .__elements[0].
1781 // While technically correct, the designator is useless and horrible to read.
1782 assertDesignatorHints(R"cpp(
1783 template <typename T, int N> struct Array { T __elements[N]; };
1784 Array<int, 2> x = {$0[[0]], $1[[1]]};
1785 )cpp",
1786 ExpectedHint{"[0]=", "0"}, ExpectedHint{"[1]=", "1"});
1787}
1788
1789TEST(DesignatorHints, OnlyAggregateInit) {
1790 assertDesignatorHints(R"cpp(
1791 struct Copyable { int x; } c;
1792 Copyable d{c};
1793
1794 struct Constructible { Constructible(int x); };
1795 Constructible x{42};
1796 )cpp" /*no designator hints expected (but param hints!)*/);
1797}
1798
1799TEST(DesignatorHints, NoCrash) {
1800 assertDesignatorHints(R"cpp(
1801 /*error-ok*/
1802 struct A {};
1803 struct Foo {int a; int b;};
1804 void test() {
1805 Foo f{A(), $b[[1]]};
1806 }
1807 )cpp",
1808 ExpectedHint{".b=", "b"});
1809}
1810
1811TEST(DesignatorHints, ParenInit) {
1812 assertDesignatorHints(R"cpp(
1813 struct S {
1814 int x;
1815 int y;
1816 int z;
1817 };
1818 S s ($x[[1]], $y[[2+2]], $z[[4]]);
1819 )cpp",
1820 ExpectedHint{".x=", "x"}, ExpectedHint{".y=", "y"},
1821 ExpectedHint{".z=", "z"});
1822}
1823
1824TEST(DesignatorHints, ParenInitDerived) {
1825 assertDesignatorHints(R"cpp(
1826 struct S1 {
1827 int a;
1828 int b;
1829 };
1830
1831 struct S2 : S1 {
1832 int c;
1833 int d;
1834 };
1835 S2 s2 ({$a[[0]], $b[[0]]}, $c[[0]], $d[[0]]);
1836 )cpp",
1837 // ExpectedHint{"S1:", "S1"},
1838 ExpectedHint{".a=", "a"}, ExpectedHint{".b=", "b"},
1839 ExpectedHint{".c=", "c"}, ExpectedHint{".d=", "d"});
1840}
1841
1842TEST(DesignatorHints, ParenInitTemplate) {
1843 assertDesignatorHints(R"cpp(
1844 template <typename T>
1845 struct S1 {
1846 int a;
1847 int b;
1848 T* ptr;
1849 };
1850
1851 struct S2 : S1<S2> {
1852 int c;
1853 int d;
1854 S1<int> mem;
1855 };
1856
1857 int main() {
1858 S2 sa ({$a1[[0]], $b1[[0]]}, $c[[0]], $d[[0]], $mem[[S1<int>($a2[[1]], $b2[[2]], $ptr[[nullptr]])]]);
1859 }
1860 )cpp",
1861 ExpectedHint{".a=", "a1"}, ExpectedHint{".b=", "b1"},
1862 ExpectedHint{".c=", "c"}, ExpectedHint{".d=", "d"},
1863 ExpectedHint{".mem=", "mem"}, ExpectedHint{".a=", "a2"},
1864 ExpectedHint{".b=", "b2"},
1865 ExpectedHint{".ptr=", "ptr"});
1866}
1867
1868TEST(InlayHints, RestrictRange) {
1869 Annotations Code(R"cpp(
1870 auto a = false;
1871 [[auto b = 1;
1872 auto c = '2';]]
1873 auto d = 3.f;
1874 )cpp");
1875 auto AST = TestTU::withCode(Code.code()).build();
1876 EXPECT_THAT(inlayHints(AST, Code.range()),
1877 ElementsAre(labelIs(": int"), labelIs(": char")));
1878}
1879
1880TEST(ParameterHints, PseudoObjectExpr) {
1881 Annotations Code(R"cpp(
1882 struct S {
1883 __declspec(property(get=GetX, put=PutX)) int x[];
1884 int GetX(int y, int z) { return 42 + y; }
1885 void PutX(int) { }
1886
1887 // This is a PseudoObjectExpression whose syntactic form is a binary
1888 // operator.
1889 void Work(int y) { x = y; } // Not `x = y: y`.
1890 };
1891
1892 int printf(const char *Format, ...);
1893
1894 int main() {
1895 S s;
1896 __builtin_dump_struct(&s, printf); // Not `Format: __builtin_dump_struct()`
1897 printf($Param[["Hello, %d"]], 42); // Normal calls are not affected.
1898 // This builds a PseudoObjectExpr, but here it's useful for showing the
1899 // arguments from the semantic form.
1900 return s.x[ $one[[1]] ][ $two[[2]] ]; // `x[y: 1][z: 2]`
1901 }
1902 )cpp");
1903 auto TU = TestTU::withCode(Code.code());
1904 TU.ExtraArgs.push_back("-fms-extensions");
1905 auto AST = TU.build();
1906 EXPECT_THAT(inlayHints(AST, std::nullopt),
1907 ElementsAre(HintMatcher(ExpectedHint{"Format: ", "Param"}, Code),
1908 HintMatcher(ExpectedHint{"y: ", "one"}, Code),
1909 HintMatcher(ExpectedHint{"z: ", "two"}, Code)));
1910}
1911
1912TEST(ParameterHints, ArgPacksAndConstructors) {
1913 assertParameterHints(
1914 R"cpp(
1915 struct Foo{ Foo(); Foo(int x); };
1916 void foo(Foo a, int b);
1917 template <typename... Args>
1918 void bar(Args... args) {
1919 foo(args...);
1920 }
1921 template <typename... Args>
1922 void baz(Args... args) { foo($param1[[Foo{args...}]], $param2[[1]]); }
1923
1924 template <typename... Args>
1925 void bax(Args... args) { foo($param3[[{args...}]], args...); }
1926
1927 void foo() {
1928 bar($param4[[Foo{}]], $param5[[42]]);
1929 bar($param6[[42]], $param7[[42]]);
1930 baz($param8[[42]]);
1931 bax($param9[[42]]);
1932 }
1933 )cpp",
1934 ExpectedHint{"a: ", "param1"}, ExpectedHint{"b: ", "param2"},
1935 ExpectedHint{"a: ", "param3"}, ExpectedHint{"a: ", "param4"},
1936 ExpectedHint{"b: ", "param5"}, ExpectedHint{"a: ", "param6"},
1937 ExpectedHint{"b: ", "param7"}, ExpectedHint{"x: ", "param8"},
1938 ExpectedHint{"b: ", "param9"});
1939}
1940
1941TEST(ParameterHints, DoesntExpandAllArgs) {
1942 assertParameterHints(
1943 R"cpp(
1944 void foo(int x, int y);
1945 int id(int a, int b, int c);
1946 template <typename... Args>
1947 void bar(Args... args) {
1948 foo(id($param1[[args]], $param2[[1]], $param3[[args]])...);
1949 }
1950 void foo() {
1951 bar(1, 2); // FIXME: We could have `bar(a: 1, a: 2)` here.
1952 }
1953 )cpp",
1954 ExpectedHint{"a: ", "param1"}, ExpectedHint{"b: ", "param2"},
1955 ExpectedHint{"c: ", "param3"});
1956}
1957
1958TEST(BlockEndHints, Functions) {
1959 assertBlockEndHints(R"cpp(
1960 int foo() {
1961 return 41;
1962 $foo[[}]]
1963
1964 template<int X>
1965 int bar() {
1966 // No hint for lambda for now
1967 auto f = []() {
1968 return X;
1969 };
1970 return f();
1971 $bar[[}]]
1972
1973 // No hint because this isn't a definition
1974 int buz();
1975
1976 struct S{};
1977 bool operator==(S, S) {
1978 return true;
1979 $opEqual[[}]]
1980 )cpp",
1981 ExpectedHint{" // foo", "foo"},
1982 ExpectedHint{" // bar", "bar"},
1983 ExpectedHint{" // operator==", "opEqual"});
1984}
1985
1986TEST(BlockEndHints, Methods) {
1987 assertBlockEndHints(R"cpp(
1988 struct Test {
1989 // No hint because there's no function body
1990 Test() = default;
1991
1992 ~Test() {
1993 $dtor[[}]]
1994
1995 void method1() {
1996 $method1[[}]]
1997
1998 // No hint because this isn't a definition
1999 void method2();
2000
2001 template <typename T>
2002 void method3() {
2003 $method3[[}]]
2004
2005 // No hint because this isn't a definition
2006 template <typename T>
2007 void method4();
2008
2009 Test operator+(int) const {
2010 return *this;
2011 $opIdentity[[}]]
2012
2013 operator bool() const {
2014 return true;
2015 $opBool[[}]]
2016
2017 // No hint because there's no function body
2018 operator int() const = delete;
2019 } x;
2020
2021 void Test::method2() {
2022 $method2[[}]]
2023
2024 template <typename T>
2025 void Test::method4() {
2026 $method4[[}]]
2027 )cpp",
2028 ExpectedHint{" // ~Test", "dtor"},
2029 ExpectedHint{" // method1", "method1"},
2030 ExpectedHint{" // method3", "method3"},
2031 ExpectedHint{" // operator+", "opIdentity"},
2032 ExpectedHint{" // operator bool", "opBool"},
2033 ExpectedHint{" // Test::method2", "method2"},
2034 ExpectedHint{" // Test::method4", "method4"});
2035}
2036
2037TEST(BlockEndHints, Namespaces) {
2038 assertBlockEndHints(
2039 R"cpp(
2040 namespace {
2041 void foo();
2042 $anon[[}]]
2043
2044 namespace ns {
2045 void bar();
2046 $ns[[}]]
2047 )cpp",
2048 ExpectedHint{" // namespace", "anon"},
2049 ExpectedHint{" // namespace ns", "ns"});
2050}
2051
2052TEST(BlockEndHints, Types) {
2053 assertBlockEndHints(
2054 R"cpp(
2055 struct S {
2056 $S[[};]]
2057
2058 class C {
2059 $C[[};]]
2060
2061 union U {
2062 $U[[};]]
2063
2064 enum E1 {
2065 $E1[[};]]
2066
2067 enum class E2 {
2068 $E2[[};]]
2069 )cpp",
2070 ExpectedHint{" // struct S", "S"}, ExpectedHint{" // class C", "C"},
2071 ExpectedHint{" // union U", "U"}, ExpectedHint{" // enum E1", "E1"},
2072 ExpectedHint{" // enum class E2", "E2"});
2073}
2074
2075TEST(BlockEndHints, If) {
2076 assertBlockEndHints(
2077 R"cpp(
2078 void foo(bool cond) {
2079 void* ptr;
2080 if (cond)
2081 ;
2082
2083 if (cond) {
2084 $simple[[}]]
2085
2086 if (cond) {
2087 } else {
2088 $ifelse[[}]]
2089
2090 if (cond) {
2091 } else if (!cond) {
2092 $elseif[[}]]
2093
2094 if (cond) {
2095 } else {
2096 if (!cond) {
2097 $inner[[}]]
2098 $outer[[}]]
2099
2100 if (auto X = cond) {
2101 $init[[}]]
2102
2103 if (int i = 0; i > 10) {
2104 $init_cond[[}]]
2105
2106 if (ptr != nullptr) {
2107 $null_check[[}]]
2108 } // suppress
2109 )cpp",
2110 ExpectedHint{" // if cond", "simple"},
2111 ExpectedHint{" // if cond", "ifelse"}, ExpectedHint{" // if", "elseif"},
2112 ExpectedHint{" // if !cond", "inner"},
2113 ExpectedHint{" // if cond", "outer"}, ExpectedHint{" // if X", "init"},
2114 ExpectedHint{" // if i > 10", "init_cond"},
2115 ExpectedHint{" // if ptr != nullptr", "null_check"});
2116}
2117
2118TEST(BlockEndHints, Loops) {
2119 assertBlockEndHints(
2120 R"cpp(
2121 void foo() {
2122 while (true)
2123 ;
2124
2125 while (true) {
2126 $while[[}]]
2127
2128 do {
2129 } while (true);
2130
2131 for (;true;) {
2132 $forcond[[}]]
2133
2134 for (int I = 0; I < 10; ++I) {
2135 $forvar[[}]]
2136
2137 int Vs[] = {1,2,3};
2138 for (auto V : Vs) {
2139 $foreach[[}]]
2140 } // suppress
2141 )cpp",
2142 ExpectedHint{" // while true", "while"},
2143 ExpectedHint{" // for true", "forcond"},
2144 ExpectedHint{" // for I", "forvar"},
2145 ExpectedHint{" // for V", "foreach"});
2146}
2147
2148TEST(BlockEndHints, Switch) {
2149 assertBlockEndHints(
2150 R"cpp(
2151 void foo(int I) {
2152 switch (I) {
2153 case 0: break;
2154 $switch[[}]]
2155 } // suppress
2156 )cpp",
2157 ExpectedHint{" // switch I", "switch"});
2158}
2159
2160TEST(BlockEndHints, PrintLiterals) {
2161 assertBlockEndHints(
2162 R"cpp(
2163 void foo() {
2164 while ("foo") {
2165 $string[[}]]
2166
2167 while ("foo but this time it is very long") {
2168 $string_long[[}]]
2169
2170 while (true) {
2171 $boolean[[}]]
2172
2173 while (1) {
2174 $integer[[}]]
2175
2176 while (1.5) {
2177 $float[[}]]
2178 } // suppress
2179 )cpp",
2180 ExpectedHint{" // while \"foo\"", "string"},
2181 ExpectedHint{" // while \"foo but...\"", "string_long"},
2182 ExpectedHint{" // while true", "boolean"},
2183 ExpectedHint{" // while 1", "integer"},
2184 ExpectedHint{" // while 1.5", "float"});
2185}
2186
2187TEST(BlockEndHints, PrintRefs) {
2188 assertBlockEndHints(
2189 R"cpp(
2190 namespace ns {
2191 int Var;
2192 int func1();
2193 int func2(int, int);
2194 struct S {
2195 int Field;
2196 int method1() const;
2197 int method2(int, int) const;
2198 }; // suppress
2199 } // suppress
2200 void foo() {
2201 int int_a {};
2202 while (ns::Var) {
2203 $var[[}]]
2204
2205 while (ns::func1()) {
2206 $func1[[}]]
2207
2208 while (ns::func2(int_a, int_a)) {
2209 $func2[[}]]
2210
2211 while (ns::S{}.Field) {
2212 $field[[}]]
2213
2214 while (ns::S{}.method1()) {
2215 $method1[[}]]
2216
2217 while (ns::S{}.method2(int_a, int_a)) {
2218 $method2[[}]]
2219 } // suppress
2220 )cpp",
2221 ExpectedHint{" // while Var", "var"},
2222 ExpectedHint{" // while func1()", "func1"},
2223 ExpectedHint{" // while func2(...)", "func2"},
2224 ExpectedHint{" // while Field", "field"},
2225 ExpectedHint{" // while method1()", "method1"},
2226 ExpectedHint{" // while method2(...)", "method2"});
2227}
2228
2229TEST(BlockEndHints, PrintConversions) {
2230 assertBlockEndHints(
2231 R"cpp(
2232 struct S {
2233 S(int);
2234 S(int, int);
2235 explicit operator bool();
2236 }; // suppress
2237 void foo(int I) {
2238 while (float(I)) {
2239 $convert_primitive[[}]]
2240
2241 while (S(I)) {
2242 $convert_class[[}]]
2243
2244 while (S(I, I)) {
2245 $construct_class[[}]]
2246 } // suppress
2247 )cpp",
2248 ExpectedHint{" // while float", "convert_primitive"},
2249 ExpectedHint{" // while S", "convert_class"},
2250 ExpectedHint{" // while S", "construct_class"});
2251}
2252
2253TEST(BlockEndHints, PrintOperators) {
2254 std::string AnnotatedCode = R"cpp(
2255 void foo(Integer I) {
2256 while(++I){
2257 $preinc[[}]]
2258
2259 while(I++){
2260 $postinc[[}]]
2261
2262 while(+(I + I)){
2263 $unary_complex[[}]]
2264
2265 while(I < 0){
2266 $compare[[}]]
2267
2268 while((I + I) < I){
2269 $lhs_complex[[}]]
2270
2271 while(I < (I + I)){
2272 $rhs_complex[[}]]
2273
2274 while((I + I) < (I + I)){
2275 $binary_complex[[}]]
2276 } // suppress
2277 )cpp";
2278
2279 // We can't store shared expectations in a vector, assertHints uses varargs.
2280 auto AssertExpectedHints = [&](llvm::StringRef Code) {
2281 assertBlockEndHints(Code, ExpectedHint{" // while ++I", "preinc"},
2282 ExpectedHint{" // while I++", "postinc"},
2283 ExpectedHint{" // while", "unary_complex"},
2284 ExpectedHint{" // while I < 0", "compare"},
2285 ExpectedHint{" // while ... < I", "lhs_complex"},
2286 ExpectedHint{" // while I < ...", "rhs_complex"},
2287 ExpectedHint{" // while", "binary_complex"});
2288 };
2289
2290 // First with built-in operators.
2291 AssertExpectedHints("using Integer = int;" + AnnotatedCode);
2292 // And now with overloading!
2293 AssertExpectedHints(R"cpp(
2294 struct Integer {
2295 explicit operator bool();
2296 Integer operator++();
2297 Integer operator++(int);
2298 Integer operator+(Integer);
2299 Integer operator+();
2300 bool operator<(Integer);
2301 bool operator<(int);
2302 }; // suppress
2303 )cpp" + AnnotatedCode);
2304}
2305
2306TEST(BlockEndHints, TrailingSemicolon) {
2307 assertBlockEndHints(R"cpp(
2308 // The hint is placed after the trailing ';'
2309 struct S1 {
2310 $S1[[} ;]]
2311
2312 // The hint is always placed in the same line with the closing '}'.
2313 // So in this case where ';' is missing, it is attached to '}'.
2314 struct S2 {
2315 $S2[[}]]
2316
2317 ;
2318
2319 // No hint because only one trailing ';' is allowed
2320 struct S3 {
2321 };;
2322
2323 // No hint because trailing ';' is only allowed for class/struct/union/enum
2324 void foo() {
2325 };
2326
2327 // Rare case, but yes we'll have a hint here.
2328 struct {
2329 int x;
2330 $anon[[}]]
2331
2332 s2;
2333 )cpp",
2334 ExpectedHint{" // struct S1", "S1"},
2335 ExpectedHint{" // struct S2", "S2"},
2336 ExpectedHint{" // struct", "anon"});
2337}
2338
2339TEST(BlockEndHints, TrailingText) {
2340 assertBlockEndHints(R"cpp(
2341 struct S1 {
2342 $S1[[} ;]]
2343
2344 // No hint for S2 because of the trailing comment
2345 struct S2 {
2346 }; /* Put anything here */
2347
2348 struct S3 {
2349 // No hint for S4 because of the trailing source code
2350 struct S4 {
2351 };$S3[[};]]
2352
2353 // No hint for ns because of the trailing comment
2354 namespace ns {
2355 } // namespace ns
2356 )cpp",
2357 ExpectedHint{" // struct S1", "S1"},
2358 ExpectedHint{" // struct S3", "S3"});
2359}
2360
2361TEST(BlockEndHints, Macro) {
2362 assertBlockEndHints(R"cpp(
2363 #define DECL_STRUCT(NAME) struct NAME {
2364 #define RBRACE }
2365
2366 DECL_STRUCT(S1)
2367 $S1[[};]]
2368
2369 // No hint because we require a '}'
2370 DECL_STRUCT(S2)
2371 RBRACE;
2372 )cpp",
2373 ExpectedHint{" // struct S1", "S1"});
2374}
2375
2376TEST(BlockEndHints, PointerToMemberFunction) {
2377 // Do not crash trying to summarize `a->*p`.
2378 assertBlockEndHints(R"cpp(
2379 class A {};
2380 using Predicate = bool(A::*)();
2381 void foo(A* a, Predicate p) {
2382 if ((a->*p)()) {
2383 $ptrmem[[}]]
2384 } // suppress
2385 )cpp",
2386 ExpectedHint{" // if ()", "ptrmem"});
2387}
2388
2389TEST(BlockEndHints, MinLineLimit) {
2390 InlayHintOptions Opts;
2391 Opts.HintMinLineLimit = 10;
2392
2393 // namespace ns below is exactly 10 lines
2394 assertBlockEndHintsWithOpts(
2395 R"cpp(
2396 namespace ns {
2397 int Var;
2398 int func1();
2399 int func2(int, int);
2400 struct S {
2401 int Field;
2402 int method1() const;
2403 int method2(int, int) const;
2404 };
2405 $namespace[[}]]
2406 void foo() {
2407 int int_a {};
2408 while (ns::Var) {
2409 }
2410
2411 while (ns::func1()) {
2412 }
2413
2414 while (ns::func2(int_a, int_a)) {
2415 }
2416
2417 while (ns::S{}.Field) {
2418 }
2419
2420 while (ns::S{}.method1()) {
2421 }
2422
2423 while (ns::S{}.method2(int_a, int_a)) {
2424 }
2425 $foo[[}]]
2426 )cpp",
2427 Opts, ExpectedHint{" // namespace ns", "namespace"},
2428 ExpectedHint{" // foo", "foo"});
2429}
2430
2431// FIXME: Low-hanging fruit where we could omit a type hint:
2432// - auto x = TypeName(...);
2433// - auto x = (TypeName) (...);
2434// - auto x = static_cast<TypeName>(...); // and other built-in casts
2435
2436// Annoyances for which a heuristic is not obvious:
2437// - auto x = llvm::dyn_cast<LongTypeName>(y); // and similar
2438// - stdlib algos return unwieldy __normal_iterator<X*, ...> type
2439// (For this one, perhaps we should omit type hints that start
2440// with a double underscore.)
2441
2442} // namespace
2443} // namespace clangd
2444} // 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:1704
@ BlockEnd
A hint after function, type or namespace definition, indicating the defined symbol name of the defini...
Definition Protocol.h:1734
@ DefaultArgument
An inlay hint that is for a default argument.
Definition Protocol.h:1743
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1717
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1710
@ Designator
A hint before an element of an aggregate braced initializer list, indicating what it is initializing.
Definition Protocol.h:1724
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:44
static clangd::Key< Config > Key
Context key which can be used to set the current Config.
Definition Config.h:48
struct clang::clangd::Config::@041344304366110202143331236314370324353035136032 InlayHints
uint32_t TypeNameLimit
Definition Config.h:201
Inlay hint information.
Definition Protocol.h:1796
std::string joinLabels() const
Join the label[].value together.
Range range
The range of source code to which the hint applies.
Definition Protocol.h:1829
ParsedAST build() const
Definition TestTU.cpp:115
static TestTU withCode(llvm::StringRef Code)
Definition TestTU.h:36