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

fix: set C/C++ language standards per target #1217

Draft
wants to merge 21 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
3511b7b
Add c_language_standard and cxx_language_standard to pkginfo.
cgrindel Jul 14, 2024
f1c90ba
Add utility functions to detect c++ code.
cgrindel Jul 28, 2024
1bbcded
The interesting_deps example passes.
cgrindel Aug 4, 2024
16bec21
The resources_example works.
cgrindel Aug 4, 2024
74cc5e1
Remove debug comments
cgrindel Aug 4, 2024
b4a2b8d
Fix typo.
cgrindel Sep 8, 2024
8d6806e
Add language standard to copts.
cgrindel Sep 8, 2024
a23ca7a
Remove obsolete flag from interesting_deps.
cgrindel Sep 8, 2024
b50d75e
Split ObjC and ObjC++ targets. Fix missing linkopts.
cgrindel Sep 21, 2024
5e442b2
Generate a resource bundle accessor for ObjC and ObjC++.
cgrindel Sep 21, 2024
5265491
Include C in ObjC targets and C++ in ObjC++ targets.
cgrindel Sep 22, 2024
aa42238
Create a separate objc_library for the resource bundle accessor.
cgrindel Sep 22, 2024
6474330
Remove lock file for google_maps_example.
cgrindel Sep 22, 2024
6bba7a3
Fix clang_files_tests.
cgrindel Sep 22, 2024
71cac08
Fix swiftpkg_build_files_tests.
cgrindel Sep 22, 2024
cd20d8d
Address buildifier warnings.
cgrindel Sep 22, 2024
bc4974c
Avoid duplicate declaration by not passing along the hdrs to the uber
cgrindel Sep 28, 2024
8b0a717
Exclude textual_hdrs from the uber targets.
cgrindel Sep 28, 2024
73d1268
Fix incorrectly adding alwayslink to apple_dynamic_xcframework_import.
cgrindel Sep 28, 2024
42a936b
Add back the special handling the for the SWIFTPM_MODULE_BUNDLE.
cgrindel Sep 28, 2024
f0a8e2d
Update the swiftpkg_build_files_tests.
cgrindel Sep 29, 2024
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
529 changes: 0 additions & 529 deletions examples/google_maps_example/MODULE.bazel.lock

This file was deleted.

3 changes: 0 additions & 3 deletions examples/interesting_deps/.bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,3 @@ import %workspace%/../../ci.bazelrc

# Try to import a local.rc file; typically, written by CI
try-import %workspace%/../../local.bazelrc

# Required by geos
build --cxxopt='-std=c++11'
23 changes: 11 additions & 12 deletions examples/resources_example/Tests/MyAppTests/MyAppTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,26 @@ class MyAppTests: XCTestCase {
XCTAssertNotNil(actual)
}


func test_CoolStuff_bundleName() {
let bundle = Bundle.bundle(named: "package-with-resources_CoolUI")
XCTAssertNotNil(bundle)
}

func test_AppLovinSDKResources() throws {
let url = ALResourceManager.resourceBundleURL
XCTAssertNotNil(url)
}

