[clang] clang-format: Sort includes by stem rather than full filename (PR #137840)
via cfe-commits
cfe-commits at lists.llvm.org
Tue Apr 29 09:30:30 PDT 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-format
Author: Daan De Meyer (DaanDeMeyer)
<details>
<summary>Changes</summary>
Sorting by stem gives nicer results when various header file names are substrings of other header file names, for example, a CLI application with a main header named analyze.h and a analyze-xxx.h header for each subcommand currently will always put analyze.h last after all the analyze-xxx.h headers, but putting analyze.h first instead of last is arguable nicer to read.
TLDR; Instead of
```
#include "analyze-blame.h"
#include "analyze.h"
```
We'll now get
```
#include "analyze.h"
#include "analyze-blame.h"
```
---
Full diff: https://github.com/llvm/llvm-project/pull/137840.diff
1 Files Affected:
- (modified) clang/lib/Format/Format.cpp (+10-8)
``````````diff
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 5a1c3f556b331..bc1e681c9be78 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3219,17 +3219,19 @@ static void sortCppIncludes(const FormatStyle &Style,
if (Style.SortIncludes == FormatStyle::SI_CaseInsensitive) {
stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
- const auto LHSFilenameLower = Includes[LHSI].Filename.lower();
- const auto RHSFilenameLower = Includes[RHSI].Filename.lower();
- return std::tie(Includes[LHSI].Priority, LHSFilenameLower,
- Includes[LHSI].Filename) <
- std::tie(Includes[RHSI].Priority, RHSFilenameLower,
- Includes[RHSI].Filename);
+ const auto LHSStem = llvm::sys::path::stem(Includes[LHSI].Filename);
+ const auto RHSStem = llvm::sys::path::stem(Includes[RHSI].Filename);
+ const auto LHSStemLower = LHSStem.lower();
+ const auto RHSStemLower = RHSStem.lower();
+ return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem) <
+ std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem);
});
} else {
stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
- return std::tie(Includes[LHSI].Priority, Includes[LHSI].Filename) <
- std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename);
+ const auto LHSStem = llvm::sys::path::stem(Includes[LHSI].Filename);
+ const auto RHSStem = llvm::sys::path::stem(Includes[RHSI].Filename);
+ return std::tie(Includes[LHSI].Priority, LHSStem) <
+ std::tie(Includes[RHSI].Priority, RHSStem);
});
}
``````````
</details>
https://github.com/llvm/llvm-project/pull/137840
More information about the cfe-commits
mailing list