diff --git a/mlir/include/mlir/Support/IndentedOstream.h b/mlir/include/mlir/Support/IndentedOstream.h --- a/mlir/include/mlir/Support/IndentedOstream.h +++ b/mlir/include/mlir/Support/IndentedOstream.h @@ -113,7 +113,13 @@ inline raw_indented_ostream & mlir::raw_indented_ostream::printReindented(StringRef str, StringRef extraPrefix) { - StringRef output = str; + // Before splitting on \n, remove Windows \r characters from \r\n endings. + std::string normalizedStr = str.str(); + normalizedStr.erase( + std::remove(normalizedStr.begin(), normalizedStr.end(), '\r'), + normalizedStr.cend()); + StringRef output(normalizedStr); + // Skip empty lines. while (!output.empty()) { auto split = output.split('\n'); diff --git a/mlir/unittests/Support/IndentedOstreamTest.cpp b/mlir/unittests/Support/IndentedOstreamTest.cpp --- a/mlir/unittests/Support/IndentedOstreamTest.cpp +++ b/mlir/unittests/Support/IndentedOstreamTest.cpp @@ -108,3 +108,19 @@ )"; EXPECT_THAT(os.str(), StrEq(expected)); } + +TEST(FormatTest, ReindentLineEndings) { + std::string str; + llvm::raw_string_ostream os(str); + raw_indented_ostream ros(os); + + // Similar string as the previous test, but with \r\n (Windows style) line + // breaks. Note that C++'s internal string representation uses \n, so just + // running the previous test as-is on Windows is not sufficient. + const auto *desc = + "\r\n\r\n\r\n First line\r\n second line"; + ros.printReindented(desc); + ros.flush(); + const auto *expected = "First line\n second line"; + EXPECT_THAT(os.str(), StrEq(expected)); +}