UsingDeclarationsSorter.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. //===--- UsingDeclarationsSorter.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. ///
  9. /// \file
  10. /// This file implements UsingDeclarationsSorter, a TokenAnalyzer that
  11. /// sorts consecutive using declarations.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "UsingDeclarationsSorter.h"
  15. #include "llvm/Support/Debug.h"
  16. #include "llvm/Support/Regex.h"
  17. #include <algorithm>
  18. #define DEBUG_TYPE "using-declarations-sorter"
  19. namespace clang {
  20. namespace format {
  21. namespace {
  22. // The order of using declaration is defined as follows:
  23. // Split the strings by "::" and discard any initial empty strings. The last
  24. // element of each list is a non-namespace name; all others are namespace
  25. // names. Sort the lists of names lexicographically, where the sort order of
  26. // individual names is that all non-namespace names come before all namespace
  27. // names, and within those groups, names are in case-insensitive lexicographic
  28. // order.
  29. int compareLabels(StringRef A, StringRef B) {
  30. SmallVector<StringRef, 2> NamesA;
  31. A.split(NamesA, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  32. SmallVector<StringRef, 2> NamesB;
  33. B.split(NamesB, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  34. size_t SizeA = NamesA.size();
  35. size_t SizeB = NamesB.size();
  36. for (size_t I = 0, E = std::min(SizeA, SizeB); I < E; ++I) {
  37. if (I + 1 == SizeA) {
  38. // I is the last index of NamesA and NamesA[I] is a non-namespace name.
  39. // Non-namespace names come before all namespace names.
  40. if (SizeB > SizeA)
  41. return -1;
  42. // Two names within a group compare case-insensitively.
  43. return NamesA[I].compare_insensitive(NamesB[I]);
  44. }
  45. // I is the last index of NamesB and NamesB[I] is a non-namespace name.
  46. // Non-namespace names come before all namespace names.
  47. if (I + 1 == SizeB)
  48. return 1;
  49. // Two namespaces names within a group compare case-insensitively.
  50. int C = NamesA[I].compare_insensitive(NamesB[I]);
  51. if (C != 0)
  52. return C;
  53. }
  54. return 0;
  55. }
  56. struct UsingDeclaration {
  57. const AnnotatedLine *Line;
  58. std::string Label;
  59. UsingDeclaration(const AnnotatedLine *Line, const std::string &Label)
  60. : Line(Line), Label(Label) {}
  61. bool operator<(const UsingDeclaration &Other) const {
  62. return compareLabels(Label, Other.Label) < 0;
  63. }
  64. };
  65. /// Computes the label of a using declaration starting at tthe using token
  66. /// \p UsingTok.
  67. /// If \p UsingTok doesn't begin a using declaration, returns the empty string.
  68. /// Note that this detects specifically using declarations, as in:
  69. /// using A::B::C;
  70. /// and not type aliases, as in:
  71. /// using A = B::C;
  72. /// Type aliases are in general not safe to permute.
  73. std::string computeUsingDeclarationLabel(const FormatToken *UsingTok) {
  74. assert(UsingTok && UsingTok->is(tok::kw_using) && "Expecting a using token");
  75. std::string Label;
  76. const FormatToken *Tok = UsingTok->Next;
  77. if (Tok && Tok->is(tok::kw_typename)) {
  78. Label.append("typename ");
  79. Tok = Tok->Next;
  80. }
  81. if (Tok && Tok->is(tok::coloncolon)) {
  82. Label.append("::");
  83. Tok = Tok->Next;
  84. }
  85. bool HasIdentifier = false;
  86. while (Tok && Tok->is(tok::identifier)) {
  87. HasIdentifier = true;
  88. Label.append(Tok->TokenText.str());
  89. Tok = Tok->Next;
  90. if (!Tok || Tok->isNot(tok::coloncolon))
  91. break;
  92. Label.append("::");
  93. Tok = Tok->Next;
  94. }
  95. if (HasIdentifier && Tok && Tok->isOneOf(tok::semi, tok::comma))
  96. return Label;
  97. return "";
  98. }
  99. void endUsingDeclarationBlock(
  100. SmallVectorImpl<UsingDeclaration> *UsingDeclarations,
  101. const SourceManager &SourceMgr, tooling::Replacements *Fixes) {
  102. bool BlockAffected = false;
  103. for (const UsingDeclaration &Declaration : *UsingDeclarations) {
  104. if (Declaration.Line->Affected) {
  105. BlockAffected = true;
  106. break;
  107. }
  108. }
  109. if (!BlockAffected) {
  110. UsingDeclarations->clear();
  111. return;
  112. }
  113. SmallVector<UsingDeclaration, 4> SortedUsingDeclarations(
  114. UsingDeclarations->begin(), UsingDeclarations->end());
  115. llvm::stable_sort(SortedUsingDeclarations);
  116. SortedUsingDeclarations.erase(
  117. std::unique(SortedUsingDeclarations.begin(),
  118. SortedUsingDeclarations.end(),
  119. [](const UsingDeclaration &a, const UsingDeclaration &b) {
  120. return a.Label == b.Label;
  121. }),
  122. SortedUsingDeclarations.end());
  123. for (size_t I = 0, E = UsingDeclarations->size(); I < E; ++I) {
  124. if (I >= SortedUsingDeclarations.size()) {
  125. // This using declaration has been deduplicated, delete it.
  126. auto Begin =
  127. (*UsingDeclarations)[I].Line->First->WhitespaceRange.getBegin();
  128. auto End = (*UsingDeclarations)[I].Line->Last->Tok.getEndLoc();
  129. auto Range = CharSourceRange::getCharRange(Begin, End);
  130. auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, ""));
  131. if (Err) {
  132. llvm::errs() << "Error while sorting using declarations: "
  133. << llvm::toString(std::move(Err)) << "\n";
  134. }
  135. continue;
  136. }
  137. if ((*UsingDeclarations)[I].Line == SortedUsingDeclarations[I].Line)
  138. continue;
  139. auto Begin = (*UsingDeclarations)[I].Line->First->Tok.getLocation();
  140. auto End = (*UsingDeclarations)[I].Line->Last->Tok.getEndLoc();
  141. auto SortedBegin =
  142. SortedUsingDeclarations[I].Line->First->Tok.getLocation();
  143. auto SortedEnd = SortedUsingDeclarations[I].Line->Last->Tok.getEndLoc();
  144. StringRef Text(SourceMgr.getCharacterData(SortedBegin),
  145. SourceMgr.getCharacterData(SortedEnd) -
  146. SourceMgr.getCharacterData(SortedBegin));
  147. LLVM_DEBUG({
  148. StringRef OldText(SourceMgr.getCharacterData(Begin),
  149. SourceMgr.getCharacterData(End) -
  150. SourceMgr.getCharacterData(Begin));
  151. llvm::dbgs() << "Replacing '" << OldText << "' with '" << Text << "'\n";
  152. });
  153. auto Range = CharSourceRange::getCharRange(Begin, End);
  154. auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, Text));
  155. if (Err) {
  156. llvm::errs() << "Error while sorting using declarations: "
  157. << llvm::toString(std::move(Err)) << "\n";
  158. }
  159. }
  160. UsingDeclarations->clear();
  161. }
  162. } // namespace
  163. UsingDeclarationsSorter::UsingDeclarationsSorter(const Environment &Env,
  164. const FormatStyle &Style)
  165. : TokenAnalyzer(Env, Style) {}
  166. std::pair<tooling::Replacements, unsigned> UsingDeclarationsSorter::analyze(
  167. TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  168. FormatTokenLexer &Tokens) {
  169. const SourceManager &SourceMgr = Env.getSourceManager();
  170. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  171. tooling::Replacements Fixes;
  172. SmallVector<UsingDeclaration, 4> UsingDeclarations;
  173. for (const AnnotatedLine *Line : AnnotatedLines) {
  174. const auto *FirstTok = Line->First;
  175. if (Line->InPPDirective || !Line->startsWith(tok::kw_using) ||
  176. FirstTok->Finalized) {
  177. endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes);
  178. continue;
  179. }
  180. if (FirstTok->NewlinesBefore > 1)
  181. endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes);
  182. const auto *UsingTok =
  183. FirstTok->is(tok::comment) ? FirstTok->getNextNonComment() : FirstTok;
  184. std::string Label = computeUsingDeclarationLabel(UsingTok);
  185. if (Label.empty()) {
  186. endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes);
  187. continue;
  188. }
  189. UsingDeclarations.push_back(UsingDeclaration(Line, Label));
  190. }
  191. endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes);
  192. return {Fixes, 0};
  193. }
  194. } // namespace format
  195. } // namespace clang