[clang] [Clang] Reject and recover from malformed module directive (PR #245099)

Aleksei Poleskov via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 22 16:06:39 PST 2026


https://github.com/the-lenoz created https://github.com/llvm/llvm-project/pull/245099

Clang accepts malformed module directives such as `module :foo;`
and can misparse or skip subsequent declarations during recovery.

This patch diagnoses a colon without a preceding module name:
`module :...` expects `private`, while `export module :...` expects
a module name.

For malformed directives, the preprocessor discards tokens up to the
semicolon or the end of the directive and supplies a synthetic
semicolon to the parser. This prevents unmatched opening delimiters
from being passed to parser recovery, where they could cause
`SkipUntil` to skip subsequent declarations. The synthetic token uses
the first invalid token's location so the diagnostic points to the
relevant source location. If the end-of-directive token was consumed,
it is preserved to avoid reading past the directive.

The tests cover diagnostics and their locations, recovery of subsequent
declarations, unmatched delimiters, missing semicolons, EOF, and valid
private module fragments and module partitions.

The initial regression tests were generated with OpenAI Codex assistance
and reviewed and refined by the authors.

Testing:
- `build/bin/llvm-lit -v clang/test/Parser/cxx20-module-colon-recovery.cpp` - passed


Co-authored-by: @priusf0x

Fixes #245098

>From ab5a9f5c9f17c7cba2c67b9322745da36aa4caaa Mon Sep 17 00:00:00 2001
From: Aleksei Poleskov <122558239+the-lenoz at users.noreply.github.com>
Date: Mon, 23 Nov 2026 02:43:13 +0300
Subject: [PATCH] [Clang] Reject and recover from malformed module directives

Improve parser recovery when a colon appears in an invalid position
in a module directive.

Add regression tests for malformed directives. The initial tests were
generated with Codex assistance and reviewed and refined by the authors.

Co-authored-by: priusf0x <priusfoxlittle at gmail.com>
Assisted-by: OpenAI Codex (test generation)
---
 .../clang/Basic/DiagnosticParseKinds.td       |   1 +
 clang/lib/Lex/PPDirectives.cpp                |  23 ++-
 clang/lib/Parse/Parser.cpp                    |  42 +++--
 .../Parser/cxx20-module-colon-recovery.cpp    | 163 ++++++++++++++++++
 4 files changed, 209 insertions(+), 20 deletions(-)
 create mode 100644 clang/test/Parser/cxx20-module-colon-recovery.cpp

diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 2be6ff8344cd6d..96110be3a57fef 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1651,6 +1651,7 @@ def ext_bit_int : Extension<
 } // end of Parse Issue category.
 
 let CategoryName = "Modules Issue" in {
+def err_expected_module_name : Error<"expected module name">;
 def err_unexpected_tok_after_module_name : Error<
   "unexpected '%0' after module name, only ';' and '[' (start of attribute "
   "specifier sequence) are allowed">;
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index ecb9e42c88bc0d..57bcbfe4bbf248 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -4362,11 +4362,24 @@ void Preprocessor::HandleCXXModuleDirective(Token ModuleTok) {
     DirToks.push_back(Tok);
     LexUnexpandedToken(Tok);
     if (Tok.isNot(tok::kw_private)) {
-      if (Tok.isNot(tok::eod))
-        CheckEndOfDirective(ModuleTok.getIdentifierInfo()->getName(),
-                            /*EnableMacros=*/false, &DirToks);
-      EnterModuleSuffixTokenStream(DirToks);
-      return;
+      // Remember wrong token location.
+      SourceLocation WrongTokLoc = Tok.getLocation();
+
+      // Discard tokens up to ';' or the end of the directive. Passing unmatched
+      // opening delimiters to the parser could make recovery skip subsequent
+      // declarations.
+      while (Tok.isNoneOf(tok::semi, tok::eod, tok::eof))
+        LexUnexpandedNonComment(Tok);
+
+      // Add synthetic semicolon to let parser recover
+      // assign its location to wrong token's to let parser highlight it in diagnostics.
+      DirToks.push_back(Token::create(tok::semi, WrongTokLoc));
+
+      // Preserve the consumed end-of-directive token so the code below does not read
+      // past this directive.
+      if (Tok.is(tok::eod))
+        DirToks.push_back(Tok);
+      break;
     }
     DirToks.push_back(Tok);
     break;
diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index fbfc632c47e45b..a4810fe923de65 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -2377,23 +2377,35 @@ Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
   }
 
   // Parse a private-module-fragment, if present.
-  if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
-      NextToken().is(tok::kw_private)) {
-    if (MDK == Sema::ModuleDeclKind::Interface) {
-      Diag(StartLoc, diag::err_module_fragment_exported)
-        << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
+  if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) {
+    if (NextToken().is(tok::kw_private)) {
+      if (MDK == Sema::ModuleDeclKind::Interface) {
+        Diag(StartLoc, diag::err_module_fragment_exported)
+            << /*private*/ 1 << FixItHint::CreateRemoval(StartLoc);
+      }
+      ConsumeToken();
+      SourceLocation PrivateLoc = ConsumeToken();
+      DiagnoseAndSkipCXX11Attributes();
+      ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
+      auto Result =
+          Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
+      if (Result) {
+        ImportState =
+            ImportState == Sema::ModuleImportState::ImportAllowed
+                ? Sema::ModuleImportState::PrivateFragmentImportAllowed
+                : Sema::ModuleImportState::PrivateFragmentImportFinished;
+      }
+      return nullptr;
     }
-    ConsumeToken();
-    SourceLocation PrivateLoc = ConsumeToken();
-    DiagnoseAndSkipCXX11Attributes();
-    ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
-    auto Result = Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
-    if (Result) {
-      ImportState =
-          ImportState == Sema::ModuleImportState::ImportAllowed
-              ? Sema::ModuleImportState::PrivateFragmentImportAllowed
-              : Sema::ModuleImportState::PrivateFragmentImportFinished;
+
+    if (MDK == Sema::ModuleDeclKind::Interface) {
+      // module directive with "export" prefix, so we expect module name instead of colon.
+      Diag(Tok, diag::err_expected_module_name);
+    } else {
+      // Unexpected token, expecting "private" keyword.
+      Diag(NextToken(), diag::err_expected) << tok::kw_private;
     }
+    SkipUntil(tok::semi);
     return nullptr;
   }
   SmallVector<IdentifierLoc, 2> Path;
diff --git a/clang/test/Parser/cxx20-module-colon-recovery.cpp b/clang/test/Parser/cxx20-module-colon-recovery.cpp
new file mode 100644
index 00000000000000..4d28b228c10205
--- /dev/null
+++ b/clang/test/Parser/cxx20-module-colon-recovery.cpp
@@ -0,0 +1,163 @@
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/implementation.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/interface.cpp
+// RUN: not %clang_cc1 -std=c++20 -fsyntax-only -fno-caret-diagnostics %t/implementation.cpp 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=IMPL-LOC
+// RUN: not %clang_cc1 -std=c++20 -fsyntax-only -fno-caret-diagnostics %t/interface.cpp 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=IFACE-LOC
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/same-line.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/private.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/partition.cpp
+// RUN: %clang_cc1 -std=c++20 -E -P %t/implementation.cpp | FileCheck %s --check-prefix=PP
+// RUN: %python -c "from pathlib import Path; [p.write_bytes(p.read_bytes().rstrip(b'\r\n')) for p in Path(r'%t').glob('eof-*.cpp')]"
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/eof-identifier.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/eof-colon.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/eof-semicolon.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/eof-export-identifier.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/eof-export-colon.cpp
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %t/eof-export-semicolon.cpp
+
+// Each declaration following a malformed directive is used immediately, so
+// skipping that declaration during recovery produces an unexpected diagnostic.
+// The final failing assertion also checks that recovery does not skip to EOF.
+// Preprocessing must preserve the declarations on subsequent lines as well.
+
+// Check that the implementation diagnostic points to the first invalid token.
+// The interface diagnostic should point to the colon where a name is expected.
+// IMPL-LOC: implementation.cpp:1:9: error: expected private
+// IFACE-LOC: interface.cpp:1:15: error: expected module name
+
+// PP: constexpr int after_identifier = 42;
+// PP: constexpr int after_semicolon = 42;
+// PP: constexpr int after_parentheses = 42;
+// PP: constexpr int after_brackets = 42;
+// PP: constexpr int after_braces = 42;
+// PP: constexpr int after_dotted_name = 42;
+// PP: constexpr int after_macro = 42;
+// PP: constexpr int after_comment = 42;
+// PP: constexpr int after_missing_semicolon = 42;
+// PP: constexpr int after_colon = 42;
+// PP: constexpr int after_unclosed_parenthesis = 42;
+
+//--- implementation.cpp
+module :foo; // expected-error {{expected private}}
+constexpr int after_identifier = 42;
+static_assert(after_identifier == 42);
+
+module :; // expected-error {{expected private}}
+constexpr int after_semicolon = 42;
+static_assert(after_semicolon == 42);
+
+module :(bad); // expected-error {{expected private}}
+constexpr int after_parentheses = 42;
+static_assert(after_parentheses == 42);
+
+module :[bad]; // expected-error {{expected private}}
+constexpr int after_brackets = 42;
+static_assert(after_brackets == 42);
+
+module :{bad}; // expected-error {{expected private}}
+constexpr int after_braces = 42;
+static_assert(after_braces == 42);
+
+module :foo.bar; // expected-error {{expected private}}
+constexpr int after_dotted_name = 42;
+static_assert(after_dotted_name == 42);
+
+#define BAD_NAME foo.bar
+module :BAD_NAME; // expected-error {{expected private}}
+constexpr int after_macro = 42;
+static_assert(after_macro == 42);
+
+module : /* comment */ foo; // expected-error {{expected private}}
+constexpr int after_comment = 42;
+static_assert(after_comment == 42);
+
+module :foo // expected-error {{expected private}}
+constexpr int after_missing_semicolon = 42;
+static_assert(after_missing_semicolon == 42);
+
+module : // expected-error {{expected private}}
+constexpr int after_colon = 42;
+static_assert(after_colon == 42);
+
+module :( // expected-error {{expected private}}
+constexpr int after_unclosed_parenthesis = 42;
+static_assert(after_unclosed_parenthesis == 42);
+
+static_assert(false, "recovery reached"); // expected-error {{static assertion failed: recovery reached}}
+
+//--- interface.cpp
+export module :foo; // expected-error {{expected module name}}
+constexpr int after_identifier = 42;
+static_assert(after_identifier == 42);
+
+export module :; // expected-error {{expected module name}}
+constexpr int after_semicolon = 42;
+static_assert(after_semicolon == 42);
+
+export module :(bad); // expected-error {{expected module name}}
+constexpr int after_parentheses = 42;
+static_assert(after_parentheses == 42);
+
+export module :[bad]; // expected-error {{expected module name}}
+constexpr int after_brackets = 42;
+static_assert(after_brackets == 42);
+
+export module :{bad}; // expected-error {{expected module name}}
+constexpr int after_braces = 42;
+static_assert(after_braces == 42);
+
+export module :foo // expected-error {{expected module name}}
+constexpr int after_missing_semicolon = 42;
+static_assert(after_missing_semicolon == 42);
+
+export module : // expected-error {{expected module name}}
+constexpr int after_colon = 42;
+static_assert(after_colon == 42);
+
+export module :( // expected-error {{expected module name}}
+constexpr int after_unclosed_parenthesis = 42;
+static_assert(after_unclosed_parenthesis == 42);
+
+static_assert(false, "recovery reached"); // expected-error {{static assertion failed: recovery reached}}
+
+//--- same-line.cpp
+// Tokens after the terminating semicolon are diagnosed by the preprocessor,
+// but must still be available to the parser after recovery.
+module :foo; constexpr int after_same_line = 42; // expected-error {{expected private}} expected-warning {{extra tokens after semicolon in 'module' directive}}
+static_assert(after_same_line == 42);
+static_assert(false, "recovery reached"); // expected-error {{static assertion failed: recovery reached}}
+
+//--- private.cpp
+// expected-no-diagnostics
+export module M;
+module :private;
+constexpr int after_private = 42;
+static_assert(after_private == 42);
+
+//--- partition.cpp
+// expected-no-diagnostics
+export module M:part;
+export constexpr int value = 42;
+static_assert(value == 42);
+
+//--- eof-identifier.cpp
+// EOF cases are stripped of trailing newlines before compilation.
+// expected-error at +1 {{expected private}}
+module :foo
+//--- eof-colon.cpp
+// expected-error at +1 {{expected private}}
+module :
+//--- eof-semicolon.cpp
+// expected-error at +1 {{expected private}}
+module :;
+//--- eof-export-identifier.cpp
+// expected-error at +1 {{expected module name}}
+export module :foo
+//--- eof-export-colon.cpp
+// expected-error at +1 {{expected module name}}
+export module :
+//--- eof-export-semicolon.cpp
+// expected-error at +1 {{expected module name}}
+export module :;



More information about the cfe-commits mailing list