From 85aaaf6e7409999842782f9fbcde3b5be4aa0c79 Mon Sep 17 00:00:00 2001 From: Dave Bartolomeo Date: Fri, 4 Jul 2025 00:36:57 -0400 Subject: [clang-tidy] EndSourceFile() for preprocessor before diagnostic client (#145784) The comment for `DiagnosticConsumer::BeginSourceFile()` states that "diagnostics with source range information are required to only be emitted in between BeginSourceFile() and EndSourceFile().". While working on some upcoming changes to the static analyzer, we hit some crashes when diagnostics were reported from the `EndOfMainFile` callback in the preprocessor. This turned out to be because `FrontEndAction::EndSourceFile()` notifies the diagnostic clients of the end of the source file before it notifies the preprocessor. Thus, the diagnostics from the preprocessor callback are reported when the diagnostic client is no longer expecting any diagnostics. The fix is to swap the order of the `EndSourceFile()` calls so that the preprocessor is notified first. I've added asserts to the `ClangTidyDiagnosticConsumer` to catch unexpected diagnostics outside of a source file. Before swapping the order of the calls as described above, this causes several failures in the clang-tidy regression tests. With the swap, there are no failures in `check-all`. rdar://141230583 --- clang/lib/Frontend/FrontendAction.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'clang/lib/Frontend/FrontendAction.cpp') diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index ef7ae27..f5996a8 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -1243,13 +1243,15 @@ llvm::Error FrontendAction::Execute() { void FrontendAction::EndSourceFile() { CompilerInstance &CI = getCompilerInstance(); - // Inform the diagnostic client we are done with this source file. - CI.getDiagnosticClient().EndSourceFile(); - // Inform the preprocessor we are done. if (CI.hasPreprocessor()) CI.getPreprocessor().EndSourceFile(); + // Inform the diagnostic client we are done with this source file. + // Do this after notifying the preprocessor, so that end-of-file preprocessor + // callbacks can report diagnostics. + CI.getDiagnosticClient().EndSourceFile(); + // Finalize the action. EndSourceFileAction(); -- cgit v1.1