clang-tools 22.0.0git
IncludeSorter.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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#include "IncludeSorter.h"
10#include "clang/Basic/SourceManager.h"
11#include "clang/Lex/Lexer.h"
12#include <algorithm>
13#include <optional>
14
15namespace clang::tidy {
16namespace utils {
17
18static StringRef removeFirstSuffix(StringRef Str,
19 ArrayRef<const char *> Suffixes) {
20 for (const StringRef Suffix : Suffixes)
21 if (Str.consume_back(Suffix))
22 return Str;
23 return Str;
24}
25
26static StringRef makeCanonicalName(StringRef Str,
27 IncludeSorter::IncludeStyle Style) {
28 // The list of suffixes to remove from source file names to get the
29 // "canonical" file names.
30 // E.g. tools/sort_includes.cc and tools/sort_includes_test.cc
31 // would both canonicalize to tools/sort_includes and tools/sort_includes.h
32 // (once canonicalized) will match as being the main include file associated
33 // with the source files.
34 if (Style == IncludeSorter::IS_LLVM) {
35 return removeFirstSuffix(
36 removeFirstSuffix(Str, {".cc", ".cpp", ".c", ".h", ".hpp"}), {"Test"});
37 }
38 if (Style == IncludeSorter::IS_Google_ObjC) {
39 const StringRef Canonical =
40 removeFirstSuffix(removeFirstSuffix(Str, {".cc", ".cpp", ".c", ".h",
41 ".hpp", ".mm", ".m"}),
42 {"_unittest", "_regtest", "_test", "Test"});
43
44 // Objective-C categories have a `+suffix` format, but should be grouped
45 // with the file they are a category of.
46 size_t StartIndex = Canonical.find_last_of('/');
47 if (StartIndex == StringRef::npos)
48 StartIndex = 0;
49 return Canonical.substr(0, Canonical.find_first_of('+', StartIndex));
50 }
51 return removeFirstSuffix(
52 removeFirstSuffix(Str, {".cc", ".cpp", ".c", ".h", ".hpp"}),
53 {"_unittest", "_regtest", "_test"});
54}
55
56// Scan to the end of the line and return the offset of the next line.
57static size_t findNextLine(const char *Text) {
58 const size_t EOLIndex = std::strcspn(Text, "\n");
59 return Text[EOLIndex] == '\0' ? EOLIndex : EOLIndex + 1;
60}
61
62static IncludeSorter::IncludeKinds
63determineIncludeKind(StringRef CanonicalFile, StringRef IncludeFile,
64 bool IsAngled, IncludeSorter::IncludeStyle Style) {
65 // Compute the two "canonical" forms of the include's filename sans extension.
66 // The first form is the include's filename without ".h" or "-inl.h" at the
67 // end. The second form is the first form with "/public/" in the file path
68 // replaced by "/internal/".
69 if (IsAngled) {
70 // If the system include (<foo>) ends with ".h", then it is a normal C-style
71 // include. Otherwise assume it is a C++-style extensionless include.
72 return IncludeFile.ends_with(".h") ? IncludeSorter::IK_CSystemInclude
73 : IncludeSorter::IK_CXXSystemInclude;
74 }
75 const StringRef CanonicalInclude = makeCanonicalName(IncludeFile, Style);
76 if (CanonicalFile.ends_with(CanonicalInclude) ||
77 CanonicalInclude.ends_with(CanonicalFile)) {
78 return IncludeSorter::IK_MainTUInclude;
79 }
80 if ((Style == IncludeSorter::IS_Google) ||
81 (Style == IncludeSorter::IS_Google_ObjC)) {
82 const std::pair<StringRef, StringRef> Parts =
83 CanonicalInclude.split("/public/");
84 StringRef FileCopy = CanonicalFile;
85 if (FileCopy.consume_front(Parts.first) &&
86 FileCopy.consume_back(Parts.second)) {
87 // Determine the kind of this inclusion.
88 if (FileCopy == "/internal/" || FileCopy == "/proto/")
89 return IncludeSorter::IK_MainTUInclude;
90 }
91 }
92 if (Style == IncludeSorter::IS_Google_ObjC) {
93 if (IncludeFile.ends_with(".generated.h") ||
94 IncludeFile.ends_with(".proto.h") ||
95 IncludeFile.ends_with(".pbobjc.h")) {
96 return IncludeSorter::IK_GeneratedInclude;
97 }
98 }
99 return IncludeSorter::IK_NonSystemInclude;
100}
101
102static int compareHeaders(StringRef LHS, StringRef RHS,
103 IncludeSorter::IncludeStyle Style) {
104 if (Style == IncludeSorter::IncludeStyle::IS_Google_ObjC) {
105 const std::pair<const char *, const char *> &Mismatch =
106 std::mismatch(LHS.begin(), LHS.end(), RHS.begin(), RHS.end());
107 if ((Mismatch.first != LHS.end()) && (Mismatch.second != RHS.end())) {
108 if ((*Mismatch.first == '.') && (*Mismatch.second == '+'))
109 return -1;
110 if ((*Mismatch.first == '+') && (*Mismatch.second == '.'))
111 return 1;
112 }
113 }
114 return LHS.compare(RHS);
115}
116
117IncludeSorter::IncludeSorter(const SourceManager *SourceMgr, FileID FileID,
118 StringRef FileName, IncludeStyle Style)
119 : SourceMgr(SourceMgr), Style(Style), CurrentFileID(FileID),
120 CanonicalFile(makeCanonicalName(FileName, Style)) {}
121
122void IncludeSorter::addInclude(StringRef FileName, bool IsAngled,
123 SourceLocation HashLocation,
124 SourceLocation EndLocation) {
125 const int Offset = findNextLine(SourceMgr->getCharacterData(EndLocation));
126
127 // Record the relevant location information for this inclusion directive.
128 auto &IncludeLocation = IncludeLocations[FileName];
129 IncludeLocation.push_back(
130 SourceRange(HashLocation, EndLocation.getLocWithOffset(Offset)));
131 SourceLocations.push_back(IncludeLocation.back());
132
133 // Stop if this inclusion is a duplicate.
134 if (IncludeLocation.size() > 1)
135 return;
136
137 // Add the included file's name to the appropriate bucket.
138 const IncludeKinds Kind =
139 determineIncludeKind(CanonicalFile, FileName, IsAngled, Style);
140 if (Kind != IK_InvalidInclude)
141 IncludeBucket[Kind].push_back(FileName.str());
142}
143
144std::optional<FixItHint>
145IncludeSorter::createIncludeInsertion(StringRef FileName, bool IsAngled) {
146 std::string IncludeStmt;
147 if (Style == IncludeStyle::IS_Google_ObjC) {
148 IncludeStmt = IsAngled
149 ? llvm::Twine("#import <" + FileName + ">\n").str()
150 : llvm::Twine("#import \"" + FileName + "\"\n").str();
151 } else {
152 IncludeStmt = IsAngled
153 ? llvm::Twine("#include <" + FileName + ">\n").str()
154 : llvm::Twine("#include \"" + FileName + "\"\n").str();
155 }
156 if (SourceLocations.empty()) {
157 // If there are no includes in this file, add it in the first line.
158 // FIXME: insert after the file comment or the header guard, if present.
159 IncludeStmt.append("\n");
160 return FixItHint::CreateInsertion(
161 SourceMgr->getLocForStartOfFile(CurrentFileID), IncludeStmt);
162 }
163
164 auto IncludeKind =
165 determineIncludeKind(CanonicalFile, FileName, IsAngled, Style);
166
167 if (!IncludeBucket[IncludeKind].empty()) {
168 for (const std::string &IncludeEntry : IncludeBucket[IncludeKind]) {
169 if (compareHeaders(FileName, IncludeEntry, Style) < 0) {
170 const auto &Location = IncludeLocations[IncludeEntry][0];
171 return FixItHint::CreateInsertion(Location.getBegin(), IncludeStmt);
172 }
173 if (FileName == IncludeEntry)
174 return std::nullopt;
175 }
176 // FileName comes after all include entries in bucket, insert it after
177 // last.
178 const std::string &LastInclude = IncludeBucket[IncludeKind].back();
179 const SourceRange LastIncludeLocation =
180 IncludeLocations[LastInclude].back();
181 return FixItHint::CreateInsertion(LastIncludeLocation.getEnd(),
182 IncludeStmt);
183 }
184 // Find the non-empty include bucket to be sorted directly above
185 // 'IncludeKind'. If such a bucket exists, we'll want to sort the include
186 // after that bucket. If no such bucket exists, find the first non-empty
187 // include bucket in the file. In that case, we'll want to sort the include
188 // before that bucket.
189 IncludeKinds NonEmptyKind = IK_InvalidInclude;
190 for (int I = IK_InvalidInclude - 1; I >= 0; --I) {
191 if (!IncludeBucket[I].empty()) {
192 NonEmptyKind = static_cast<IncludeKinds>(I);
193 if (NonEmptyKind < IncludeKind)
194 break;
195 }
196 }
197 if (NonEmptyKind == IK_InvalidInclude)
198 return std::nullopt;
199
200 if (NonEmptyKind < IncludeKind) {
201 // Create a block after.
202 const std::string &LastInclude = IncludeBucket[NonEmptyKind].back();
203 const SourceRange LastIncludeLocation =
204 IncludeLocations[LastInclude].back();
205 IncludeStmt = '\n' + IncludeStmt;
206 return FixItHint::CreateInsertion(LastIncludeLocation.getEnd(),
207 IncludeStmt);
208 }
209 // Create a block before.
210 const std::string &FirstInclude = IncludeBucket[NonEmptyKind][0];
211 const SourceRange FirstIncludeLocation =
212 IncludeLocations[FirstInclude].back();
213 IncludeStmt.append("\n");
214 return FixItHint::CreateInsertion(FirstIncludeLocation.getBegin(),
215 IncludeStmt);
216}
217
218} // namespace utils
219
220llvm::ArrayRef<std::pair<utils::IncludeSorter::IncludeStyle, StringRef>>
222 static constexpr std::pair<utils::IncludeSorter::IncludeStyle, StringRef>
223 Mapping[] = {{utils::IncludeSorter::IS_LLVM, "llvm"},
224 {utils::IncludeSorter::IS_Google, "google"},
225 {utils::IncludeSorter::IS_Google_ObjC, "google-objc"}};
226 return {Mapping};
227}
228} // namespace clang::tidy
static IncludeSorter::IncludeKinds determineIncludeKind(StringRef CanonicalFile, StringRef IncludeFile, bool IsAngled, IncludeSorter::IncludeStyle Style)
static StringRef makeCanonicalName(StringRef Str, IncludeSorter::IncludeStyle Style)
static StringRef removeFirstSuffix(StringRef Str, ArrayRef< const char * > Suffixes)
static size_t findNextLine(const char *Text)
static int compareHeaders(StringRef LHS, StringRef RHS, IncludeSorter::IncludeStyle Style)
static ArrayRef< std::pair< utils::IncludeSorter::IncludeStyle, StringRef > > getEnumMapping()