[clang] [clang-format] Fix an off-by-1 bug with -length option (PR #143302)

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Thu Jun 26 19:08:28 PDT 2025


================
@@ -296,12 +296,16 @@ static bool fillRanges(MemoryBuffer *Code,
     }
     if (!EmptyLengths)
       Length = Lengths[I];
+    if (Length == 0) {
+      errs() << "error: length should be at least 1\n";
+      return true;
+    }
     if (Offset + Length > CodeSize) {
       errs() << "error: invalid length " << Length << ", offset + length ("
-             << Offset + Length << ") is outside the file.\n";
+             << Offset + Length << ") is outside the file\n";
       return true;
     }
-    Ranges.push_back(tooling::Range(Offset, Length));
+    Ranges.push_back(tooling::Range(Offset, Length - 1));
----------------
owenca wrote:

I really don't understand the rant. I didn't touch the off-by-1 bug (if it's indeed a bug) in `AffectedRangeManager.cpp` precisely because it would impact libFormat, which has been like this since its [inception](f79351157959adde9a65d99075590a9db613a77b) 12+ years ago, and all range tests in FormatTests have been based on this semantics. If you (or anyone else) want to address it now, please open an issue and submit a pull request.

> hi folks, we're seeing some regressions that's possibly related to this change (working on a repro right now).

I'll look into this as soon as you have a repro.

https://github.com/llvm/llvm-project/pull/143302


More information about the cfe-commits mailing list