Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic support for generating C++ header from Swift code #14241

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions mesonbuild/compilers/swift.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from __future__ import annotations

import json
import re
import subprocess, os.path
import typing as T
Expand All @@ -29,6 +30,27 @@
's': ['-O'],
}


def _get_swift_library_paths(exelist: T.List[str], info: MachineInfo, static: bool) -> T.List[str]:
try:
command = [*exelist, '-print-target-info']
if static:
command += ['-static-stdlib']
s = subprocess.check_output(command, universal_newlines=True,
encoding='utf-8', stderr=subprocess.STDOUT)
data = json.loads(s)
paths = [
*data['paths']['runtimeLibraryPaths'],
*data['paths']['runtimeLibraryImportPaths'],
*([data['paths']['sdkPath']] if info.is_darwin() else []),
]
return paths
except subprocess.CalledProcessError as e:
raise MesonException(f'Failed to get Swift target info: {e.output}')
except KeyError:
raise MesonException('Failed to extract Swift library path')


class SwiftCompiler(Compiler):

LINKER_PREFIX = ['-Xlinker']
Expand All @@ -54,6 +76,9 @@ def __init__(self, exelist: T.List[str], version: str, for_machine: MachineChoic
mlog.error('xcrun not found. Install Xcode to compile Swift code.')
raise MesonException('Could not detect Xcode. Please install it to compile Swift code.')

self.dynamic_library_path: T.List[str] = _get_swift_library_paths(exelist, info, False)
self.static_library_path: T.List[str] = _get_swift_library_paths(exelist, info, True)

def get_pic_args(self) -> T.List[str]:
return []

Expand Down
66 changes: 66 additions & 0 deletions mesonbuild/modules/swift.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: 2025 The Meson development team

from __future__ import annotations

import typing as T

from . import NewExtensionModule, ModuleInfo, ModuleReturnValue
from mesonbuild import build
from mesonbuild.compilers.swift import SwiftCompiler
from mesonbuild.interpreterbase.decorators import typed_kwargs, typed_pos_args

if T.TYPE_CHECKING:
from . import ModuleState
from mesonbuild.interpreter import Interpreter


def initialize(*args: T.Any, **kwargs: T.Any) -> SwiftModule:
return SwiftModule(*args, **kwargs)


class SwiftModule(NewExtensionModule):
INFO = ModuleInfo('swift', '1.7.99')

def __init__(self, interpreter: Interpreter):
super().__init__()
self.interpreter = interpreter
self.swiftc: T.Optional[SwiftCompiler]

try:
swiftc = interpreter.compilers.host['swift']
assert isinstance(swiftc, SwiftCompiler), 'swiftc is not an instance of SwiftCompiler'
self.swiftc = swiftc
except KeyError:
self.swiftc = None

self.methods.update({
'get_library_path': self.get_library_path,
'generate_cpp_header': self.generate_cpp_header,
})

@typed_pos_args('swift.get_library_path')
@typed_kwargs('swift.get_library_path')
def get_library_path(self, state: ModuleState, args, kwargs) -> ModuleReturnValue:
paths = [*self.swiftc.dynamic_library_path, *self.swiftc.static_library_path]
return ModuleReturnValue(paths, [])

@typed_pos_args('swift.generate_cpp_header', build.BuildTarget)
@typed_kwargs('swift.generate_cpp_header')
def generate_cpp_header(self, state: ModuleState, args: T.Tuple[build.BuildTarget], kwargs) -> ModuleReturnValue:
(module,) = args

header_name = f'{module.name}-Swift.h'
command = [
*self.swiftc.get_exelist(),
'@INPUT@',
*self.swiftc.get_module_args(module.name),
*self.swiftc.get_cxx_interoperability_args(self.interpreter.compilers.host),
'-emit-clang-header-path', '@OUTPUT@',
]

tgt = build.CustomTarget(header_name, state.subdir, state.subproject, state.environment, command,
module.get_sources() + module.get_generated_sources(), [header_name],
backend=state.backend)

return ModuleReturnValue(tgt, [tgt])
Loading