func test_IterableDataModel() throws {
// Log Iterable messages to an array
class LogDelegate: IterableLogDelegate {
var messages: [String] = []
func log(level: LogLevel, message: String) {

func log(level _: LogLevel, message: String) {
messages.append(message)
}
}

let logDelegate = LogDelegate()
IterableLogUtil.sharedInstance = IterableLogUtil(
dateProvider: SystemDateProvider(),
Expand All @@ -41,14 +40,14 @@ class MyAppTests: XCTestCase {
// Create the persistence container from the bundled CoreData model
let container: PersistentContainer? = PersistentContainer.initialize()
XCTAssertNotNil(container)

// Assert that the persistence container was successfully created
let lastMessage = try XCTUnwrap(logDelegate.messages.last)
XCTAssert(
lastMessage.contains("Successfully loaded persistent store at:"),
"Expected success log message. Found: \(logDelegate.messages.last ?? "nil")"
)

IterableLogUtil.sharedInstance = nil
}
}
Expand All @@ -60,18 +59,18 @@ extension Foundation.Bundle {
let candidates = [
// Bundle should be present here when the package is linked into an App.
Bundle.main.resourceURL,

// Bundle should be present here when the package is linked into a framework.
Bundle(for: BundleFinder.self).resourceURL,

// For command-line tools.
Bundle.main.bundleURL,

// Bundle should be present here when running previews from a different package (this is the path to "…/Debug-iphonesimulator/").
Bundle(for: BundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent(),
Bundle(for: BundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent(),
]

for candidate in candidates {
let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
Expand Down
51 changes: 50 additions & 1 deletion swiftpkg/internal/clang_files.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,30 @@ _PUBLIC_HDR_DIRNAMES = ["include", "public"]
# https://bazel.build/reference/be/c-cpp#cc_library.srcs
_HEADER_EXTS = [".h", ".hh", ".hpp", ".hxx", ".inl", ".H"]

# C source extensions
_C_SRC_EXTS = [".c"]

# C++ source extensions
_CXX_SRC_EXTS = [".cc", ".cpp"]

# Objective-C source extensions
_OBJC_SRC_EXTS = [".m"]

_OBJCXX_SRC_EXTS = [".mm"]

# Assembly source extensions
_ASSEMBLY_SRC_EXTS = [".S"]

# Sources that should be included when constructing other cc_xxx targets
_OTHER_SRC_EXTS = [".so", ".o", ".inc"]

# Acceptable sources clang and objc:
# https://bazel.build/reference/be/c-cpp#cc_library.srcs
# https://bazel.build/reference/be/objective-c#objc_library.srcs
# NOTE: From examples found so far, .inc files tend to include source, not
# header declarations.
_SRC_EXTS = [".c", ".cc", ".cpp", ".S", ".so", ".o", ".m", ".mm", ".inc"]
_SRC_EXTS = _C_SRC_EXTS + _CXX_SRC_EXTS + _OBJC_SRC_EXTS + _OBJCXX_SRC_EXTS + \
_ASSEMBLY_SRC_EXTS + _OTHER_SRC_EXTS

def _is_hdr(path):
_root, ext = paths.split_extension(path)
Expand Down Expand Up @@ -323,6 +341,36 @@ def _collect_files(
textual_hdrs = sorted(textual_hdrs),
)

def _organize_srcs(srcs):
c_srcs = []
cxx_srcs = []
objc_srcs = []
objcxx_srcs = []
assembly_srcs = []
other_srcs = []
for src in srcs:
_root, ext = paths.split_extension(src)
if ext in _C_SRC_EXTS:
c_srcs.append(src)
elif ext in _CXX_SRC_EXTS:
cxx_srcs.append(src)
elif ext in _OBJC_SRC_EXTS:
objc_srcs.append(src)
elif ext in _OBJCXX_SRC_EXTS:
objcxx_srcs.append(src)
elif ext in _ASSEMBLY_SRC_EXTS:
assembly_srcs.append(src)
else:
other_srcs.append(src)
return struct(
c_srcs = c_srcs,
cxx_srcs = cxx_srcs,
objc_srcs = objc_srcs,
objcxx_srcs = objcxx_srcs,
assembly_srcs = assembly_srcs,
other_srcs = other_srcs,
)

clang_files = struct(
collect_files = _collect_files,
find_magical_public_hdr_dir = _find_magical_public_hdr_dir,
Expand All @@ -331,6 +379,7 @@ clang_files = struct(
is_include_hdr = _is_include_hdr,
is_public_modulemap = _is_public_modulemap,
is_under_path = _is_under_path,
organize_srcs = _organize_srcs,
reduce_paths = _reduce_paths,
relativize = _relativize,
)
13 changes: 10 additions & 3 deletions swiftpkg/internal/objc_resource_bundle_accessor.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ Generate an ObjC header file with an SPM-specific `SWIFTPM_MODULE_BUNDLE` macro.
)

def _objc_resource_bundle_accessor_impl_impl(ctx):
accessor_impl = ctx.actions.declare_file("{}_ObjcResourceBundleAccessor.m".format(
ctx.label.name,
))
accessor_impl = ctx.actions.declare_file(
"{label}_ObjcResourceBundleAccessor.{ext}".format(
ext = ctx.attr.extension,
label = ctx.label.name,
),
)
ctx.actions.expand_template(
template = ctx.file._impl_template,
output = accessor_impl,
Expand All @@ -52,6 +55,10 @@ objc_resource_bundle_accessor_impl = rule(
mandatory = True,
doc = "The name of the resource bundle.",
),
"extension": attr.string(
default = "m",
doc = "The extension for the accessor implementation file.",
),
"module_name": attr.string(
mandatory = True,
doc = "The name of the module.",
Expand Down
13 changes: 13 additions & 0 deletions swiftpkg/internal/pkginfo_targets.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ _modulemap_suffix = "_modulemap"
_resource_bundle_suffix = "_resource_bundle"
_objc_resource_bundle_accessor_hdr_suffix = "_objc_resource_bundle_accessor_hdr"
_objc_resource_bundle_accessor_impl_suffix = "_objc_resource_bundle_accessor_impl"
_objc_resource_bundle_accessor_library_suffix = "_objc_resource_bundle_accessor_library"
_resource_bundle_accessor_suffix = "_resource_bundle_accessor"
_resource_bundle_infoplist_suffix = "_resource_bundle_infoplist"
_swift_hint_suffix = "_swift_hint"
Expand Down Expand Up @@ -196,6 +197,17 @@ def _objc_resource_bundle_accessor_impl_label_name(target_name):
"""
return target_name + _objc_resource_bundle_accessor_impl_suffix

def _objc_resource_bundle_accessor_library_label_name(target_name):
"""Returns the name of the related `objc_library` target.

Args:
target_name: The publicly advertised name for the Swift target.

Returns:
The name of the `objc_library` as a `string`.
"""
return target_name + _objc_resource_bundle_accessor_library_suffix

def _resource_bundle_accessor_label_name(target_name):
"""Returns the name of the related `resource_bundle_accessor` target.

Expand Down Expand Up @@ -275,6 +287,7 @@ def make_pkginfo_targets(bazel_labels):
modulemap_label_name = _modulemap_label_name,
objc_resource_bundle_accessor_hdr_label_name = _objc_resource_bundle_accessor_hdr_label_name,
objc_resource_bundle_accessor_impl_label_name = _objc_resource_bundle_accessor_impl_label_name,
objc_resource_bundle_accessor_library_label_name = _objc_resource_bundle_accessor_library_label_name,
resource_bundle_accessor_label_name = _resource_bundle_accessor_label_name,
resource_bundle_infoplist_label_name = _resource_bundle_infoplist_label_name,
resource_bundle_label_name = _resource_bundle_label_name,
Expand Down
16 changes: 14 additions & 2 deletions swiftpkg/internal/pkginfos.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,8 @@ def _new_from_parsed_json(
targets = targets,
url = url,
version = version,
c_language_standard = dump_manifest.get("cLanguageStandard"),
cxx_language_standard = dump_manifest.get("cxxLanguageStandard"),
)

# MARK: - Swift Package
Expand All @@ -638,7 +640,9 @@ def _new(
products = [],
targets = [],
url = None,
version = None):
version = None,
c_language_standard = None,
cxx_language_standard = None):
"""Returns a `struct` representing information about a Swift package.

Args:
Expand All @@ -657,6 +661,10 @@ def _new(
`pkginfos.new_target()`.
url: Optional. The url of the package (`string`).
version: Optional. The semantic version of the package (`string`).
c_language_standard: Optional. The c language standard (e.g. `c99`,
`gnu99`, `c11`).
cxx_language_standard: Optional. The c++ language standard (e.g.
`c++11`, `c++20`).

Returns:
A `struct` representing information about a Swift package.
Expand All @@ -672,6 +680,8 @@ def _new(
targets = targets,
url = url,
version = version,
c_language_standard = c_language_standard,
cxx_language_standard = cxx_language_standard,
)

# MARK: - Platform
Expand Down Expand Up @@ -1165,6 +1175,8 @@ def _new_clang_src_info_from_sources(
srcs = sets.to_list(srcs_set)
explicit_srcs = sets.to_list(explicit_srcs_set)

# TODO(chuck): Can I remove explicit_srcs? I believe that it is obsolete.

return _new_clang_src_info(
srcs = srcs,
explicit_srcs = explicit_srcs,
Expand All @@ -1184,7 +1196,7 @@ def _new_clang_src_info(
private_includes = [],
modulemap_path = None):
return struct(
srcs = srcs,
organized_srcs = clang_files.organize_srcs(srcs),
explicit_srcs = explicit_srcs,
hdrs = hdrs,
textual_hdrs = textual_hdrs,
Expand Down
41 changes: 38 additions & 3 deletions swiftpkg/internal/starlark_codegen.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,30 @@ def _to_starlark(val):
fail("Failed to finish processing starlark for value: {}".format(val))

def _process_complex_types(out):
def _fail_with_orig_out(msg):
def _pad_str(width, value):
value = str(value)
val_len = len(value)
if val_len >= width:
return value
padding = width - val_len
return " " * padding + value

# buildifier: disable=print
print("*** DEBUG _process_complex_types out: ")

# Not sure why buildifier is complaining about idx not being initialized.
# buildifier: disable=uninitialized
for idx, item in enumerate(out):
# buildifier: disable=print
# buildifier: disable=uninitialized
print("*** DEBUG", _pad_str(3, idx), ":", _pad_str(7, type(item)), ":", item)
fail(msg)

finished = True
new_out = []
for v in out:

for idx, v in enumerate(out):
v_type = type(v)

# Check for a with_indent struct and get its indent value and process
Expand Down Expand Up @@ -127,10 +148,24 @@ def _process_complex_types(out):
elif v_type == "struct":
to_starlark_fn = getattr(v, "to_starlark_parts", None)
if to_starlark_fn == None:
fail("Starlark code gen received a struct without a to_starlark_parts function.", v)
_fail_with_orig_out(
"""\
Starlark code gen received a struct without a to_starlark_parts function. \
idx: {idx}, v: {v}\
""".format(
idx = idx,
v = v,
),
)
new_out.extend(to_starlark_fn(v, current_indent))
else:
fail("Starlark code gen received an unsupported type.", v_type, v)
_fail_with_orig_out("""\
Starlark code gen received an unsupported type. idx: {idx}, v_type: {v_type}, v: {v}\
""".format(
idx = idx,
v_type = v_type,
v = v,
))

return new_out, finished

Expand Down
Loading
Loading