From b547e1a4d163721b2dc3be869a3f06c6203217dc Mon Sep 17 00:00:00 2001 From: David Truby Date: Tue, 21 Apr 2020 19:45:43 +0100 Subject: [PATCH] [flang] Fix handling of files without terminating newlines. Reviewers: sscalpone Subscribers: llvm-commits Tags: #llvm Differential Revision: https://reviews.llvm.org/D78578 --- flang/lib/Parser/source.cpp | 17 ++++++++++++----- flang/test/Semantics/missing_newline.f90 | 4 ++++ 2 files changed, 16 insertions(+), 5 deletions(-) create mode 100644 flang/test/Semantics/missing_newline.f90 diff --git a/flang/lib/Parser/source.cpp b/flang/lib/Parser/source.cpp index 376786e3923e..4f6c21fc2b48 100644 --- a/flang/lib/Parser/source.cpp +++ b/flang/lib/Parser/source.cpp @@ -127,12 +127,19 @@ bool SourceFile::ReadStandardInput(llvm::raw_ostream &error) { } void SourceFile::ReadFile() { - if (buf_->getBuffer().size() == 0) { - Close(); - buf_ = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(1); - buf_->getBuffer()[0] = '\n'; - } buf_end_ = RemoveCarriageReturns(buf_->getBuffer()); + if (content().size() == 0 || content().back() != '\n') { + // Don't bother to copy if we have spare memory + if (content().size() >= buf_->getBufferSize()) { + auto tmp_buf{llvm::WritableMemoryBuffer::getNewUninitMemBuffer( + content().size() + 1)}; + llvm::copy(content(), tmp_buf->getBufferStart()); + Close(); + buf_ = std::move(tmp_buf); + } + buf_end_++; + buf_->getBuffer()[buf_end_ - 1] = '\n'; + } IdentifyPayload(); RecordLineStarts(); } diff --git a/flang/test/Semantics/missing_newline.f90 b/flang/test/Semantics/missing_newline.f90 new file mode 100644 index 000000000000..6dfafba7db86 --- /dev/null +++ b/flang/test/Semantics/missing_newline.f90 @@ -0,0 +1,4 @@ +! RUN: echo -n "end program" > %t.f90 +! RUN: %f18 -fparse-only %t.f90 +! RUN: echo -ne "\rend program" > %t.f90 +! RUN: %f18 -fparse-only %t.f90