forked from apple/swift-clang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClangRefactorTest.cpp
1404 lines (1276 loc) · 54.7 KB
/
ClangRefactorTest.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- ClangRefactorTest.cpp - ------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a clang-refactor-test tool that is used to test the
// refactoring library in Clang.
//
//===----------------------------------------------------------------------===//
#include "clang-c/Refactor.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/Tooling/Refactor/SymbolName.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/LineIterator.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace clang;
namespace opts {
static cl::OptionCategory
ClangRefactorTestOptions("clang-refactor-test common options");
cl::SubCommand RenameInitiateSubcommand(
"rename-initiate", "Initiate renaming in an initial translation unit");
cl::SubCommand RenameInitiateUSRSubcommand(
"rename-initiate-usr",
"Initiate renaming in an translation unit on a specific declaration");
cl::SubCommand RenameIndexedFileSubcommand(
"rename-indexed-file",
"Initiate renaming and find occurrences in an indexed file");
cl::SubCommand ListRefactoringActionsSubcommand("list-actions",
"Print the list of the "
"refactoring actions that can "
"be performed at the specified "
"location");
cl::SubCommand InitiateActionSubcommand("initiate",
"Initiate a refactoring action");
cl::SubCommand
PerformActionSubcommand("perform",
"Initiate and perform a refactoring action");
const cl::desc
AtOptionDescription("The location at which the refactoring should be "
"initiated (<file>:<line>:<column>)");
const cl::desc InRangeOptionDescription(
"The location(s) at which the refactoring should be "
"initiated (<file>:<line>:<column>-<last-column>)");
const cl::desc SelectedRangeOptionDescription(
"The selected source range in which the refactoring should be "
"initiated (<file>:<line>:<column>-<line>:<column>)");
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
namespace rename {
static cl::list<std::string> AtLocation("at", AtOptionDescription, cl::Required,
cl::cat(ClangRefactorTestOptions),
cl::sub(RenameInitiateSubcommand),
cl::OneOrMore);
static cl::opt<std::string>
USR("usr", cl::desc("The USR of the declaration that should be renamed"),
cl::cat(ClangRefactorTestOptions), cl::sub(RenameInitiateUSRSubcommand),
cl::Required);
static cl::opt<std::string>
NewName("new-name", cl::desc("The new name to change the symbol to."),
cl::Required, cl::cat(ClangRefactorTestOptions),
cl::sub(RenameInitiateSubcommand),
cl::sub(RenameInitiateUSRSubcommand));
static cl::list<std::string>
IndexedNames("name", cl::desc("The names of the renamed symbols"),
cl::Required, cl::OneOrMore, cl::cat(ClangRefactorTestOptions),
cl::sub(RenameIndexedFileSubcommand));
static cl::list<std::string> IndexedNewNames(
"new-name", cl::desc("The new name to change the symbol to."), cl::Required,
cl::OneOrMore, cl::cat(ClangRefactorTestOptions),
cl::sub(RenameIndexedFileSubcommand));
static cl::opt<std::string>
IndexedSymbolKind("indexed-symbol-kind",
cl::desc("The kind of the indexed symbol."), cl::Optional,
cl::cat(ClangRefactorTestOptions),
cl::sub(RenameIndexedFileSubcommand));
static cl::opt<std::string>
IndexedFileName("indexed-file", cl::desc("The name of the indexed file"),
cl::Required, cl::cat(ClangRefactorTestOptions),
cl::sub(RenameIndexedFileSubcommand));
static cl::list<std::string>
IndexedLocations("indexed-at",
cl::desc("The location of an indexed occurrence "
"([<kind>|<symbol-index>:]<line>:<column>)"),
cl::ZeroOrMore, cl::cat(ClangRefactorTestOptions),
cl::sub(RenameIndexedFileSubcommand));
static cl::opt<bool> AvoidTextual(
"no-textual-matches", cl::desc("Avoid searching for textual matches"),
cl::cat(ClangRefactorTestOptions), cl::sub(RenameIndexedFileSubcommand));
static cl::opt<bool> DumpSymbols(
"dump-symbols", cl::desc("Dump the information about the renamed symbols"),
cl::cat(ClangRefactorTestOptions), cl::sub(RenameInitiateSubcommand),
cl::sub(RenameInitiateUSRSubcommand));
}
namespace listActions {
cl::opt<std::string> AtLocation("at", AtOptionDescription, cl::Required,
cl::cat(ClangRefactorTestOptions),
cl::sub(ListRefactoringActionsSubcommand));
cl::opt<std::string> SelectedRange("selected", SelectedRangeOptionDescription,
cl::cat(ClangRefactorTestOptions),
cl::sub(ListRefactoringActionsSubcommand));
cl::opt<bool> DumpRawActionType(
"dump-raw-action-type",
cl::desc("Prints the action type integer value for each listed action"),
cl::cat(ClangRefactorTestOptions),
cl::sub(ListRefactoringActionsSubcommand));
}
namespace initiateAndPerform {
cl::list<std::string> InLocationRanges("in", cl::ZeroOrMore,
InRangeOptionDescription,
cl::cat(ClangRefactorTestOptions),
cl::sub(InitiateActionSubcommand));
cl::list<std::string> AtLocations("at", cl::ZeroOrMore, AtOptionDescription,
cl::cat(ClangRefactorTestOptions),
cl::sub(InitiateActionSubcommand),
cl::sub(PerformActionSubcommand));
cl::list<std::string> SelectedRanges("selected", cl::ZeroOrMore,
SelectedRangeOptionDescription,
cl::cat(ClangRefactorTestOptions),
cl::sub(InitiateActionSubcommand),
cl::sub(PerformActionSubcommand));
cl::opt<std::string> ActionName("action", cl::Required,
cl::desc("The name of the refactoring action"),
cl::cat(ClangRefactorTestOptions),
cl::sub(InitiateActionSubcommand),
cl::sub(PerformActionSubcommand));
cl::opt<bool> LocationAgnostic(
"location-agnostic",
cl::desc(
"Ignore the location of initiation when verifying result consistency"),
cl::cat(ClangRefactorTestOptions), cl::sub(InitiateActionSubcommand));
cl::opt<unsigned> CandidateIndex(
"candidate",
cl::desc(
"The index of the refactoring candidate which should be performed"),
cl::cat(ClangRefactorTestOptions), cl::sub(PerformActionSubcommand));
cl::opt<std::string> ContinuationFile(
"continuation-file",
cl::desc("The source file in which the continuation should run"),
cl::cat(ClangRefactorTestOptions), cl::sub(PerformActionSubcommand));
cl::opt<std::string> QueryResults(
"query-results", cl::desc("The indexer query results that should be passed "
"into the continuation"),
cl::cat(ClangRefactorTestOptions), cl::sub(PerformActionSubcommand));
cl::opt<bool> EmitAssociatedInfo(
"emit-associated", cl::desc("Dump additional associated information"),
cl::cat(ClangRefactorTestOptions), cl::sub(PerformActionSubcommand));
}
cl::opt<bool> Apply(
"apply",
cl::desc(
"Apply the changes and print the modified file to standard output"),
cl::cat(ClangRefactorTestOptions), cl::sub(PerformActionSubcommand),
cl::sub(RenameInitiateSubcommand), cl::sub(RenameIndexedFileSubcommand));
cl::opt<bool>
Diff("diff",
cl::desc("Display the replaced text in red when -apply is specified"),
cl::cat(ClangRefactorTestOptions), cl::sub(PerformActionSubcommand),
cl::sub(RenameInitiateSubcommand),
cl::sub(RenameIndexedFileSubcommand));
cl::opt<int> Context("context", cl::desc("How many lines of context should be "
"displayed when -apply is specified"),
cl::cat(ClangRefactorTestOptions),
cl::sub(PerformActionSubcommand),
cl::sub(RenameInitiateSubcommand),
cl::sub(RenameIndexedFileSubcommand));
static cl::opt<std::string> FileName(
cl::Positional, cl::desc("<filename>"), cl::Required,
cl::cat(ClangRefactorTestOptions), cl::sub(RenameInitiateSubcommand),
cl::sub(RenameInitiateUSRSubcommand), cl::sub(RenameIndexedFileSubcommand),
cl::sub(ListRefactoringActionsSubcommand),
cl::sub(InitiateActionSubcommand), cl::sub(PerformActionSubcommand));
static cl::opt<bool> IgnoreFilenameForInitiationTU(
"ignore-filename-for-initiation-tu", cl::Optional,
cl::cat(ClangRefactorTestOptions), cl::sub(RenameIndexedFileSubcommand));
static cl::list<std::string> CompilerArguments(
cl::ConsumeAfter, cl::desc("<arguments to be passed to the compiler>"),
cl::cat(ClangRefactorTestOptions), cl::sub(RenameInitiateSubcommand),
cl::sub(RenameInitiateUSRSubcommand), cl::sub(RenameIndexedFileSubcommand),
cl::sub(ListRefactoringActionsSubcommand),
cl::sub(InitiateActionSubcommand), cl::sub(PerformActionSubcommand));
static cl::opt<std::string> ImplementationTU(
"implementation-tu", cl::desc("The name of the implementation TU"),
cl::cat(ClangRefactorTestOptions), cl::sub(RenameInitiateSubcommand));
}
static const char *renameOccurrenceKindString(CXSymbolOccurrenceKind Kind,
bool IsLocal,
bool IsMacroExpansion) {
switch (Kind) {
case CXSymbolOccurrence_MatchingSymbol:
return IsMacroExpansion ? "macro" : IsLocal ? "rename local" : "rename";
case CXSymbolOccurrence_MatchingSelector:
assert(!IsLocal && "Objective-C selector renames must be global");
return IsMacroExpansion ? "selector in macro" : "selector";
case CXSymbolOccurrence_MatchingImplicitProperty:
assert(!IsLocal);
return IsMacroExpansion ? "implicit-property in macro"
: "implicit-property";
case CXSymbolOccurrence_MatchingCommentString:
return "comment";
case CXSymbolOccurrence_MatchingDocCommentString:
return "documentation";
case CXSymbolOccurrence_MatchingFilename:
return "filename";
case CXSymbolOccurrence_MatchingStringLiteral:
return "string-literal";
case CXSymbolOccurrence_ExtractedDeclaration:
return "extracted-decl";
case CXSymbolOccurrence_ExtractedDeclaration_Reference:
return "extracted-decl-ref";
}
llvm_unreachable("unexpected CXSymbolOccurrenceKind value");
}
static int apply(ArrayRef<CXRefactoringReplacement> Replacements,
StringRef Filename) {
// Assume that the replacements are sorted.
auto Result = MemoryBuffer::getFile(Filename);
if (!Result) {
errs() << "Failed to open " << Filename << "\n";
return 1;
}
raw_ostream &OS = outs();
int Context = opts::Context;
MemoryBuffer &Buffer = **Result;
std::vector<std::pair<StringRef, std::vector<CXRefactoringReplacement>>>
Lines;
for (auto I = line_iterator(Buffer, /*SkipBlanks=*/false),
E = line_iterator();
I != E; ++I)
Lines.push_back(
std::make_pair(*I, std::vector<CXRefactoringReplacement>()));
unsigned FlushedLine = 1;
auto FlushUntil = [&](unsigned Line) {
// Adjust the first flushed line if needed when printing in context mode.
if (FlushedLine == 1 && Context)
FlushedLine = std::max(int(Line) - Context, 1);
for (; FlushedLine < Line; ++FlushedLine) {
const auto &Line = Lines[FlushedLine - 1];
if (Line.second.empty()) {
OS << Line.first << "\n";
continue;
}
unsigned I = 0;
for (const CXRefactoringReplacement &Replacement : Line.second) {
OS << Line.first.substr(I, Replacement.Range.Begin.Column - 1 - I);
if (opts::Diff) {
OS.changeColor(raw_ostream::RED, false, true);
OS << Line.first.substr(Replacement.Range.Begin.Column - 1,
Replacement.Range.End.Column - 1 -
(Replacement.Range.Begin.Column - 1));
}
OS.changeColor(raw_ostream::GREEN);
OS << clang_getCString(Replacement.ReplacementString);
OS.resetColor();
I = Replacement.Range.End.Column - 1;
}
OS << Line.first.substr(I);
if (I < Line.first.size() || opts::Diff)
OS << "\n";
}
};
int EndLineMax = 0;
for (const CXRefactoringReplacement &Replacement : Replacements) {
EndLineMax = std::max(int(Replacement.Range.End.Line), EndLineMax);
unsigned StartingLine = Replacement.Range.Begin.Line;
FlushUntil(StartingLine);
if (Replacement.Range.End.Line == StartingLine) {
Lines[StartingLine - 1].second.push_back(Replacement);
continue;
}
// Multi-line replacements have to be split
for (unsigned I = StartingLine; I <= Replacement.Range.End.Line; ++I) {
CXRefactoringReplacement NewReplacement;
if (I == Replacement.Range.End.Line)
NewReplacement.ReplacementString = Replacement.ReplacementString;
else
// FIXME: This is a hack to workaround the fact that the API doesn't
// provide a way to create a null string. This should be fixed when
// upstreaming.
NewReplacement.ReplacementString = {0, 0};
NewReplacement.Range.Begin.Line = I;
NewReplacement.Range.Begin.Column =
I == StartingLine ? Replacement.Range.Begin.Column : 1;
NewReplacement.Range.End.Line = I;
NewReplacement.Range.End.Column = I == Replacement.Range.End.Line
? Replacement.Range.End.Column
: Lines[I - 1].first.size() + 1;
NewReplacement.AssociatedData = nullptr;
Lines[I - 1].second.push_back(NewReplacement);
}
}
FlushUntil(Context ? std::min(int(Lines.size()), EndLineMax + Context) + 1
: Lines.size() + 2);
// Print out a dividor when printing in the context mode.
if (Context) {
for (int I = 0; I < 80; ++I)
OS << '-';
OS << "\n";
}
return 0;
}
/// Converts the given renamed \p Occurrence into a string value that represents
/// this occurrence.
static std::string
occurrenceToString(const CXSymbolOccurrence &Occurrence, bool IsLocal,
const tooling::OldSymbolName &NewName,
const tooling::OldSymbolName &ExpectedReplacementStrings,
StringRef Filename) {
std::string Str;
llvm::raw_string_ostream OS(Str);
OS << renameOccurrenceKindString(Occurrence.Kind, IsLocal,
Occurrence.IsMacroExpansion)
<< ' ';
if (!Filename.empty())
OS << '"' << Filename << "\" ";
bool FirstRange = true;
assert(NewName.size() >= Occurrence.NumNamePieces &&
"new name doesn't match the number of pieces");
for (unsigned J = 0; J != Occurrence.NumNamePieces; ++J) {
if (!FirstRange) // TODO
OS << ", ";
// Print the replacement string if it doesn't match the expected string.
if (NewName[J] != ExpectedReplacementStrings[J])
OS << '"' << NewName[J] << "\" ";
CXFileRange Range = Occurrence.NamePieces[J];
OS << Range.Begin.Line << ":" << Range.Begin.Column << " -> "
<< Range.End.Line << ":" << Range.End.Column;
FirstRange = false;
}
return OS.str();
}
static CXCursorKind
renameIndexedOccurrenceKindStringToKind(StringRef Str, CXCursorKind Default) {
return llvm::StringSwitch<CXCursorKind>(Str)
.Case("objc-im", CXCursor_ObjCInstanceMethodDecl)
.Case("objc-cm", CXCursor_ObjCClassMethodDecl)
.Case("objc-message", CXCursor_ObjCMessageExpr)
.Case("include", CXCursor_InclusionDirective)
.Case("objc-class", CXCursor_ObjCInterfaceDecl)
.Default(Default);
}
/// Parses the string passed as the -indexed-at argument.
std::pair<CXRenamedIndexedSymbolLocation, unsigned>
parseIndexedOccurrence(StringRef IndexedOccurrence,
CXCursorKind DefaultCursorKind) {
StringRef LineColumnLoc = IndexedOccurrence;
CXCursorKind Kind = DefaultCursorKind;
unsigned SymbolIndex = 0;
if (LineColumnLoc.count(':') > 1) {
std::pair<StringRef, StringRef> Split = LineColumnLoc.split(':');
// The first value is either the kind or the symbol index.
if (Split.first.getAsInteger(10, SymbolIndex)) {
if (Split.second.count(':') > 1) {
std::pair<StringRef, StringRef> SecondSplit = Split.second.split(':');
if (SecondSplit.first.getAsInteger(10, SymbolIndex))
assert(false && "expected symbol index");
Split.second = SecondSplit.second;
}
Kind = renameIndexedOccurrenceKindStringToKind(Split.first, Kind);
}
LineColumnLoc = Split.second;
}
auto Loc = std::string("-:") + LineColumnLoc.str();
auto Location = ParsedSourceLocation::FromString(Loc);
return std::make_pair(
CXRenamedIndexedSymbolLocation{{Location.Line, Location.Column}, Kind},
SymbolIndex);
}
/// Compare the produced occurrences to the expected occurrences that were
/// gathered at the first location. Return true if the occurrences are
/// different.
static bool compareOccurrences(ArrayRef<std::string> ExpectedReplacements,
CXSymbolOccurrencesResult Occurrences,
bool IsLocal,
const tooling::OldSymbolName &NewSymbolName,
bool PrintFilenames) {
unsigned NumFiles = clang_SymbolOccurrences_getNumFiles(Occurrences);
size_t ExpectedReplacementIndex = 0;
for (unsigned FileIndex = 0; FileIndex < NumFiles; ++FileIndex) {
CXSymbolOccurrencesInFile FileResult;
clang_SymbolOccurrences_getOccurrencesForFile(Occurrences, FileIndex,
&FileResult);
StringRef Filename =
PrintFilenames ? clang_getCString(FileResult.Filename) : "";
for (unsigned I = 0; I != FileResult.NumOccurrences; ++I) {
std::string Replacement =
occurrenceToString(FileResult.Occurrences[I], IsLocal, NewSymbolName,
NewSymbolName, Filename);
if (ExpectedReplacementIndex >= ExpectedReplacements.size() ||
Replacement != ExpectedReplacements[ExpectedReplacementIndex])
return true;
++ExpectedReplacementIndex;
}
}
// Verify that all of the expected replacements were checked.
return ExpectedReplacementIndex != ExpectedReplacements.size();
}
struct ImplementationTUWrapper {
CXTranslationUnit TU = nullptr;
ImplementationTUWrapper() {}
~ImplementationTUWrapper() { clang_disposeTranslationUnit(TU); }
ImplementationTUWrapper(const ImplementationTUWrapper &) = delete;
ImplementationTUWrapper &operator=(const ImplementationTUWrapper &) = delete;
bool load(CXRefactoringAction Action, CXIndex CIdx,
ArrayRef<const char *> Args);
};
bool ImplementationTUWrapper::load(CXRefactoringAction Action, CXIndex CIdx,
ArrayRef<const char *> Args) {
if (!clang_RefactoringAction_requiresImplementationTU(Action))
return false;
CXString USR =
clang_RefactoringAction_getUSRThatRequiresImplementationTU(Action);
outs() << "Implementation TU USR: '" << clang_getCString(USR) << "'\n";
clang_disposeString(USR);
if (!TU) {
CXErrorCode Err = clang_parseTranslationUnit2(
CIdx, opts::ImplementationTU.c_str(), Args.data(), Args.size(), 0, 0,
CXTranslationUnit_KeepGoing, &TU);
if (Err != CXError_Success) {
errs() << "error: failed to load implementation TU '"
<< opts::ImplementationTU << "'\n";
return true;
}
}
CXErrorCode Err = clang_RefactoringAction_addImplementationTU(Action, TU);
if (Err != CXError_Success) {
errs() << "error: failed to add implementation TU '"
<< opts::ImplementationTU << "'\n";
return true;
}
return false;
}
static bool reportNewNameError(CXErrorCode Err) {
std::string NewName = opts::RenameIndexedFileSubcommand
? opts::rename::IndexedNewNames[0]
: opts::rename::NewName;
if (Err == CXError_RefactoringNameSizeMismatch)
errs() << "error: the number of strings in the new name '" << NewName
<< "' doesn't match the the number of strings in the old name\n";
else if (Err == CXError_RefactoringNameInvalid)
errs() << "error: invalid new name '" << NewName << "'\n";
else
return true;
return false;
}
int rename(CXTranslationUnit TU, CXIndex CIdx, ArrayRef<const char *> Args) {
assert(!opts::RenameIndexedFileSubcommand);
// Contains the renamed source replacements for the first location. It is
// compared to replacements from follow-up renames to ensure that all renames
// give the same result.
std::vector<std::string> ExpectedReplacements;
// Should we print out the filenames. False by default, but true when multiple
// files are modified.
bool PrintFilenames = false;
ImplementationTUWrapper ImplementationTU;
auto RenameAt = [&](const ParsedSourceLocation &Location,
const std::string &USR) -> int {
CXRefactoringAction RenamingAction;
CXErrorCode Err;
CXDiagnosticSet Diags = nullptr;
if (USR.empty()) {
CXSourceLocation Loc =
clang_getLocation(TU, clang_getFile(TU, Location.FileName.c_str()),
Location.Line, Location.Column);
Err = clang_Refactoring_initiateAction(
TU, Loc, clang_getNullRange(), CXRefactor_Rename,
/*Options=*/nullptr, &RenamingAction, &Diags);
} else {
Err = clang_Refactoring_initiateActionOnDecl(
TU, USR.c_str(), CXRefactor_Rename, /*Options=*/nullptr,
&RenamingAction, nullptr);
}
if (Err != CXError_Success) {
errs() << "error: could not rename symbol "
<< (USR.empty() ? "at the given location\n"
: "with the given USR\n");
if (USR.empty()) {
unsigned NumDiags = clang_getNumDiagnosticsInSet(Diags);
for (unsigned DiagID = 0; DiagID < NumDiags; ++DiagID) {
CXDiagnostic Diag = clang_getDiagnosticInSet(Diags, DiagID);
CXString Spelling = clang_getDiagnosticSpelling(Diag);
errs() << clang_getCString(Spelling) << "\n";
clang_disposeString(Spelling);
}
}
clang_disposeDiagnosticSet(Diags);
return 1;
}
clang_disposeDiagnosticSet(Diags);
if (ImplementationTU.load(RenamingAction, CIdx, Args))
return 1;
Err = clang_Refactoring_initiateRenamingOperation(RenamingAction);
if (Err != CXError_Success) {
errs() << "error: failed to initiate the renaming operation!\n";
return 1;
}
bool IsLocal = clang_RefactoringAction_getInitiatedActionType(
RenamingAction) == CXRefactor_Rename_Local;
unsigned NumSymbols = clang_RenamingOperation_getNumSymbols(RenamingAction);
if (opts::rename::DumpSymbols) {
outs() << "Renaming " << NumSymbols << " symbols\n";
for (unsigned I = 0; I < NumSymbols; ++I) {
CXString USR =
clang_RenamingOperation_getUSRForSymbol(RenamingAction, I);
outs() << "'" << clang_getCString(USR) << "'\n";
clang_disposeString(USR);
}
}
CXSymbolOccurrencesResult Occurrences;
Occurrences = clang_Refactoring_findSymbolOccurrencesInInitiationTU(
RenamingAction, Args.data(), Args.size(), 0, 0);
clang_RefactoringAction_dispose(RenamingAction);
// FIXME: This is a hack
LangOptions LangOpts;
LangOpts.ObjC = true;
tooling::OldSymbolName NewSymbolName(opts::rename::NewName, LangOpts);
if (ExpectedReplacements.empty()) {
if (opts::Apply) {
// FIXME: support --apply.
}
unsigned NumFiles = clang_SymbolOccurrences_getNumFiles(Occurrences);
if (NumFiles > 1)
PrintFilenames = true;
// Convert the occurrences to strings
for (unsigned FileIndex = 0; FileIndex < NumFiles; ++FileIndex) {
CXSymbolOccurrencesInFile FileResult;
clang_SymbolOccurrences_getOccurrencesForFile(Occurrences, FileIndex,
&FileResult);
StringRef Filename =
PrintFilenames ? clang_getCString(FileResult.Filename) : "";
for (unsigned I = 0; I != FileResult.NumOccurrences; ++I)
ExpectedReplacements.push_back(
occurrenceToString(FileResult.Occurrences[I], IsLocal,
NewSymbolName, NewSymbolName, Filename));
}
clang_SymbolOccurrences_dispose(Occurrences);
return 0;
}
// Compare the produced occurrences to the expected occurrences that were
// gathered at the first location.
bool AreOccurrencesDifferent =
compareOccurrences(ExpectedReplacements, Occurrences, IsLocal,
NewSymbolName, PrintFilenames);
clang_SymbolOccurrences_dispose(Occurrences);
if (!AreOccurrencesDifferent)
return 0;
errs() << "error: occurrences for a rename at " << Location.FileName << ":"
<< Location.Line << ":" << Location.Column
<< " differ to occurrences from the rename at the first location!\n";
return 1;
};
std::vector<ParsedSourceLocation> ParsedLocations;
for (const auto &I : enumerate(opts::rename::AtLocation)) {
auto Location = ParsedSourceLocation::FromString(I.value());
if (Location.FileName.empty()) {
errs()
<< "error: The -at option must use the <file:line:column> format\n";
return 1;
}
ParsedLocations.push_back(Location);
}
if (opts::RenameInitiateUSRSubcommand) {
if (RenameAt(ParsedSourceLocation(), opts::rename::USR))
return 1;
} else {
assert(!ParsedLocations.empty() && "No -at locations");
for (const auto &Location : ParsedLocations) {
if (RenameAt(Location, ""))
return 1;
}
}
// Print the produced renamed replacements
if (opts::Apply)
return 0;
for (const auto &Replacement : ExpectedReplacements)
outs() << Replacement << "\n";
if (ExpectedReplacements.empty())
outs() << "no replacements found\n";
return 0;
}
int renameIndexedFile(CXIndex CIdx, ArrayRef<const char *> Args) {
assert(opts::RenameIndexedFileSubcommand);
// Compute the number of symbols.
unsigned NumSymbols = opts::rename::IndexedNames.size();
// Get the occurrences of a symbol.
CXCursorKind DefaultCursorKind = renameIndexedOccurrenceKindStringToKind(
opts::rename::IndexedSymbolKind, CXCursor_NotImplemented);
std::vector<std::vector<CXIndexedSymbolLocation>> IndexedOccurrences(
NumSymbols, std::vector<CXIndexedSymbolLocation>());
for (const auto &IndexedOccurrence : opts::rename::IndexedLocations) {
auto Occurrence =
parseIndexedOccurrence(IndexedOccurrence, DefaultCursorKind);
unsigned SymbolIndex = Occurrence.second;
assert(SymbolIndex < IndexedOccurrences.size() && "Invalid symbol index");
IndexedOccurrences[SymbolIndex].push_back(CXIndexedSymbolLocation{
Occurrence.first.Location, Occurrence.first.CursorKind});
}
// Create the indexed symbols.
std::vector<CXIndexedSymbol> IndexedSymbols;
for (const auto &I : llvm::enumerate(IndexedOccurrences)) {
const auto &Occurrences = I.value();
const char *Name =
opts::rename::IndexedNames[opts::rename::IndexedNames.size() < 2
? 0
: I.index()]
.c_str();
IndexedSymbols.push_back({Occurrences.data(), (unsigned)Occurrences.size(),
DefaultCursorKind, Name});
}
CXRefactoringOptionSet Options = nullptr;
if (opts::rename::AvoidTextual) {
Options = clang_RefactoringOptionSet_create();
clang_RefactoringOptionSet_add(Options,
CXRefactorOption_AvoidTextualMatches);
}
CXSymbolOccurrencesResult Occurrences;
CXErrorCode Err = clang_Refactoring_findSymbolOccurrencesInIndexedFile(
IndexedSymbols.data(), IndexedSymbols.size(), CIdx,
opts::rename::IndexedFileName.c_str(), Args.data(), Args.size(), 0, 0,
Options, &Occurrences);
if (Err != CXError_Success) {
if (reportNewNameError(Err))
errs() << "error: failed to perform indexed file rename\n";
return 1;
}
if (Options)
clang_RefactoringOptionSet_dispose(Options);
// Should we print out the filenames. False by default, but true when multiple
// files are modified.
bool PrintFilenames = false;
unsigned NumFiles = clang_SymbolOccurrences_getNumFiles(Occurrences);
if (NumFiles > 1)
PrintFilenames = true;
LangOptions LangOpts;
LangOpts.ObjC = true;
tooling::OldSymbolName ExpectedReplacementStrings(
opts::rename::IndexedNewNames[0], LangOpts);
// Print the occurrences.
bool HasReplacements = false;
for (unsigned FileIndex = 0; FileIndex < NumFiles; ++FileIndex) {
CXSymbolOccurrencesInFile FileResult;
clang_SymbolOccurrences_getOccurrencesForFile(Occurrences, FileIndex,
&FileResult);
StringRef Filename =
PrintFilenames ? clang_getCString(FileResult.Filename) : "";
HasReplacements = FileResult.NumOccurrences;
for (unsigned I = 0; I != FileResult.NumOccurrences; ++I) {
unsigned SymbolIndex = FileResult.Occurrences[I].SymbolIndex;
const char *NewName =
opts::rename::IndexedNewNames[opts::rename::IndexedNewNames.size() < 2
? 0
: SymbolIndex]
.c_str();
LangOptions LangOpts;
LangOpts.ObjC = true;
tooling::OldSymbolName NewSymbolName(NewName, LangOpts);
outs() << occurrenceToString(FileResult.Occurrences[I], /*IsLocal*/ false,
NewSymbolName, ExpectedReplacementStrings,
Filename)
<< "\n";
}
}
if (!HasReplacements)
outs() << "no replacements found\n";
clang_SymbolOccurrences_dispose(Occurrences);
return 0;
}
/// Returns the last column number of a line in a file.
static unsigned lastColumnForFile(StringRef Filename, unsigned LineNo) {
auto Buf = llvm::MemoryBuffer::getFile(Filename);
if (!Buf)
return 0;
unsigned LineCount = 1;
for (llvm::line_iterator Lines(**Buf, /*SkipBlanks=*/false);
!Lines.is_at_end(); ++Lines, ++LineCount) {
if (LineNo == LineCount)
return Lines->size() + 1;
}
return 0;
}
struct ParsedSourceLineRange : ParsedSourceLocation {
unsigned MaxColumn;
ParsedSourceLineRange() {}
ParsedSourceLineRange(const ParsedSourceLocation &Loc)
: ParsedSourceLocation(Loc), MaxColumn(Loc.Column) {}
static Optional<ParsedSourceLineRange> FromString(StringRef Str) {
std::pair<StringRef, StringRef> RangeSplit = Str.rsplit('-');
auto PSL = ParsedSourceLocation::FromString(RangeSplit.first);
ParsedSourceLineRange Result;
Result.FileName = std::move(PSL.FileName);
Result.Line = PSL.Line;
Result.Column = PSL.Column;
if (Result.FileName.empty())
return None;
if (RangeSplit.second == "end")
Result.MaxColumn = lastColumnForFile(Result.FileName, Result.Line);
else if (RangeSplit.second.getAsInteger(10, Result.MaxColumn))
return None;
if (Result.MaxColumn < Result.Column)
return None;
return Result;
}
};
struct OldParsedSourceRange {
ParsedSourceLocation Begin, End;
OldParsedSourceRange(const ParsedSourceLocation &Begin,
const ParsedSourceLocation &End)
: Begin(Begin), End(End) {}
static Optional<OldParsedSourceRange> FromString(StringRef Str) {
std::pair<StringRef, StringRef> RangeSplit = Str.rsplit('-');
auto Begin = ParsedSourceLocation::FromString(RangeSplit.first);
if (Begin.FileName.empty())
return None;
std::string EndString = Begin.FileName + ":" + RangeSplit.second.str();
auto End = ParsedSourceLocation::FromString(EndString);
if (End.FileName.empty())
return None;
return OldParsedSourceRange(Begin, End);
}
};
int listRefactoringActions(CXTranslationUnit TU) {
auto Location =
ParsedSourceLocation::FromString(opts::listActions::AtLocation);
if (Location.FileName.empty()) {
errs() << "error: The -at option must use the <file:line:column> format\n";
return 1;
}
CXSourceRange Range;
if (!opts::listActions::SelectedRange.empty()) {
auto SelectionRange =
OldParsedSourceRange::FromString(opts::listActions::SelectedRange);
if (!SelectionRange) {
errs() << "error: The -selected option must use the "
"<file:line:column-line:column> format\n";
return 1;
}
auto Begin = SelectionRange.getValue().Begin;
auto End = SelectionRange.getValue().End;
CXFile File = clang_getFile(TU, Begin.FileName.c_str());
Range =
clang_getRange(clang_getLocation(TU, File, Begin.Line, Begin.Column),
clang_getLocation(TU, File, End.Line, End.Column));
} else
Range = clang_getNullRange();
CXSourceLocation Loc =
clang_getLocation(TU, clang_getFile(TU, Location.FileName.c_str()),
Location.Line, Location.Column);
CXRefactoringActionSet ActionSet;
CXRefactoringActionSetWithDiagnostics FailedActionSet;
CXErrorCode Err =
clang_Refactoring_findActionsWithInitiationFailureDiagnosicsAt(
TU, Loc, Range, /*Options=*/nullptr, &ActionSet, &FailedActionSet);
if (FailedActionSet.NumActions) {
errs() << "Failed to initiate " << FailedActionSet.NumActions
<< " actions because:\n";
for (unsigned I = 0; I < FailedActionSet.NumActions; ++I) {
errs() << clang_getCString(clang_RefactoringActionType_getName(
FailedActionSet.Actions[I].Action))
<< ":";
CXDiagnosticSet Diags = FailedActionSet.Actions[I].Diagnostics;
unsigned NumDiags = clang_getNumDiagnosticsInSet(Diags);
for (unsigned DiagID = 0; DiagID < NumDiags; ++DiagID) {
CXDiagnostic Diag = clang_getDiagnosticInSet(Diags, DiagID);
CXString Spelling = clang_getDiagnosticSpelling(Diag);
errs() << ' ' << clang_getCString(Spelling);
clang_disposeString(Spelling);
}
errs() << "\n";
}
}
if (Err == CXError_RefactoringActionUnavailable)
errs() << "No refactoring actions are available at the given location\n";
if (Err != CXError_Success)
return 1;
// Print the list of refactoring actions.
outs() << "Found " << ActionSet.NumActions << " actions:\n";
for (unsigned I = 0; I < ActionSet.NumActions; ++I) {
outs() << clang_getCString(
clang_RefactoringActionType_getName(ActionSet.Actions[I]));
if (opts::listActions::DumpRawActionType)
outs() << "(" << ActionSet.Actions[I] << ")";
outs() << "\n";
}
clang_RefactoringActionSet_dispose(&ActionSet);
clang_RefactoringActionSetWithDiagnostics_dispose(&FailedActionSet);
return 0;
}
static std::string locationToString(CXSourceLocation Loc) {
unsigned Line, Column;
clang_getFileLocation(Loc, nullptr, &Line, &Column, nullptr);
std::string S;
llvm::raw_string_ostream OS(S);
OS << Line << ':' << Column;
return OS.str();
}
static std::string rangeToString(CXSourceRange Range) {
return locationToString(clang_getRangeStart(Range)) + " -> " +
locationToString(clang_getRangeEnd(Range));
}
static std::string
refactoringCandidatesToString(CXRefactoringCandidateSet Candidates) {
std::string Results = "with multiple candidates:";
for (unsigned I = 0; I < Candidates.NumCandidates; ++I) {
Results += "\n";
Results += clang_getCString(Candidates.Candidates[I].Description);
}
return Results;
}
static void printEscaped(StringRef Str, raw_ostream &OS) {
size_t Pos = Str.find('\n');
OS << Str.substr(0, Pos);
if (Pos == StringRef::npos)
return;
OS << "\\n";
printEscaped(Str.substr(Pos + 1), OS);
}
bool printRefactoringReplacements(
CXRefactoringResult Result, CXRefactoringContinuation Continuation,
CXRefactoringContinuation CurrentContinuation) {
CXRefactoringReplacements Replacements =
clang_RefactoringResult_getSourceReplacements(Result);
if (Replacements.NumFileReplacementSets == 0) {
if (CurrentContinuation)
return false;
errs() << "error: no replacements produced!\n";
return true;
}
// Print out the produced results.
for (unsigned FileIndex = 0; FileIndex < Replacements.NumFileReplacementSets;
++FileIndex) {
const CXRefactoringFileReplacementSet &FileSet =
Replacements.FileReplacementSets[FileIndex];
if (opts::Apply) {
apply(llvm::makeArrayRef(FileSet.Replacements, FileSet.NumReplacements),
clang_getCString(FileSet.Filename));
continue;
}
for (unsigned I = 0; I < FileSet.NumReplacements; ++I) {
const CXRefactoringReplacement &Replacement = FileSet.Replacements[I];
if (Continuation) {
// Always print the filenames in with continuations.
outs() << '"' << clang_getCString(FileSet.Filename) << "\" ";
}
outs() << '"';
printEscaped(clang_getCString(Replacement.ReplacementString), outs());
outs() << "\" ";
CXFileRange Range = Replacement.Range;
outs() << Range.Begin.Line << ":" << Range.Begin.Column << " -> "
<< Range.End.Line << ":" << Range.End.Column;
if (opts::initiateAndPerform::EmitAssociatedInfo) {
CXRefactoringReplacementAssociatedSymbolOccurrences Info =
clang_RefactoringReplacement_getAssociatedSymbolOccurrences(
Replacement);
for (const CXSymbolOccurrence &SymbolOccurrence :
llvm::makeArrayRef(Info.AssociatedSymbolOccurrences,
Info.NumAssociatedSymbolOccurrences)) {
outs() << " [Symbol " << renameOccurrenceKindString(
SymbolOccurrence.Kind, /*IsLocal*/ false,
SymbolOccurrence.IsMacroExpansion)
<< ' ' << SymbolOccurrence.SymbolIndex;
for (const auto &Piece :
llvm::makeArrayRef(SymbolOccurrence.NamePieces,
SymbolOccurrence.NumNamePieces)) {
outs() << ' ' << Piece.Begin.Line << ":" << Piece.Begin.Column
<< " -> " << Piece.End.Line << ":" << Piece.End.Column;
}
outs() << ']';
}
}
outs() << "\n";
}
}
return false;
}
/// Returns the last column number of a line in a file.
static std::string queryResultsForFile(StringRef Filename, StringRef Name,
StringRef FileSubstitution) {
auto Buf = llvm::MemoryBuffer::getFile(Filename);
if (!Buf)
return "<invalid>";
StringRef Buffer = (*Buf)->getBuffer();
std::string Label = Name.str() + ":";
size_t I = Buffer.find(Label);
if (I == StringRef::npos)
return "<invalid>";
I = I + Label.size();