[Preprocessor] Elide empty line(s) at start of file.
authorMichael Kruse <llvm-project@meinersbur.de>
Wed, 25 Aug 2021 16:31:53 +0000 (11:31 -0500)
committerMichael Kruse <llvm-project@meinersbur.de>
Wed, 25 Aug 2021 17:48:59 +0000 (12:48 -0500)
In -P mode, PrintPPOutputPPCallbacks::MoveToLine started at least one
newline if current and target line number mismatched. The method is also
called when entering a new file, be it the main file or an include file.
In this situation line numbers always almost mismatch, resulting in a
newline for each occurance even if no tokens have been printed
in-between.

Empty lines at the beginning of the output must be trimmed because it
may be parsed by scripts expecting the result to appear on the first
output line, as done by LibreOffice's configure script.

Fix by only emitting a newline if tokens have been printed so far using
the EmittedTokensOnThisLine flag. Also adding a test case of FileChanged
callbacks occuring with empty include files.

This fixes llvm.org/PR51616

clang/lib/Frontend/PrintPreprocessedOutput.cpp
clang/test/Preprocessor/print_empty_include.c [new file with mode: 0644]
clang/test/Preprocessor/print_empty_include.h [new file with mode: 0644]
clang/test/Preprocessor/print_line_track.c

index 5c5fc75..3a3b158 100644 (file)
@@ -293,7 +293,7 @@ bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo,
       WriteLineInfo(LineNo, nullptr, 0);
     }
     StartedNewLine = true;
-  } else if (!StartedNewLine) {
+  } else if (EmittedTokensOnThisLine) {
     // If we are not on the correct line and don't need to be line-correct,
     // at least ensure we start on a new line.
     OS << '\n';
diff --git a/clang/test/Preprocessor/print_empty_include.c b/clang/test/Preprocessor/print_empty_include.c
new file mode 100644 (file)
index 0000000..04cda99
--- /dev/null
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -E -P %s | count 1
+// Ensure no superfluous newlines are printed
+// llvm.org/PR51616
+
+#include "print_empty_include.h"
+#include "print_empty_include.h"
+
+#define EXPANDED_TO_NOTHING
+EXPANDED_TO_NOTHING
+
diff --git a/clang/test/Preprocessor/print_empty_include.h b/clang/test/Preprocessor/print_empty_include.h
new file mode 100644 (file)
index 0000000..34b0701
--- /dev/null
@@ -0,0 +1,4 @@
+#if 0
+intentionally empty
+#endif
+
index fb2ccf2..156ae22 100644 (file)
@@ -3,7 +3,7 @@
  * RUN: %clang_cc1 -E -P %s | grep 'a 3'
  * RUN: %clang_cc1 -E -P %s | grep 'b 16'
  * RUN: %clang_cc1 -E %s | not grep '# 0 '
- * RUN: %clang_cc1 -E -P %s | count 4
+ * RUN: %clang_cc1 -E -P %s | count 2
  * PR1848 PR3437 PR7360
 */