[PATCH] D78578: [flang] Fix handling of files without terminating newlines.

David Truby via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Fri Apr 24 08:04:33 PDT 2020


DavidTruby updated this revision to Diff 259888.
DavidTruby added a comment.

Added test case including carriage returns; this tests the case where we already
have enough memory to add a newline at the end since we've moved the carriage
returns there.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D78578/new/

https://reviews.llvm.org/D78578

Files:
  flang/lib/Parser/source.cpp
  flang/test/Semantics/missing_newline.f90


Index: flang/test/Semantics/missing_newline.f90
===================================================================
--- /dev/null
+++ 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
Index: flang/lib/Parser/source.cpp
===================================================================
--- flang/lib/Parser/source.cpp
+++ 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();
 }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D78578.259888.patch
Type: text/x-patch
Size: 1280 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20200424/a3791b58/attachment.bin>


More information about the llvm-commits mailing list