Swift: Replace hyphens with underscores in default module name

GetSwiftModuleName() returns the target name verbatim when
Swift_MODULE_NAME is not set, but hyphens are not valid in Swift
module identifiers.  Replace them with underscores so that targets
like swift-syntax get module name swift_syntax automatically.

Issue: #27748
This commit is contained in:
Roman Lavrov
2026-04-27 19:21:29 -04:00
parent de52c08ba2
commit 933c59ffde
6 changed files with 39 additions and 2 deletions
+2 -1
View File
@@ -4,4 +4,5 @@ Swift_MODULE_NAME
.. versionadded:: 3.15
This property specifies the name of the Swift module. It is defaulted to the
name of the target.
name of the target, with hyphens replaced by underscores (hyphens are not valid
in Swift module identifiers).
@@ -6,3 +6,6 @@ swift-ninja-separate-swiftmodule-edge
the :variable:`CMAKE_Swift_SEPARATE_MODULE_EMISSION` variable, to control
whether importable Swift targets emit ``.swiftmodule`` from a dedicated
build edge. Policy :policy:`CMP0215` enables this by default.
* The default :prop_tgt:`Swift_MODULE_NAME` now replaces hyphens with
underscores, since hyphens are not valid in Swift module identifiers.
+7 -1
View File
@@ -6173,7 +6173,13 @@ std::string cmGeneratorTarget::BuildDatabasePath(
std::string cmGeneratorTarget::GetSwiftModuleName() const
{
return this->GetPropertyOrDefault("Swift_MODULE_NAME", this->GetName());
if (cmValue name = this->GetProperty("Swift_MODULE_NAME")) {
return *name;
}
// Hyphens are not valid in Swift module identifiers.
std::string name = this->GetName();
std::replace(name.begin(), name.end(), '-', '_');
return name;
}
std::string cmGeneratorTarget::GetSwiftModuleFileName() const
+7
View File
@@ -171,6 +171,13 @@ if(RunCMake_GENERATOR MATCHES "Ninja")
endif()
endblock()
block()
set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/SwiftModuleNameHyphen-build)
run_cmake(SwiftModuleNameHyphen)
set(RunCMake_TEST_NO_CLEAN 1)
run_cmake_command(SwiftModuleNameHyphen-build ${CMAKE_COMMAND} --build . -- -vn)
endblock()
block()
set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/SwiftLibraryModuleCommand-build)
run_cmake(SwiftLibraryModuleCommand)
@@ -0,0 +1,9 @@
# The module name should have underscores, not hyphens.
if(NOT actual_stdout MATCHES "-module-name L_hyphen")
string(APPEND RunCMake_TEST_FAILED
"Expected '-module-name L_hyphen', hyphens should be replaced with underscores.\n")
endif()
if(actual_stdout MATCHES "-module-name L-hyphen")
string(APPEND RunCMake_TEST_FAILED
"Found '-module-name L-hyphen', hyphens are not valid in Swift module names.\n")
endif()
@@ -0,0 +1,11 @@
cmake_policy(SET CMP0157 NEW)
if(NOT CMAKE_GENERATOR MATCHES "Ninja")
message(SEND_ERROR "this test must use a Ninja generator, found ${CMAKE_GENERATOR}")
endif()
enable_language(Swift)
# A target with hyphens in the name. Swift module names cannot contain
# hyphens, so CMake should replace them with underscores.
add_library(L-hyphen STATIC L.swift)