diff --git a/flang/lib/Parser/source.cpp b/flang/lib/Parser/source.cpp --- a/flang/lib/Parser/source.cpp +++ b/flang/lib/Parser/source.cpp @@ -127,12 +127,19 @@ } 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 --- /dev/null +++ b/flang/test/Semantics/missing_newline.f90 @@ -0,0 +1,2 @@ +! RUN: echo -n "end program" > %t.f90 +! RUN: %f18 -fparse-only %t.f90