1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
|
diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 2e948c23569f..0dedbcf22bea 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -21,6 +21,7 @@ add_clang_library(clangDaemonTweaks OBJECT
ExpandMacro.cpp
ExtractFunction.cpp
ExtractVariable.cpp
+ ImplementAbstract.cpp
MemberwiseConstructor.cpp
ObjCLocalizeStringLiteral.cpp
ObjCMemberwiseInitializer.cpp
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ImplementAbstract.cpp b/clang-tools-extra/clangd/refactor/tweaks/ImplementAbstract.cpp
new file mode 100644
index 000000000000..40c380ab6e44
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/ImplementAbstract.cpp
@@ -0,0 +1,417 @@
+//===--- ImplementAbstract.cpp -----------------------------------*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "refactor/InsertionPoint.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/Basic/Specifiers.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// FIXME: Have some way to control this, maybe in the config?
+constexpr bool DefineMethods = true;
+using MethodAndAccess =
+ llvm::PointerIntPair<const CXXMethodDecl *, 2, AccessSpecifier>;
+
+AccessSpecifier getMostConstrained(AccessSpecifier InheritSpecifier,
+ AccessSpecifier DefinedAs) {
+ return std::max(InheritSpecifier, DefinedAs);
+}
+
+/// Populates \p Overrides with all the methods that are overridden by methods
+/// in \p RD.
+void buildOverrideSet(const CXXRecordDecl &RD,
+ llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Overrides) {
+ for (const CXXMethodDecl *Method : RD.methods()) {
+ if (!Method->isVirtual())
+ continue;
+ for (const auto *Overriding : Method->overridden_methods())
+ Overrides.insert(Overriding);
+ }
+}
+
+bool areAnyBasesDependent(const CXXRecordDecl &RD) {
+ for (const CXXBaseSpecifier &Base : RD.bases()) {
+ const RecordType *RT = Base.getType()->getAs<RecordType>();
+ if (!RT)
+ return true;
+ const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
+ if (!BaseDecl->isPolymorphic())
+ continue;
+ if (areAnyBasesDependent(*BaseDecl))
+ return true;
+ }
+ return false;
+}
+
+/// Detects if there are any non overridden methods declared in \p RD.
+bool detectPureMethodsImpl(
+ const CXXRecordDecl &RD,
+ llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Overrides) {
+ if (RD.getNumBases() > 0) {
+ buildOverrideSet(RD, Overrides);
+ for (const CXXBaseSpecifier &Base : RD.bases()) {
+ const RecordType *RT = Base.getType()->getAs<RecordType>();
+ assert(RT && "There should be no dependent bases at this point");
+ const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
+ if (!BaseDecl->isPolymorphic())
+ continue;
+ if (detectPureMethodsImpl(*BaseDecl, Overrides))
+ return true;
+ }
+ }
+ for (const CXXMethodDecl *Method : RD.methods()) {
+ if (!Method->isPureVirtual())
+ continue;
+ if (!Overrides.contains(Method))
+ return true;
+ }
+ return false;
+}
+
+/// Detects if there are pure virtual methods from the base class \p Base from
+/// \p RD that need an implementation.
+bool hasPureVirtualMethodsFromBase(const CXXRecordDecl &RD,
+ const CXXBaseSpecifier &Base) {
+ assert(llvm::any_of(RD.bases(), [&Base](const CXXBaseSpecifier &Base2) {
+ // CXXBaseSpecifier has no operator== and as DynTypedNode holds a copy, we
+ // can't use pointer identity. This check should ensure the base we have
+ // selected comes from RD.
+ return Base.getTypeSourceInfo() == Base2.getTypeSourceInfo() &&
+ Base.getSourceRange() == Base2.getSourceRange();
+ }));
+ const RecordType *RT = Base.getType()->getAs<RecordType>();
+ if (!RT)
+ return false;
+ const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
+ if (!BaseDecl->isPolymorphic())
+ return false;
+ if (areAnyBasesDependent(*BaseDecl))
+ return false;
+ llvm::SmallPtrSet<const CXXMethodDecl *, 16> Overrides;
+ buildOverrideSet(RD, Overrides);
+ return detectPureMethodsImpl(*BaseDecl, Overrides);
+}
+
+/// Detects if there are pure virtual methods from \p RD base classes that need
+/// an implementation.
+bool hasPureVirtualMethods(const CXXRecordDecl &RD) {
+ if (areAnyBasesDependent(RD))
+ return false;
+ llvm::SmallPtrSet<const CXXMethodDecl *, 16> Overrides;
+ buildOverrideSet(RD, Overrides);
+ return detectPureMethodsImpl(RD, Overrides);
+}
+
+/// Stores all pure methods in \p Record that aren't in \p Overrides in \p
+/// Results. The methods are stored the most constrained access of \p Access and
+/// the AccessSpecifier of the method.
+void collectNonOverriddenPureMethods(
+ const CXXRecordDecl &Record,
+ llvm::SmallVectorImpl<MethodAndAccess> &Results, AccessSpecifier Access,
+ const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Overrides) {
+ for (const CXXMethodDecl *Method : Record.methods()) {
+ if (!Method->isPureVirtual())
+ continue;
+ if (!Overrides.contains(Method))
+ Results.emplace_back(Method,
+ getMostConstrained(Access, Method->getAccess()));
+ }
+}
+
+/// Collect all the pure virtual methods in \p Record and its base classes that
+/// don't appear in \p Overrides, store the results in \p Results. Returns true
+/// if any of the bases are dependent, otherwise false.
+bool collectPureMethodsImpl(
+ const CXXRecordDecl &Record,
+ llvm::SmallVectorImpl<MethodAndAccess> &Results, AccessSpecifier Access,
+ llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Overrides) {
+ if (Record.getNumBases() > 0) {
+ buildOverrideSet(Record, Overrides);
+ for (const CXXBaseSpecifier &Base : Record.bases()) {
+ const RecordType *RT = Base.getType()->getAs<RecordType>();
+ if (!RT)
+ return true;
+ const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
+ if (!BaseDecl->isPolymorphic())
+ continue;
+ if (collectPureMethodsImpl(
+ *BaseDecl, Results,
+ getMostConstrained(Access, Base.getAccessSpecifier()), Overrides))
+ // Propergate any error back up.
+ return true;
+ }
+ }
+ // Add the Pure methods from this class after traversing the bases. This means
+ // when it comes time to create implementation, methods from classes higher up
+ // the heirachy will appear first.
+ collectNonOverriddenPureMethods(Record, Results, Access, Overrides);
+ return false;
+}
+
+/// Collect all the pure virtual methods from the base class \p Base that
+/// haven't been overridden in \p Record. Store the results in \p Results.
+bool collectPureMethodsFromBase(
+ const CXXRecordDecl &RD, const CXXBaseSpecifier &Base,
+ llvm::SmallVectorImpl<MethodAndAccess> &Results) {
+ assert(llvm::any_of(RD.bases(), [&Base](const CXXBaseSpecifier &Base2) {
+ // CXXBaseSpecifier has no operator== and as DynTypedNode holds a copy, we
+ // can't use pointer identity. This check should ensure the base we have
+ // selected comes from RD.
+ return Base.getTypeSourceInfo() == Base2.getTypeSourceInfo() &&
+ Base.getSourceRange() == Base2.getSourceRange();
+ }));
+ const RecordType *RT = Base.getType()->getAs<RecordType>();
+ if (!RT)
+ return true;
+ const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
+ if (!BaseDecl->isPolymorphic())
+ return true;
+ llvm::SmallPtrSet<const CXXMethodDecl *, 16> Overrides;
+ buildOverrideSet(RD, Overrides);
+ return collectPureMethodsImpl(*BaseDecl, Results, Base.getAccessSpecifier(),
+ Overrides);
+}
+
+bool collectAllPureMethods(const CXXRecordDecl &RD,
+ llvm::SmallVectorImpl<MethodAndAccess> &Results) {
+ llvm::SmallPtrSet<const CXXMethodDecl *, 16> Overrides;
+ buildOverrideSet(RD, Overrides);
+ return collectPureMethodsImpl(RD, Results, AS_public, Overrides);
+}
+
+/// Gets the class at the Selection \p Inputs. If the selection is in
+/// the base-specifier-list, The base that it's over will be stored in \p
+/// BaseSpec. \returns nullptr if no class could be found.
+const CXXRecordDecl *
+getSelectedRecord(const Tweak::Selection &Inputs,
+ std::optional<CXXBaseSpecifier> *BaseSpec) {
+ const SelectionTree::Node *Node = Inputs.ASTSelection.commonAncestor();
+ if (!Node)
+ return nullptr;
+ if (const auto *RD = Node->ASTNode.get<CXXRecordDecl>())
+ return RD;
+ // Handle when the selection is over the base specifier. This is recursive
+ // because the base specifier could be a template instantiation containing
+ // multiple nodes.
+ for (; Node->Parent; Node = Node->Parent) {
+ if (const auto *BS = Node->ASTNode.get<CXXBaseSpecifier>()) {
+ if (const auto *RD = Node->Parent->ASTNode.get<CXXRecordDecl>()) {
+ if (BaseSpec)
+ *BaseSpec = *BS;
+ return RD;
+ }
+ }
+ }
+ return nullptr;
+}
+
+/// Some quick to check basic heuristics to check before we try and collect
+/// virtual methods.
+bool isClassOK(const CXXRecordDecl &RecordDecl) {
+ if (!RecordDecl.isThisDeclarationADefinition())
+ return false;
+ if (!RecordDecl.isClass() && !RecordDecl.isStruct())
+ return false;
+ if (RecordDecl.hasAnyDependentBases() || RecordDecl.getNumBases() == 0)
+ return false;
+ // We should check for abstract, but that prevents working on template classes
+ // that don't have any dependent bases.
+ if (!RecordDecl.isPolymorphic())
+ return false;
+ return true;
+}
+
+class PrintingInContextCallback : public PrintingCallbacks {
+public:
+ PrintingInContextCallback(const DeclContext *CurContext)
+ : CurContext(CurContext) {}
+ virtual ~PrintingInContextCallback() = default;
+ bool isScopeVisible(const DeclContext *DC) const override {
+ return DC->Encloses(CurContext);
+ }
+
+ PrintingPolicy getPolicy() const {
+ PrintingPolicy P = CurContext->getParentASTContext().getPrintingPolicy();
+ P.SuppressScope = false;
+ P.Callbacks = this;
+ return P;
+ }
+
+private:
+ const DeclContext *CurContext;
+};
+
+bool buildBody(llvm::raw_ostream &Out, ArrayRef<MethodAndAccess> Items,
+ AccessSpecifier AccessKind, const PrintingPolicy &Policy) {
+ bool Any = false;
+ for (const auto &MethodAndAccess : Items) {
+ if (MethodAndAccess.getInt() != AccessKind)
+ continue;
+ Any = true;
+ const CXXMethodDecl *Method = MethodAndAccess.getPointer();
+ Method->getReturnType().print(Out, Policy);
+ Out << ' ';
+ Out << Method->getNameAsString() << "(";
+ bool IsFirst = true;
+ for (const auto &Param : Method->parameters()) {
+ if (!IsFirst)
+ Out << ", ";
+ else
+ IsFirst = false;
+ Param->print(Out, Policy);
+ }
+ Out << ") ";
+ if (Method->isConst())
+ Out << "const ";
+ if (Method->isVolatile())
+ Out << "volatile ";
+ if (DefineMethods) {
+ Out << "override {\n";
+ if (!Method->getReturnType()->isVoidType())
+ Out << "return {};\n";
+ Out << "}\n";
+ } else {
+ Out << "override;\n";
+ }
+ }
+ return Any;
+}
+
+class ImplementAbstract : public Tweak {
+public:
+ const char *id() const override;
+
+ bool prepare(const Selection &Inputs) override {
+ Selected = getSelectedRecord(Inputs, &FromBase);
+ if (!Selected)
+ return false;
+ if (!isClassOK(*Selected))
+ return false;
+ if (FromBase)
+ return hasPureVirtualMethodsFromBase(*Selected, *FromBase);
+
+ return hasPureVirtualMethods(*Selected);
+ }
+
+ Expected<Effect> apply(const Selection &Inputs) override {
+
+ llvm::SmallVector<MethodAndAccess> PureVirtualMethods;
+ auto Res = FromBase ? collectPureMethodsFromBase(*Selected, *FromBase,
+ PureVirtualMethods)
+ : collectAllPureMethods(*Selected, PureVirtualMethods);
+
+ (void)Res;
+ assert(!Res && !PureVirtualMethods.empty());
+
+ PrintingInContextCallback Callbacks(Selected);
+ PrintingPolicy Policy = Callbacks.getPolicy();
+
+ SmallString<256> Buffer;
+ llvm::raw_svector_ostream OS(Buffer);
+ tooling::Replacements Replacements;
+
+ std::vector<Anchor> Anchors = {
+ // Below all constructors
+ {[](const Decl *D) { return llvm::isa<CXXConstructorDecl>(D); },
+ Anchor::Below},
+ // Above destructor
+ {[](const Decl *D) { return llvm::isa<CXXDestructorDecl>(D); },
+ Anchor::Above},
+ // Above fields
+ {[](const Decl *D) { return llvm::isa<FieldDecl>(D); }, Anchor::Above},
+ };
+
+ AccessSpecifier Last = Selected->isClass() ? AS_private : AS_public;
+ for (auto *D : Selected->decls()) {
+ if (auto *ASD = dyn_cast<AccessSpecDecl>(D)) {
+ Last = ASD->getAccess();
+ }
+ }
+
+ if (buildBody(OS, PureVirtualMethods, Last, Policy)) {
+ auto Replacement = insertDecl(Buffer, *Selected, Anchors, Last);
+ if (!Replacement)
+ return Replacement.takeError();
+ llvm::cantFail(Replacements.add(*Replacement));
+ Buffer.clear();
+ }
+
+ for (AccessSpecifier Spec : {AS_public, AS_protected, AS_private}) {
+ if (Spec == Last)
+ continue;
+ if (!buildBody(OS, PureVirtualMethods, Spec, Policy))
+ continue;
+ auto Replacement = insertDecl(Buffer, *Selected, Anchors, Spec);
+ if (!Replacement)
+ return Replacement.takeError();
+ if (auto Err = Replacements.add(*Replacement)) {
+ Err = llvm::handleErrors(
+ std::move(Err),
+ [&Replacements](
+ const tooling::ReplacementError &RE) -> llvm::Error {
+ if (RE.get() != tooling::replacement_error::insert_conflict)
+ return llvm::make_error<tooling::ReplacementError>(RE);
+ const auto &Conflict = RE.getNewReplacement();
+ tooling::Replacement NewR(
+ Conflict->getFilePath(),
+ Replacements.getShiftedCodePosition(
+ RE.getExistingReplacement()->getOffset()),
+ 0, Conflict->getReplacementText());
+ Replacements = Replacements.merge(tooling::Replacements(NewR));
+ return llvm::Error::success();
+ });
+ if (Err)
+ return std::move(Err);
+ }
+ Buffer.clear();
+ }
+
+ return Effect::mainFileEdit(Inputs.AST->getASTContext().getSourceManager(),
+ std::move(Replacements));
+ }
+
+ std::string title() const override {
+ if (FromBase) {
+ assert(Selected);
+ PrintingInContextCallback Callbacks(Selected->getDeclContext());
+ std::string Result = "Implement pure virtual methods from '";
+ llvm::raw_string_ostream OS(Result);
+ FromBase->getTypeSourceInfo()->getType().print(OS, Callbacks.getPolicy());
+ OS << '\'';
+ OS.flush();
+ return Result;
+ }
+ return "Implement pure virtual methods";
+ }
+
+ llvm::StringLiteral kind() const override {
+ return CodeAction::REFACTOR_KIND;
+ }
+
+private:
+ const CXXRecordDecl *Selected;
+ std::optional<CXXBaseSpecifier> FromBase;
+};
+
+REGISTER_TWEAK(ImplementAbstract)
+
+} // namespace
+} // namespace clangd
+} // namespace clang
diff --git a/clang-tools-extra/clangd/unittests/CMakeLists.txt b/clang-tools-extra/clangd/unittests/CMakeLists.txt
index 4fa9f18407ae..0cec15c387bc 100644
--- a/clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ b/clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -128,6 +128,7 @@ add_unittest(ClangdUnitTests ClangdTests
tweaks/ExpandMacroTests.cpp
tweaks/ExtractFunctionTests.cpp
tweaks/ExtractVariableTests.cpp
+ tweaks/ImplementAbstractTests.cpp
tweaks/MemberwiseConstructorTests.cpp
tweaks/ObjCLocalizeStringLiteralTests.cpp
tweaks/ObjCMemberwiseInitializerTests.cpp
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp
new file mode 100644
index 000000000000..711bd5d123d6
--- /dev/null
+++ b/clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp
@@ -0,0 +1,427 @@
+//===-- ImplementAbstractTests.cpp ------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestTU.h"
+#include "TweakTesting.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using ::testing::Not;
+
+namespace clang {
+namespace clangd {
+namespace {
+
+bool stringEqIgnoreWs(StringRef LHS, StringRef RHS) {
+ auto TrimmedL = LHS.trim();
+ auto TrimmedR = RHS.trim();
+ static constexpr llvm::StringLiteral WS(" \t\r\n\f\v");
+
+ while (!TrimmedL.empty() && !TrimmedR.empty()) {
+ auto LPos = TrimmedL.find_first_of(WS);
+ auto RPos = TrimmedR.find_first_of(WS);
+ if (TrimmedL.take_front(LPos) != TrimmedR.take_front(RPos))
+ return false;
+ TrimmedL =
+ TrimmedL.substr(LPos).drop_while([](char C) { return WS.contains(C); });
+ TrimmedR =
+ TrimmedR.substr(RPos).drop_while([](char C) { return WS.contains(C); });
+ }
+ return TrimmedL == TrimmedR;
+}
+
+MATCHER_P(STREQWS, EqualTo, "") {
+ if (stringEqIgnoreWs(arg, EqualTo))
+ return true;
+
+ auto Result =
+ testing::internal::EqFailure("", "", arg, std::string(EqualTo), false);
+ *result_listener << Result.message();
+ return false;
+}
+
+TWEAK_TEST(ImplementAbstract);
+
+TEST_F(ImplementAbstractTest, TestUnavailable) {
+
+ StringRef Cases[]{
+ // Not a pure virtual method.
+ R"cpp(
+ class A {
+ virtual void Foo();
+ };
+ class ^B : public A {};
+ )cpp",
+ // Pure virtual method overridden in class.
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };
+ class ^B : public A {
+ void Foo() override;
+ };
+ )cpp",
+ // Pure virtual method overridden in class with virtual keyword
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };
+ class ^B : public A {
+ virtual void Foo() override;
+ };
+ )cpp",
+ // Pure virtual method overridden in class without override keyword
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };
+ class ^B : public A {
+ void Foo();
+ };
+ )cpp",
+ // Pure virtual method overriden in base class.
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };
+ class B : public A {
+ void Foo() override;
+ };
+ class ^C : public B {};
+ )cpp"};
+ for (const auto &Case : Cases) {
+ EXPECT_THAT(Case, Not(isAvailable()));
+ }
+}
+
+TEST_F(ImplementAbstractTest, NormalAvailable) {
+ struct Case {
+ llvm::StringRef TestHeader;
+ llvm::StringRef TestSource;
+ llvm::StringRef ExpectedSource;
+ };
+
+ Case Cases[]{
+ {
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };)cpp",
+ R"cpp(
+ class B : public A {
+ ^};
+ )cpp",
+ R"cpp(
+ class B : public A {
+ void Foo() override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ public:
+ virtual int Foo() = 0;
+ };)cpp",
+ R"cpp(
+ class ^B : public A {
+ };
+ )cpp",
+ R"cpp(
+ class B : public A {
+ public:
+ int Foo() override {
+ return {};
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo(int Param) = 0;
+ };)cpp",
+ R"cpp(
+ class ^B : public A {
+ };
+ )cpp",
+ R"cpp(
+ class B : public A {
+ void Foo(int Param) override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo(int Param) = 0;
+ };)cpp",
+ R"cpp(
+ struct ^B : public A {
+ };
+ )cpp",
+ R"cpp(
+ struct B : public A {
+ private:
+ void Foo(int Param) override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo(int Param) const volatile = 0;
+
+ public:
+ virtual void Bar(int Param) = 0;
+ };)cpp",
+ R"cpp(
+ class ^B : public A {
+ void Foo(int Param) const volatile override;
+ };
+ )cpp",
+ R"cpp(
+ class B : public A {
+ void Foo(int Param) const volatile override;
+
+ public:
+ void Bar(int Param) override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ virtual void Bar() = 0;
+ };
+ class B : public A {
+ void Foo() override {
+ }
+ };
+ )cpp",
+ R"cpp(
+ class ^C : public B {
+ virtual void Baz();
+ };
+ )cpp",
+ R"cpp(
+ class C : public B {
+ virtual void Baz();
+ void Bar() override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };)cpp",
+ R"cpp(
+ class ^B : public A {
+ ~B();
+ };
+ )cpp",
+ R"cpp(
+ class B : public A {
+ void Foo() override {
+ }
+
+ ~B();
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+
+ public:
+ virtual void Bar() = 0;
+ };)cpp",
+ R"cpp(
+ class ^B : public A {
+ };
+ )cpp",
+ R"cpp(
+ class B : public A {
+ void Foo() override {
+ }
+
+ public:
+ void Bar() override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };
+ struct B : public A {
+ virtual void Bar() = 0;
+ };)cpp",
+ R"cpp(
+ class ^C : public B {
+ };
+ )cpp",
+ R"cpp(
+ class C : public B {
+ void Foo() override {
+ }
+
+ public:
+ void Bar() override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };
+ struct B : public A {
+ virtual void Bar() = 0;
+ };)cpp",
+ R"cpp(
+ class ^C : private B {
+ };
+ )cpp",
+ R"cpp(
+ class C : private B {
+ void Foo() override {
+ }
+ void Bar() override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ struct A {
+ virtual void Foo() = 0;
+ };
+ struct B {
+ virtual void Bar() = 0;
+ };)cpp",
+ R"cpp(
+ class C : public ^A, B {
+ };
+ )cpp",
+ R"cpp(
+ class C : public A, B {
+ public:
+ void Foo() override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ struct A {
+ virtual void Foo() = 0;
+ };
+ struct B {
+ virtual void Bar() = 0;
+ };)cpp",
+ R"cpp(
+ class ^C : public A, B {
+ };
+ )cpp",
+ R"cpp(
+ class C : public A, B {
+ void Bar() override {
+ }
+
+ public:
+ void Foo() override {
+ }
+ };
+ )cpp",
+ },
+ };
+
+ for (const auto &Case : Cases) {
+ Header = Case.TestHeader.str();
+ EXPECT_THAT(apply(Case.TestSource), STREQWS(Case.ExpectedSource));
+ }
+}
+
+TEST_F(ImplementAbstractTest, TemplateUnavailable) {
+ StringRef Cases[]{
+ R"cpp(
+ template <typename T> class A { virtual void Foo() = 0; };
+ template <typename T> class ^B : public A<T> {};
+ )cpp",
+ R"cpp(
+ template <typename T> class ^B : public T{};
+ )cpp",
+ };
+ for (const auto &Case : Cases) {
+ EXPECT_THAT(Case, Not(isAvailable()));
+ }
+}
+
+TEST_F(ImplementAbstractTest, TemplateAvailable) {
+ struct Case {
+ llvm::StringRef TestHeader;
+ llvm::StringRef TestSource;
+ llvm::StringRef ExpectedSource;
+ };
+ Case Cases[]{
+ {
+ R"cpp(
+ template <typename T> class A { virtual void Foo() = 0; };
+ )cpp",
+ R"cpp(
+ class ^B : public A<int> {
+
+ };
+ )cpp",
+ R"cpp(
+ class B : public A<int> {
+ void Foo() override {
+ }
+ };
+ )cpp",
+ },
+ {
+ R"cpp(
+ class A {
+ virtual void Foo() = 0;
+ };)cpp",
+ R"cpp(
+ template <typename T> class ^B : public A {
+
+ };
+ )cpp",
+ R"cpp(
+ template <typename T> class B : public A {
+ void Foo() override {
+ }
+ };
+ )cpp",
+ },
+ };
+ for (const auto &Case : Cases) {
+ Header = Case.TestHeader.str();
+ EXPECT_THAT(apply(Case.TestSource), STREQWS(Case.ExpectedSource));
+ }
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
|