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