From ae98cdb66f40d994fe990d7b8b354da3c1d330d4 Mon Sep 17 00:00:00 2001 From: Agent <344224964+logan-shire-agent[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:59:28 -0500 Subject: [PATCH 1/3] Foundation is the Swift SDK's on Android and the web: Isomer's Swift SDKs registered by URL, foundation/'s sources moved to isomer_hermetic_toolchains (docs/hermetic_toolchains.md) Isomer's Swift SDKs (AttilaTheFun/isomer_hermetic_toolchains, isomer-6.4.2) are swift.org's 6.4.2 Android and WebAssembly SDKs with corelibs Foundation taken out and Isomer's Foundation, FoundationNetworking, IsomerFoundation, CoreGraphics and Combine put in, plain or -i18n (FoundationInternationalization and the SDK's ICU), so every `import Foundation` there is Isomer's with no dependency declared. - Package.swift: no Foundation, FoundationNetworking or IsomerFoundation targets and no swift-foundation dependency; CoreGraphics and Combine for Linux and Windows only. - @isomer//:foundation and :isomer_foundation empty on Android and the web; //core_graphics and //frameworks/combine the SDK's there. Foundation's configure_package target_deps gone (isomer's and the examples'). - --@isomer//foundation:internationalization checks that the -i18n SDK is registered. - isomer registers the -i18n SDKs (Foundation's tests and ICU's trimming run against them), the examples the plain ones; rules_swift 4.2.2.isomer.4 for swift.android_sdk(url = ...). - FileWrapper.swift to shared/swift_ui_corelibs; tools/foundation/check_link.py removed; tools/parity reads the SDK's Foundation family. - README: "Isomer's Swift SDKs", one snippet a platform, and the Upgrading notes. --- AGENTS.md | 85 +-- BUILD.bazel | 43 +- MODULE.bazel | 123 ++-- Package.swift | 106 +-- README.md | 147 +++- TODO.md | 40 +- core_graphics/BUILD.bazel | 32 +- docs/hermetic_toolchains.md | 257 ++++--- docs/library_evolution.md | 6 +- docs/prebuilt_swift_libraries.md | 15 +- examples/.bazelrc | 12 +- examples/MODULE.bazel | 95 +-- .../swift_packages/Package.resolved | 17 - .../third_party/swift_packages/Package.swift | 2 +- foundation/BUILD.bazel | 87 +-- foundation/Bundle.swift | 356 --------- foundation/CalendarSymbols.swift | 44 -- foundation/CharacterSet.swift | 519 ------------- foundation/Combine.swift | 90 --- foundation/FileHandle.swift | 223 ------ foundation/FileManager+ItemType.swift | 21 - foundation/FileWrapper.swift | 141 ---- foundation/Foundation.swift | 43 -- foundation/HTTPCookieStorage.swift | 18 - foundation/ISO8601DateFormatter.swift | 71 -- foundation/IndexSet.swift | 374 ---------- foundation/JSONSerialization.swift | 375 ---------- foundation/Locks.swift | 184 ----- foundation/NSError.swift | 172 ----- foundation/NSNumber.swift | 132 ---- foundation/NSNumberBridging.swift | 407 ----------- foundation/NSObject.swift | 39 - foundation/NSRange.swift | 127 ---- foundation/NSRegularExpression.swift | 306 -------- foundation/NSUUID.swift | 77 -- foundation/NotificationCenter.swift | 167 ----- foundation/OperationQueue.swift | 34 - foundation/Paths.swift | 53 -- foundation/RelativeDateTimeFormatter.swift | 127 ---- foundation/Stream.swift | 223 ------ foundation/String+Format.swift | 244 ------- foundation/StringProtocol+NSString.swift | 281 ------- foundation/Thread.swift | 189 ----- foundation/URLError.swift | 304 -------- foundation/URLRequest.swift | 206 ------ foundation/URLResourceValues.swift | 39 - foundation/URLResponse.swift | 156 ---- foundation/URLSession.swift | 689 ------------------ foundation/URLSessionTask.swift | 299 -------- foundation/URLSessionWebSocketTask.swift | 336 --------- foundation/UserDefaults.swift | 321 -------- foundation/defs.bzl | 13 +- foundation/dispatch_time/DispatchTime.swift | 10 - foundation/internationalization/BUILD.bazel | 32 +- ...IsomerFoundationInternationalization.swift | 3 - .../SDKInternationalization.swift | 6 + foundation/isomer_foundation/BUILD.bazel | 43 -- .../isomer_foundation/IsomerNetwork.swift | 273 ------- .../IsomerUserDefaults.swift | 37 - foundation/networking/BUILD.bazel | 16 - .../networking/FoundationNetworking.swift | 8 - foundation/tests/BUILD.bazel | 24 +- foundation/wasi_thread_identity/identity.c | 23 - foundation/wasi_thread_identity/identity.h | 9 - frameworks/BUILD.bazel | 11 +- frameworks/combine/BUILD.bazel | 19 +- shared/BUILD.bazel | 8 + shared/swift_ui_corelibs/FileWrapper.swift | 145 +++- tests/snapshot/BUILD.bazel | 2 +- third_party/swift_packages/Package.resolved | 17 - third_party/swift_packages/Package.swift | 8 +- tools/foundation/check_link.py | 87 --- tools/library_evolution/defs.bzl | 16 +- tools/parity/parity.py | 47 +- tools/parity/reasons/Foundation.json | 4 +- .../swift_foundation_apple_interface.patch | 195 ----- ...ift_foundation_create_directory_root.patch | 13 - .../swift_foundation_package_helpers.patch | 89 --- tools/patches/swift_foundation_sdk_icu.patch | 22 - tools/platforms/transition.bzl | 8 +- tools/wasm/defs.bzl | 9 +- 81 files changed, 826 insertions(+), 8825 deletions(-) delete mode 100644 foundation/Bundle.swift delete mode 100644 foundation/CalendarSymbols.swift delete mode 100644 foundation/CharacterSet.swift delete mode 100644 foundation/Combine.swift delete mode 100644 foundation/FileHandle.swift delete mode 100644 foundation/FileManager+ItemType.swift delete mode 100644 foundation/FileWrapper.swift delete mode 100644 foundation/Foundation.swift delete mode 100644 foundation/HTTPCookieStorage.swift delete mode 100644 foundation/ISO8601DateFormatter.swift delete mode 100644 foundation/IndexSet.swift delete mode 100644 foundation/JSONSerialization.swift delete mode 100644 foundation/Locks.swift delete mode 100644 foundation/NSError.swift delete mode 100644 foundation/NSNumber.swift delete mode 100644 foundation/NSNumberBridging.swift delete mode 100644 foundation/NSObject.swift delete mode 100644 foundation/NSRange.swift delete mode 100644 foundation/NSRegularExpression.swift delete mode 100644 foundation/NSUUID.swift delete mode 100644 foundation/NotificationCenter.swift delete mode 100644 foundation/OperationQueue.swift delete mode 100644 foundation/Paths.swift delete mode 100644 foundation/RelativeDateTimeFormatter.swift delete mode 100644 foundation/Stream.swift delete mode 100644 foundation/String+Format.swift delete mode 100644 foundation/StringProtocol+NSString.swift delete mode 100644 foundation/Thread.swift delete mode 100644 foundation/URLError.swift delete mode 100644 foundation/URLRequest.swift delete mode 100644 foundation/URLResourceValues.swift delete mode 100644 foundation/URLResponse.swift delete mode 100644 foundation/URLSession.swift delete mode 100644 foundation/URLSessionTask.swift delete mode 100644 foundation/URLSessionWebSocketTask.swift delete mode 100644 foundation/UserDefaults.swift delete mode 100644 foundation/dispatch_time/DispatchTime.swift delete mode 100644 foundation/internationalization/IsomerFoundationInternationalization.swift create mode 100644 foundation/internationalization/SDKInternationalization.swift delete mode 100644 foundation/isomer_foundation/BUILD.bazel delete mode 100644 foundation/isomer_foundation/IsomerNetwork.swift delete mode 100644 foundation/isomer_foundation/IsomerUserDefaults.swift delete mode 100644 foundation/networking/BUILD.bazel delete mode 100644 foundation/networking/FoundationNetworking.swift delete mode 100644 foundation/wasi_thread_identity/identity.c delete mode 100644 foundation/wasi_thread_identity/identity.h mode change 120000 => 100644 shared/swift_ui_corelibs/FileWrapper.swift delete mode 100755 tools/foundation/check_link.py delete mode 100644 tools/patches/swift_foundation_apple_interface.patch delete mode 100644 tools/patches/swift_foundation_create_directory_root.patch delete mode 100644 tools/patches/swift_foundation_package_helpers.patch delete mode 100644 tools/patches/swift_foundation_sdk_icu.patch diff --git a/AGENTS.md b/AGENTS.md index 3127e92c..2dc09d82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ management. The repo is ONE Bazel module, `isomer`, plus the examples: | --- | --- | --- | | `.` | `isomer` | everything below | | `swift_ffi/` | (isomer) | the Swift <-> Kotlin/JavaScript/C bridge generator: macros, analyzer, generator, rules, runtimes. Labels `//swift_ffi/...` (`@isomer//swift_ffi/...` from outside). Its own examples are `swift_ffi/examples`; docs in `docs/swift_ffi/`. Every BUILD file under it carries `package(features = [swift.enable_v6, treat_warnings_as_errors, ...])` — what its REPO.bazel said when it was a repo; keep that on new packages there | -| `core_graphics/`, `foundation/` | (isomer) | Isomer's `CoreGraphics` and `Foundation` for the platforms without Apple's (see "Apple's frameworks off Apple") | +| `core_graphics/`, `foundation/` | (isomer) | Isomer's `CoreGraphics` for Linux and Windows, and Foundation's build settings and tests: Isomer's `Foundation`, and Android's and the web's CoreGraphics and Combine, are in Isomer's Swift SDKs since 0.56 (AttilaTheFun/isomer_hermetic_toolchains; see "Apple's frameworks off Apple") | | `frameworks/` | (isomer) | the other Apple frameworks SwiftUI's interface names, off Apple: `CoreTransferable`, `UniformTypeIdentifiers`, `PhotosUI`, `OSLog` (`Logger`: logcat on Android, standard error elsewhere; `@isomer//:os_log`, and in each platform's SDK group), `Combine` (since 0.42: Isomer's own, beneath Foundation). Not UIKit or Dispatch (see "Apple's frameworks off Apple") | | `metal/` | (isomer) | Isomer's `Metal` (`//metal/metal`), IsomerMetal (`//metal/isomer_metal`: the MSL→WGSL translator, the backend interface), the web backend (`//metal/web`, `//metal/runtime`) | | `swift_gpu/` | (isomer) | the GPU abstraction (`//swift_gpu/{core,metal,apple,android,wasm,linux,windows}`) | @@ -144,14 +144,19 @@ What building a whole application on the stack taught (a todos app, with a gRPC server over PostgreSQL, was the reference until 0.35, when it moved to a repository of its own): -- **Foundation on wasm/Android** is Isomer's (//foundation, over - swift-foundation; see "Foundation and CoreGraphics" below). Every - SwiftPM package an app links there depends on `@isomer//:foundation` - through `configure_package(target_deps = ...)` in its MODULE.bazel; - `tools/foundation/check_link.py ` finds one that doesn't. +- **Foundation on wasm/Android** is Isomer's, and the Swift SDK's (since + 0.56): Isomer's Swift SDKs (AttilaTheFun/isomer_hermetic_toolchains, + docs/hermetic_toolchains.md) are swift.org's with corelibs Foundation out + and Isomer's family in, so every `import Foundation` there, a package's + included, is Isomer's with no dependency declared. A consumer registers + them by URL (`swift.android_sdk(url = …, sha256 = …)`, + `swift.wasm_sdk(…)`; README, "Isomer's Swift SDKs"): plain, or -i18n for + an app that formats (FoundationInternationalization and ICU). isomer's own + module registers the -i18n SDKs, the examples the plain ones. - **Isomer's Swift is a Swift package (0.43; SwiftUI since 0.44)**: the - root Package.swift beside the Bazel module: Foundation, FoundationNetworking, - IsomerFoundation, CoreGraphics and Combine (0.43), and SwiftUI with what it + root Package.swift beside the Bazel module: CoreGraphics and Combine (0.43; + Linux's and Windows' alone since 0.56, when Foundation, FoundationNetworking + and IsomerFoundation went to the SDKs), and SwiftUI with what it stands on (IsomerSwiftUI, CoreTransferable, UniformTypeIdentifiers, ImageIO, PhotosUI, the SwiftUIMacros macro target; 0.44). rules_swift_package_manager builds it as `@swiftpkg_isomer` in the root's one graph, under its own @@ -161,8 +166,8 @@ a repository of its own): `inject_repo(swift_deps, "isomer")`. isomer's own graph (third_party/swift_packages, dev-only) and the examples' take the package by path (cgrindel/rules_swift_package_manager#2638; with #2639 and #2640 the - registry's 1.25.0.isomer.1). Isomer's labels (`//foundation`, - `//core_graphics`, `//shared/isomer_swift_ui`, each platform's + registry's 1.25.0.isomer.1). Isomer's labels (`//core_graphics`, + `//shared/isomer_swift_ui`, each platform's `libraries/swift_ui:core`, ...) are `one_configuration` wrappers over the package's products. SwiftUI is one target, the same on every platform off Apple: what differs is plugged in, each platform's host (IsomerWebHost, @@ -171,9 +176,7 @@ a repository of its own): which the host defines) and the GPU renderer (IsomerGPURenderer), Bazel modules over it; `:swift_ui` is the group of SwiftUI and the host. What the package can't express comes from the Bazel module through configure_package - `target_deps`: Foundation's internationalization (a marker module Foundation - checks with `canImport`, `--@isomer//foundation:internationalization`), - and the wire protos' Swift (shared/wire): the package generates it as it + `target_deps`: the wire protos' Swift (shared/wire): the package generates it as it builds with swift-protobuf's build plugin (each target's swift-protobuf-config.json), a plugin rules_swift_package_manager doesn't run, so under Bazel swift_proto_library generates it as modules of their @@ -815,7 +818,7 @@ how Isomer runs it. `_runtime(_multithreaded)`), and `SwiftFFILock` is a pthread mutex. A host import called on a guest thread runs on the host's main thread (posted when it answers nothing, waited for when it does). Foundation's - `Thread.isMainThread` there is foundation/wasi_thread_identity's: the + `Thread.isMainThread` there is CWasiThreadIdentity's (the SDK's): the thread that ran the constructors. WasmKit's WASI Threads is process-scoped: a threaded instance is kept for the life of the process (no teardown, no hot reload), and a trap on a guest thread ends the app. @@ -955,15 +958,15 @@ stubs (shared/swift_ui_core/NotYet.swift, generated: the compiler says "Not yet in Isomer: "); implementing one means running it again (or deleting the stub); tools/parity/stubs_skip.txt keeps one out. -- **Foundation** (//foundation, `@isomer//:foundation`): built over - swift-foundation (swift-6.4.2-RELEASE's commit), a dependency of isomer's - Swift package (above; through rules_swift_package_manager since 0.40, - the registry's Bazel module 6.3.2.isomer.2 before), with patches - (MODULE.bazel says which and why). ICU is the Swift SDK's prebuilt one, a - patch to its manifest linking it by name, not swift-foundation-icu built - from source. +- **Foundation** (the Swift SDK's on Android and the web since 0.56; its + sources are isomer_hermetic_toolchains' `Isomer/Sources`, which were + //foundation's until then; docs/hermetic_toolchains.md): built over + swift-foundation (swift-6.4.2-RELEASE, Isomer's patches as commits on + that repository's `isomer-6.4.2` branch) into Isomer's Swift SDKs, plain + and -i18n, by its `sdk/build.sh`. ICU is the Swift SDK's prebuilt one, linked + by name, not swift-foundation-icu built from source. FoundationEssentials, plus what corelibs has that apps reach for, written - in Swift here: CharacterSet, NSString's string API (searching, replacing, + in Swift: CharacterSet, NSString's string API (searching, replacing, trimming, comparing, percent encoding; built in swift-foundation's package, `package_name = "swift-foundation"`, to search with Essentials' own helpers), `String(format:)`, NSRange, NSRegularExpression @@ -984,21 +987,21 @@ deleting the stub); tools/parity/stubs_skip.txt keeps one out. argument domain: `-key value` among the program's arguments, or, where a host starts no program with arguments (Android), in ISO_ARGUMENTS (`am start -e ISO_ARGUMENTS '-reviews.fixture YES'`: the generated - activity sets each ISO_ extra in the environment). `--@isomer//foundation:internationalization` - adds FoundationInternationalization over the Swift SDK's prebuilt ICU + activity sets each ISO_ extra in the environment). The -i18n SDKs' Foundation + re-exports FoundationInternationalization over the Swift SDK's prebuilt ICU (lib_FoundationICU.a); `isomer_web_app(icu_locales = [...])` keeps only - those languages' ICU data (34 MB → 6-7 MB). Linux and Windows still use - the toolchain's corelibs Foundation; servers too. - - Every library that imports Foundation must depend on - `@isomer//:foundation` (SwiftPM packages through `configure_package( - target_deps = ...)`), or it finds the Swift SDK's Foundation, which - then links beside Isomer's (duplicate `Foundation` symbols). - `tools/foundation/check_link.py [] ` names the - leak; give it the flags the targets were built with (it refuses to pass - on autolink files that are not on disk). + those languages' ICU data (34 MB → 6-7 MB). + `--@isomer//foundation:internationalization` built that in when isomer + built Foundation; since 0.56 it checks that the SDK registered is the + -i18n one (foundation/internationalization). Isomer's modules in the SDKs + are built resilient (library evolution), as an Apple SDK's are. Linux and + Windows still use the toolchain's corelibs Foundation; servers too. + - `@isomer//:foundation` and `@isomer//:isomer_foundation` are empty + dependencies since 0.56 (a library needs neither: the SDK's modules are + found and autolinked), kept for the BUILD files that name them. - **FoundationNetworking** (0.39.15): where Isomer's Foundation is the - Foundation (Android, the web), `@isomer//:foundation` brings a module - of that name too (//foundation/networking), which re-exports Isomer's + Foundation (Android, the web), the SDK has a module of that name too, + which re-exports Isomer's Foundation, whose URLSession, URLRequest and URLResponse are those corelibs keeps there. Code written for Linux (`#if canImport(FoundationNetworking) import FoundationNetworking`) then sees @@ -1010,10 +1013,10 @@ deleting the stub); tools/parity/stubs_skip.txt keeps one out. rules_swift_package_manager keeps the LAST configure_package per package and visits the root module first: a dependency's tag beats the root's. - - The `:foundation` aliases are `one_configuration` wrappers - (foundation/defs.bzl): RSPM's per-package minimum-OS transitions would - otherwise build Foundation twice (every Apple platform's option is - cleared: a web site bundled into an iOS app builds under `ios`). + - Isomer's package modules are reached through `one_configuration` + wrappers (foundation/defs.bzl): RSPM's per-package minimum-OS + transitions would otherwise build them twice (every Apple platform's + option is cleared: a web site bundled into an iOS app builds under `ios`). - A module renamed away (SwiftUIExtensions before 0.31) can survive as a stale .swiftmodule in Bazel's output directory, beside the module that replaced it, and shadow it: import the new name and depend on its target. @@ -1093,8 +1096,8 @@ deleting the stub); tools/parity/stubs_skip.txt keeps one out. interface has them, without delegates (foundation/URLSession.swift says where each kind of URL goes). file: and data: URLs are read in Swift; http(s) and ws(s) go through transports a host installs in - **IsomerFoundation** (//foundation/isomer_foundation, - `@isomer//:isomer_foundation`): `IsomerNetwork.http` (an + **IsomerFoundation** (a module of Isomer's Swift SDKs, the toolchains' + `Isomer/Sources/IsomerFoundation`): `IsomerNetwork.http` (an `HTTPTransport`: one exchange, whole bodies, `NetworkTransportError` for no response) and `IsomerNetwork.webSocket` (a `WebSocketTransport` whose connections send text or data and receive diff --git a/BUILD.bazel b/BUILD.bazel index fb35ebd6..2d178219 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -44,38 +44,38 @@ alias( visibility = ["//visibility:public"], ) -# Where `import Foundation` and `import CoreGraphics` come from: Apple's on -# Apple platforms (nothing to link), Isomer's on wasm and Android. A library that -# imports Foundation and is built for a non-Apple platform depends on -# `@isomer//:foundation`, which an application's other libraries (a SwiftPM -# package through rules_swift_package_manager's `target_deps`, a label flag) -# can be pointed at. +# Where `import Foundation` and `import CoreGraphics` come from: the Swift +# SDK's, so nothing to link. Apple's on Apple platforms; Isomer's on Android +# and the web, whose Swift SDKs (Isomer's, since 0.56: README, "Upgrading +# isomer") carry Isomer's Foundation; on Linux and Windows still the +# toolchain's corelibs Foundation (with Isomer's CoreGraphics beside it, +# :core_graphics). No library needs to depend on this any more: it stays, an +# empty dependency, for the BUILD files and `target_deps` that name it, and +# on Android and the web it carries the check that +# --@isomer//foundation:internationalization's SDK is the -i18n one +# (foundation/BUILD.bazel). alias( name = "foundation", actual = select({ # A compiled feature (apple/compiled): Apple's Foundation with # Isomer's Observation and Synchronization. "//apple/compiled:feature_on": "//apple/libraries/compiled_swift_ui:foundation", - "@platforms//os:wasi": "//foundation:for_dependents", - "@platforms//os:android": "//foundation:for_dependents", - # Apple's frameworks; on Linux and Windows still the toolchain's - # Foundation (with Isomer's CoreGraphics beside it, :core_graphics). + "@platforms//os:wasi": "//foundation:from_sdk", + "@platforms//os:android": "//foundation:from_sdk", "//conditions:default": ":system_framework", }), visibility = ["//visibility:public"], ) # What a host installs beneath Isomer's Foundation (URLSession's transports, -# UserDefaults' store): IsomerFoundation, on the platforms with Isomer's -# Foundation; nothing on Apple platforms, where it has no place (code that -# builds for both guards with `#if canImport(IsomerFoundation)`). +# UserDefaults' store): IsomerFoundation, a module of Isomer's Swift SDKs on +# Android and the web (since 0.56), so nothing to link; nothing on other +# platforms, where it has no place (code that builds for both guards with +# `#if canImport(IsomerFoundation)`). An empty dependency, for the BUILD +# files that name it. alias( name = "isomer_foundation", - actual = select({ - "@platforms//os:wasi": "//foundation/isomer_foundation:for_dependents", - "@platforms//os:android": "//foundation/isomer_foundation:for_dependents", - "//conditions:default": ":system_framework", - }), + actual = ":system_framework", visibility = ["//visibility:public"], ) @@ -99,9 +99,10 @@ alias( alias( name = "core_graphics", actual = select({ - "@platforms//os:wasi": "//core_graphics:for_dependents", - "@platforms//os:android": "//core_graphics:for_dependents", - # Beside the toolchain's Foundation there: what it lacks + # Apple's on Apple platforms, the Swift SDK's on Android and the web + # (Isomer's SDKs carry Isomer's CoreGraphics): nothing to link. On + # Linux and Windows Isomer's, built here, beside the toolchain's + # Foundation there: what it lacks # (CGAffineTransform, CGPath, CGColor...; core_graphics/BUILD.bazel). "@platforms//os:linux": "//core_graphics:for_dependents", "@platforms//os:windows": "//core_graphics:for_dependents", diff --git a/MODULE.bazel b/MODULE.bazel index 6fa14630..edcff331 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -40,8 +40,8 @@ bazel_dep(name = "platforms", version = "1.1.0") # Apple platform (uses the locally installed Xcode, as all Bazel apple builds do). # rules_swift from this project's registry (AttilaTheFun/bazel_registry, -# listed before the BCR in .bazelrc): 4.2.2.isomer.3 is upstream's 4.2.2 with -# six rules_swift pull requests until a release has them, each a patch in +# listed before the BCR in .bazelrc): 4.2.2.isomer.4 is upstream's 4.2.2 with +# seven rules_swift pull requests until a release has them, each a patch in # the registry entry, taken from the PR's head: # * #1989 (merged after 4.2.2): C compiled for wasm gets the Swift SDK's # clang resource directory, so and come from the @@ -56,12 +56,15 @@ bazel_dep(name = "platforms", version = "1.1.0") # beside the shared runtime, -lc++ the static libc++). # * #1985 (merged after 4.2.2): swift.org's release metadata through 6.4.2; # * #2000: Android targets down to the Swift SDK's own minimum (6.4's: API -# 23), without RELR relocations below 28. +# 23), without RELR relocations below 28; +# * #2012: `swift.android_sdk(url = …, sha256 = …)`, an Android Swift SDK +# from any URL, as #1860 gives `swift.wasm_sdk`: how a consumer registers +# Isomer's Swift SDKs (README, "Upgrading isomer"). # It sorts above the 4.2.2 rules_applecross asks for, so no override holds -# it, here or in a consumer. A change is a new entry (4.2.2.isomer.4) made +# it, here or in a consumer. A change is a new entry (4.2.2.isomer.5) made # with the registry's tools/add_version.py --fork; back to a plain BCR # version at the release that has them all. -bazel_dep(name = "rules_swift", version = "4.2.2.isomer.3") +bazel_dep(name = "rules_swift", version = "4.2.2.isomer.4") # rules_apple and apple_support at rules_applecross's versions, from this # project's registry: rules_apple 5.3.1.applecross.6 is rules_apple 5.3.1 # with rules_applecross's patches (bundling and signing on Linux), asking @@ -94,87 +97,60 @@ bazel_dep(name = "hermetic_android_toolchains", version = "0.5.0.isomer.1") # reactor + TypeScript bindings. # The macro plugins (swift_ffi's, SwiftUI's) and the source analyzer use -# swift-syntax from the SwiftPM graph (use_repo below): the one release/6.4.x -# swift-foundation takes, matching the toolchain. +# swift-syntax from the SwiftPM graph (use_repo below): release/6.4.x, as +# swift-foundation takes it, matching the toolchain. -# --- Isomer's Swift package (Foundation and the frameworks off Apple) ------- +# --- Isomer's Swift package (the frameworks off Apple) ---------------------- # Isomer's Swift libraries are a Swift package too (Package.swift, at the -# root): Foundation, CoreGraphics, Combine and what they stand on. -# rules_swift_package_manager builds them from it, as @swiftpkg_isomer, in -# the application's one SwiftPM graph: an application lists isomer in its -# Package.swift (by revision: the release's tag or a commit) beside its -# bazel_dep here, so swift-foundation and swift-collections resolve once, -# for its packages and Isomer's alike. This module's own graph, used when it -# is the root (third_party/swift_packages), takes the package by path. +# root): SwiftUI, the frameworks beneath it and, for Linux and Windows, +# CoreGraphics and Combine. rules_swift_package_manager builds them from it, +# as @swiftpkg_isomer, in the application's one SwiftPM graph: an +# application lists isomer in its Package.swift (by revision: the release's +# tag or a commit) beside its bazel_dep here, so the packages they share +# (SwiftProtobuf, swift-syntax) resolve once, for its packages and Isomer's +# alike. This module's own graph, used when it is the root +# (third_party/swift_packages), takes the package by path. # -# Isomer's Foundation is built over swift-foundation's FoundationEssentials -# (and FoundationInternationalization when an app asks for it, -# //foundation:internationalization), adding what corelibs gives Swift code -# elsewhere (CharacterSet, NSString's string API, String(format:) and the -# rest of foundation/). Apple platforms use Apple's Foundation. -# -# swift-foundation's patches: swift-foundation#2409 (merged upstream; in its -# next release), Android's fts_open (the Android SDK's apinotes would make it -# unneeded, but rules_swift compiles with the static resource directory, -# which has none), Apple's signatures where swift-foundation's differ and its -# extra declarations made internal, and `package` on the Essentials helpers -# Foundation searches strings with (it is built in swift-foundation's package -# for that). +# Foundation isn't built here (since 0.56): off Apple it is the Swift SDK's. +# Isomer's Swift SDKs for Android and the web carry Isomer's Foundation (over +# swift-foundation's FoundationEssentials, with what corelibs gives Swift code +# elsewhere: CharacterSet, NSString's string API, String(format:), URLSession +# over the host's transports), FoundationNetworking, IsomerFoundation, +# CoreGraphics and Combine, in place of corelibs' (AttilaTheFun/isomer_hermetic_toolchains, +# docs/hermetic_toolchains.md); so every `import Foundation` there, a +# package's or a module's, is Isomer's with no dependency declared. Linux and +# Windows keep the toolchain's corelibs Foundation. # # The registry's 1.25.0.isomer.1: upstream 1.25.0 with three pull requests to # cgrindel/rules_swift_package_manager, until a release has them (MVS gives # it to every consumer): #2638 # (a local package that is a Bazel module too, isomer's taken by path in its # own graph, is copied without its Bazel files), #2639 (no Apple minimum OS -# versions off Apple: isomer declares iOS 16 and macOS 13 over -# swift-foundation's 26) and #2640 (a Swift target's cSettings defines reach -# its Clang importer, as SwiftPM passes them: swift-foundation's WASI -# emulation macros). +# versions off Apple: isomer declares iOS 16 and macOS 13, and a package +# beneath it may declare more) and #2640 (a Swift target's cSettings defines +# reach its Clang importer, as SwiftPM passes them). bazel_dep(name = "rules_swift_package_manager", version = "1.25.0.isomer.1") # rules_swift_package_manager's own extension, so an application's graph and -# this module's packages are one: what isomer declares here (its patches, a -# dependency of its Foundation) applies to the application's graph, and the -# repositories isomer uses are that graph's. Its graph is declared only when -# it is the root (dev_dependency, below): every module's from_package is -# resolved, and two graphs would declare the same repositories. +# this module's packages are one: what isomer declares here applies to the +# application's graph, and the repositories isomer uses are that graph's. Its +# graph is declared only when it is the root (dev_dependency, below): every +# module's from_package is resolved, and two graphs would declare the same +# repositories. swift_deps = use_extension("@rules_swift_package_manager//:extensions.bzl", "swift_deps") -swift_deps.configure_package( - name = "swift-foundation", - patch_args = ["-p1"], - patches = [ - "//tools/patches:swift_foundation_create_directory_root.patch", - "//tools/patches:swift_foundation_apple_interface.patch", - "//tools/patches:swift_foundation_package_helpers.patch", - "//tools/patches:swift_foundation_sdk_icu.patch", - ], -) -# FoundationInternationalization, re-exported by Foundation when the build -# asks for it (`--@isomer//foundation:internationalization`, which no -# SwiftPM condition can express): a module Foundation can import, or -# nothing (foundation/internationalization). The generated repositories see -# @isomer by the application's inject_repo (README: "Consuming isomer"). +# The wire protos' Swift, which the package generates with swift-protobuf's +# build plugin, a plugin rules_swift_package_manager doesn't run: +# swift_proto_library's modules, which IsomerSwiftUI and IsomerWire re-export +# (//shared/wire). The generated repositories see @isomer by the +# application's inject_repo (README: "Consuming isomer"). swift_deps.configure_package( name = "isomer", - # And the wire protos' Swift, which the package generates with - # swift-protobuf's build plugin, a plugin rules_swift_package_manager - # doesn't run: swift_proto_library's modules, which IsomerSwiftUI and - # IsomerWire re-export (//shared/wire). target_deps = { - "Foundation": ["@isomer//foundation/internationalization"], "IsomerSwiftUI": ["@isomer//shared/wire:tree_messages"], "IsomerWire": ["@isomer//shared/wire:wire_messages"], }, ) -# SwiftProtobuf (the render tree's wire format, shared/wire/tree.proto): -# where Isomer's Foundation is the Foundation (the web, Android), its -# `import Foundation` is Isomer's, as every package an application links -# there (README). -swift_deps.configure_package( - name = "swift-protobuf", - target_deps = {"SwiftProtobuf": ["@isomer//foundation:for_swift_packages"]}, -) # gRPC Swift 2 and SwiftNIO (driving an app: drive/): in every application's # graph, as isomer's package depends on them; built only where an app is # served or driven from (a Mac, Linux), never for the web or Android. @@ -183,7 +159,6 @@ use_repo( "swiftpkg_grpc_swift_2", "swiftpkg_grpc_swift_nio_transport", "swiftpkg_isomer", - "swiftpkg_swift_foundation", "swiftpkg_swift_nio", "swiftpkg_swift_protobuf", "swiftpkg_swift_syntax", @@ -440,12 +415,24 @@ swift.toolchain( name = "swift_toolchain", swift_version = "6.4.2", ) -swift.wasm_sdk() +# Isomer's Swift SDKs (since 0.56): swift.org's 6.4.2 SDKs with corelibs +# Foundation taken out and Isomer's put in (AttilaTheFun/isomer_hermetic_toolchains, +# docs/hermetic_toolchains.md). isomer's own builds take the -i18n ones, +# whose Foundation has FoundationInternationalization and ICU, so Foundation's +# tests (foundation/tests) cover it; the examples take the plain ones, as +# most applications do (README, "Upgrading isomer"). +swift.wasm_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm-i18n.artifactbundle.tar.gz", + sha256 = "d787225d4cb19003b6674272bb4643153aab751016d9f14c064ba58981e68f38", +) # No wasi-threads SDK beside it since 0.41: Isomer's was a build of # Swift 6.3.2 with swiftlang/swift#92018, which reaches a release in 6.5; # reactors built for `@isomer//swift_ffi/rules:wasm32-wasip1-threads` wait # for it (TODO.md). -swift.android_sdk() +swift.android_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android-i18n.artifactbundle.tar.gz", + sha256 = "4a726a303e53529ba2d8f6c97f735ce6b880313740efc53065028a460aee0296", +) use_repo( swift, # Aggregator repo: holds the registered toolchains and a host-independent diff --git a/Package.swift b/Package.swift index 1c4bb1ee..ac5f38c8 100644 --- a/Package.swift +++ b/Package.swift @@ -1,20 +1,24 @@ // swift-tools-version:6.0 // Isomer's Swift libraries as a Swift package, beside its Bazel module: an // application lists isomer in its own Package.swift, and -// rules_swift_package_manager resolves Isomer's Swift (and swift-foundation, -// swift-collections and the rest) in the application's one graph. The Bazel +// rules_swift_package_manager resolves Isomer's Swift (and SwiftProtobuf, +// swift-syntax and the rest) in the application's one graph. The Bazel // module keeps what isn't Swift libraries: the application macros, the // platform hosts and runtimes, swift_ffi's generators, the toolchains. // // Pinned by revision, the release's tag or a commit // (`.package(url: "https://github.com/AttilaTheFun/isomer.git", revision: "v0.43.1")`): -// swift-foundation has no semantic versions and takes its own dependencies by -// branch, which SwiftPM allows only beneath a revision pin. +// swift-syntax is taken by branch, as swift-foundation takes it, which +// SwiftPM allows only beneath a revision pin. // -// The Apple-named modules are Isomer's off Apple only: on Apple platforms an -// application uses Apple's, so its targets depend on these with -// `.when(platforms: [.android, .wasi])` (Foundation) or the platforms that -// lack Apple's frameworks (CoreGraphics, Combine). +// Foundation is the Swift SDK's on every platform (since 0.56): on Android +// and the web Isomer's Swift SDKs carry Isomer's Foundation, FoundationNetworking, +// IsomerFoundation, CoreGraphics and Combine (AttilaTheFun/isomer_hermetic_toolchains; +// docs/hermetic_toolchains.md), so no target here depends on a Foundation +// and `import Foundation` anywhere is the SDK's. Linux and Windows keep the +// toolchain's corelibs Foundation, with Isomer's CoreGraphics and Combine +// from here beside it, until their SDKs carry Isomer's too. On Apple +// platforms an application uses Apple's frameworks. import CompilerPluginSupport import PackageDescription @@ -22,16 +26,19 @@ import PackageDescription // stand in. let offApple: [Platform] = [.android, .wasi, .linux, .windows] +// Where the Swift SDK's Foundation is corelibs', which has no CoreGraphics +// or Combine: Isomer's are built here. (On Android and the web Isomer's +// Swift SDKs carry them.) +let corelibsFoundation: [Platform] = [.linux, .windows] + let package = Package( name: "isomer", // Where Isomer's own modules build on Apple platforms (an app compiled - // against Isomer's frameworks: iOS 16). Foundation and the frameworks - // build only off Apple, where swift-foundation's 26 means nothing. + // against Isomer's frameworks: iOS 16). The frameworks build only off + // Apple. platforms: [.macOS("13"), .iOS("16")], products: [ - .library(name: "Foundation", targets: ["Foundation"]), - .library(name: "FoundationNetworking", targets: ["FoundationNetworking"]), - .library(name: "IsomerFoundation", targets: ["IsomerFoundation"]), + // Linux's and Windows' (the Swift SDKs carry them elsewhere). .library(name: "CoreGraphics", targets: ["CoreGraphics"]), .library(name: "Combine", targets: ["Combine"]), .library(name: "IsomerSwiftUI", targets: ["IsomerSwiftUI"]), @@ -53,12 +60,10 @@ let package = Package( .executable(name: "iso", targets: ["iso"]), ], dependencies: [ - // swift-6.4.2-RELEASE's commit: the swift-foundation the Swift SDKs' - // Foundation is built from. - .package(url: "https://github.com/swiftlang/swift-foundation.git", revision: "e4049b2d77e2d5d70c4cfcc99fd5eca32e1bcb06"), // tag: swift-6.4.2-RELEASE // SwiftUI's macros (@State, @Entry): swift-syntax as swift-foundation - // takes it, by its branch (SwiftPM reconciles no other requirement on - // it); the commit is Package.resolved's. + // takes it, by its branch, so an application whose graph has + // swift-foundation too resolves one (SwiftPM reconciles no other + // requirement on it); the commit is Package.resolved's. .package(url: "https://github.com/swiftlang/swift-syntax", branch: "release/6.4.x"), // as swift-foundation // The render tree's wire format (shared/wire/tree.proto). .package(url: "https://github.com/apple/swift-protobuf.git", from: "1.38.1"), @@ -72,6 +77,11 @@ let package = Package( .package(url: "https://github.com/apple/swift-nio.git", from: "2.81.0"), ], targets: [ + // Isomer's CoreGraphics and Combine beside Linux's and Windows' + // corelibs Foundation. The copies Isomer's Swift SDKs carry for + // Android and the web are isomer_hermetic_toolchains' (Isomer/Sources): + // a change here goes there too, until those platforms' SDKs carry + // them as well. .target( name: "CoreGraphics", path: "core_graphics", @@ -79,7 +89,7 @@ let package = Package( swiftSettings: [ // The toolchain's corelibs Foundation declares CGFloat and the // geometry types there (AGENTS.md). - .define("ISOMER_CORELIBS_FOUNDATION", .when(platforms: [.linux, .windows])), + .define("ISOMER_CORELIBS_FOUNDATION", .when(platforms: corelibsFoundation)), ] ), .target( @@ -87,46 +97,6 @@ let package = Package( path: "frameworks/combine", exclude: ["BUILD.bazel", "tests"] ), - .target( - name: "IsomerFoundation", - dependencies: [.product(name: "FoundationEssentials", package: "swift-foundation")], - path: "foundation/isomer_foundation", - exclude: ["BUILD.bazel"], - swiftSettings: [.swiftLanguageMode(.v6), .enableUpcomingFeature("ExistentialAny")] - ), - .target( - name: "IsomerDispatchTime", - path: "foundation/dispatch_time" - ), - .target( - name: "CWasiThreadIdentity", - path: "foundation/wasi_thread_identity", - publicHeadersPath: "." - ), - .target( - name: "Foundation", - dependencies: [ - "Combine", - "CoreGraphics", - "IsomerFoundation", - .product(name: "FoundationEssentials", package: "swift-foundation"), - .target(name: "IsomerDispatchTime", condition: .when(platforms: [.android, .wasi])), - .target(name: "CWasiThreadIdentity", condition: .when(platforms: [.wasi])), - ], - path: "foundation", - exclude: ["BUILD.bazel", "defs.bzl", "dispatch_time", "internationalization", "isomer_foundation", "networking", "tests", "wasi_thread_identity"], - swiftSettings: [ - // Built in swift-foundation's package, as the Bazel target is: - // its string API searches with Essentials' `package` helpers. - .unsafeFlags(["-package-name", "swift-foundation"]), - ] - ), - .target( - name: "FoundationNetworking", - dependencies: ["Foundation"], - path: "foundation/networking", - exclude: ["BUILD.bazel"] - ), // The modules SwiftUI stands on, off Apple: what Isomer's SwiftUI // reads of its host and runtime (IsomerSwiftUI: the render tree's wire // format, shared/wire/tree.proto, generated as it builds), CoreTransferable, @@ -135,7 +105,6 @@ let package = Package( name: "IsomerSwiftUI", dependencies: [ .product(name: "SwiftProtobuf", package: "swift-protobuf"), - .target(name: "Foundation", condition: .when(platforms: [.android, .wasi])), ], path: "shared/isomer_swift_ui", exclude: ["BUILD.bazel"], @@ -145,19 +114,16 @@ let package = Package( ), .target( name: "CoreTransferable", - dependencies: [.target(name: "Foundation", condition: .when(platforms: [.android, .wasi]))], path: "frameworks/core_transferable", exclude: ["BUILD.bazel"] ), .target( name: "UniformTypeIdentifiers", - dependencies: [.target(name: "Foundation", condition: .when(platforms: [.android, .wasi]))], path: "frameworks/uniform_type_identifiers", exclude: ["BUILD.bazel"] ), .target( name: "ImageIO", - dependencies: [.target(name: "Foundation", condition: .when(platforms: [.android, .wasi]))], path: "shared/image_io", exclude: ["BUILD.bazel"] ), @@ -187,10 +153,9 @@ let package = Package( // and terminal hosts): Isomer's elsewhere. .target(name: "CoreTransferable", condition: .when(platforms: offApple)), .target(name: "UniformTypeIdentifiers", condition: .when(platforms: offApple)), - .target(name: "Foundation", condition: .when(platforms: [.android, .wasi])), .target(name: "ImageIO", condition: .when(platforms: offApple)), - .target(name: "CoreGraphics", condition: .when(platforms: [.linux, .windows])), - .target(name: "Combine", condition: .when(platforms: [.linux, .windows])), + .target(name: "CoreGraphics", condition: .when(platforms: corelibsFoundation)), + .target(name: "Combine", condition: .when(platforms: corelibsFoundation)), ], path: "shared", exclude: ["swift_ui_core/BUILD.bazel"], @@ -201,8 +166,9 @@ let package = Package( "renderers/TreeDecoder.swift", "renderers/TreeEncoder.swift", // Linux's and Windows' Foundation (the toolchain's) has no - // FileWrapper, which FileDocument hands over: Isomer's - // Foundation's, compiled into SwiftUI there (the file says when). + // FileWrapper, which FileDocument hands over: compiled into + // SwiftUI there (the file says when). Isomer's Foundation, the + // SDK's on Android and the web, has its own. "swift_ui_corelibs", ], swiftSettings: [ @@ -262,7 +228,6 @@ let package = Package( name: "IsomerWire", dependencies: [ .product(name: "SwiftProtobuf", package: "swift-protobuf"), - .target(name: "Foundation", condition: .when(platforms: [.android, .wasi])), ], path: "shared/wire/swift", exclude: ["BUILD.bazel"], @@ -275,7 +240,6 @@ let package = Package( dependencies: [ "IsomerWire", .product(name: "SwiftProtobuf", package: "swift-protobuf"), - .target(name: "Foundation", condition: .when(platforms: [.android, .wasi])), ], path: "drive/serving", exclude: ["BUILD.bazel"] @@ -341,6 +305,6 @@ let package = Package( ), ], // Swift 5 language mode, as isomer's Bazel targets build (those that - // opt into 6 say so: IsomerFoundation). + // opt into 6 say so). swiftLanguageModes: [.v5] ) diff --git a/README.md b/README.md index 80758560..d9c390f3 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ It is a set of pieces, and none of them requires the others: | SQLite everywhere | SQLite's C API and a thin, strict-concurrency-safe Swift layer over it, the same SQLite on every platform (WebAssembly included) | [swift_sql](https://github.com/AttilaTheFun/swift_sql) | | Swift on every platform | Cross-compilation to WebAssembly, Android and Windows in Bazel | [rules_swift](https://github.com/bazelbuild/rules_swift) (upstream) | | Bridges to each platform's own language | Generated Kotlin, TypeScript and C bindings | [`swift_ffi/`](swift_ffi/) | -| Apple's frameworks off Apple | `Foundation`, `CoreGraphics` and `Metal` with Apple's interfaces, written in Swift, for the web and Android (Metal: the web, on WebGPU, with Metal Shading Language translated to WGSL) | [`foundation/`](foundation/), [`core_graphics/`](core_graphics/), [`metal/`](metal/), [docs/parity](docs/parity/) | +| Apple's frameworks off Apple | `Foundation`, `CoreGraphics` and `Metal` with Apple's interfaces, written in Swift, for the web and Android (Foundation in Isomer's Swift SDKs; Metal: the web, on WebGPU, with Metal Shading Language translated to WGSL) | [isomer_hermetic_toolchains](https://github.com/AttilaTheFun/isomer_hermetic_toolchains), [`core_graphics/`](core_graphics/), [`metal/`](metal/), [docs/parity](docs/parity/) | | Graphics and maps | One GPU abstraction (Metal, WebGPU, OpenGL, Direct3D); an OpenStreetMap renderer on it | [`swift_gpu/`](swift_gpu/), [`swift_map/`](swift_map/) | Why Swift: it rules out whole kinds of bugs when the program is compiled @@ -107,27 +107,27 @@ Isomer: an iOS app, a web site and an Android app) is in `examples/playground/`, until then. **Foundation and CoreGraphics.** On wasm and Android, `import Foundation` -is Isomer's: swift-foundation's FoundationEssentials, a Swift package at its -swift-6.4.2-RELEASE with a few patches (MODULE.bazel lists them), with no +is Isomer's, and it comes with the Swift SDK (since 0.56): Isomer's Swift +SDKs ([AttilaTheFun/isomer_hermetic_toolchains](https://github.com/AttilaTheFun/isomer_hermetic_toolchains), +[docs/hermetic_toolchains.md](docs/hermetic_toolchains.md)) are swift.org's +with corelibs Foundation taken out and Isomer's put in, so every `import +Foundation` built with them, your code's, a Swift package's or a Bazel +module's, is Isomer's with no dependency declared. It is swift-foundation's +FoundationEssentials at swift-6.4.2-RELEASE with a few patches, with no swift-corelibs-foundation layer (no CoreFoundation; of what corelibs gives Swift code only what apps reach for, written in Swift: `CharacterSet`, `NSString`'s string API, `String(format:)`, `NSRange`, `NSRegularExpression`, the locks, `Thread`, `FileHandle`, -`NSNumber`) and no ICU unless an app asks for -`--@isomer//foundation:internationalization` (FoundationInternationalization -over the Swift SDK's ICU; `isomer_web_app(icu_locales = ["en"])` trims its -data to the languages named). `import CoreGraphics` is -Isomer's too (`//core_graphics`): geometry, `CGFloat` (a `Double` on every -architecture), `CGAffineTransform`, `CGColor`, `CGPath`. `SwiftUI` re-exports -both, as Apple's does. Any library built for those platforms that imports -Foundation depends on `@isomer//:foundation` (a SwiftPM package through -rules_swift_package_manager's `target_deps`); `tools/foundation/check_link.py` -finds an app that links the Swift SDK's Foundation instead. A library that -depends on `@isomer//:swift_ui` has Foundation through it already (SwiftUI -re-exports it), so it needs no `@isomer//:foundation` of its own; a macro of -yours that adds `@isomer//:foundation` to a target's `deps` must not be given -it again, as Bazel rejects a label listed twice in one attribute. Linux and -Windows still use the toolchain's Foundation. docs/isomer_031_plan.md has the -plan and docs/parity/ what each module covers. +`NSNumber`), and no ICU in the plain SDKs: an app that formats dates, +numbers or lists registers the -i18n ones, whose Foundation has +FoundationInternationalization over the SDK's ICU +(`isomer_web_app(icu_locales = ["en"])` trims its data to the languages +named). `import CoreGraphics` and `import Combine` are Isomer's too, from the +same SDKs: geometry, `CGFloat` (a `Double` on every architecture), +`CGAffineTransform`, `CGColor`, `CGPath`. `SwiftUI` re-exports Foundation +and CoreGraphics, as Apple's does. Linux and Windows still use the +toolchain's corelibs Foundation, with Isomer's CoreGraphics and Combine +(`//core_graphics`, `//frameworks/combine`) beside it. docs/isomer_031_plan.md +has the plan and docs/parity/ what each module covers. **Metal.** On the web, `import Metal` is Isomer's (`//metal/metal`): the classic Metal API, with libraries made from Metal Shading Language source, @@ -721,23 +721,22 @@ fails saying which to do. rules_android's own Maven (its tools) is rules_android's to declare; docs/android_maven.md shows how to pin it with isomer's lock file, as the examples do. -Isomer's Swift libraries are a Swift package too (since 0.43: Foundation, -CoreGraphics, Combine and what they stand on, from isomer's root -Package.swift), built through rules_swift_package_manager in your own -SwiftPM graph, so swift-foundation and swift-collections resolve once for -your packages and Isomer's. List isomer in the Package.swift your graph -reads, at the same release, by its tag (or a commit between releases; -swift-foundation takes its own dependencies by branch, which SwiftPM allows -only beneath a revision pin): +Isomer's Swift libraries are a Swift package too (since 0.43: SwiftUI and +the frameworks it stands on, from isomer's root Package.swift), built +through rules_swift_package_manager in your own SwiftPM graph, so +SwiftProtobuf and swift-syntax resolve once for your packages and Isomer's. +List isomer in the Package.swift your graph reads, at the same release, by +its tag (or a commit between releases; isomer takes swift-syntax by branch, +which SwiftPM allows only beneath a revision pin): ```swift .package(url: "https://github.com/AttilaTheFun/isomer.git", revision: "v0.43.1"), ``` use rules_swift_package_manager's own `swift_deps` extension (not a -re-export of your own: isomer adds its patches and a dependency of its -Foundation to it), and let the generated package repositories see -`@isomer`, which those additions name: +re-export of your own: isomer adds its wire protos' modules to it), and let +the generated package repositories see `@isomer`, which those additions +name: ```starlark swift_deps = use_extension("@rules_swift_package_manager//:extensions.bzl", "swift_deps") @@ -748,9 +747,6 @@ swift_deps.from_package( inject_repo(swift_deps, "isomer") ``` -swift-foundation pins swift-collections exactly (1.1.6 at Swift 6.4.2), so -your graph takes that version. - **Only the root module's take effect.** `inject_repo` and `override_repo` are ignored in any module that is not the root (as dev dependencies are), and so are the `dev_dependency = True` extension tags and registrations the @@ -789,10 +785,10 @@ The isomer the root depends on and the one its Package.swift lists are the module's release: one isomer in the build. Nothing of isomer's needs an override in your MODULE.bazel since 0.40 (its -rules_swift, 4.2.2.isomer.3, sorts above the version rules_applecross asks +rules_swift, 4.2.2.isomer.4, sorts above the version rules_applecross asks for); you still register the toolchains, and only those of the platforms you build: an app for iOS, the Mac and Android declares the host toolchain -and `swift.android_sdk()` and registers the Android Swift toolchains, with +and Isomer's Android SDK (below) and registers the Android Swift toolchains, with no wasm SDK, wasm toolchains, Windows SDK or rules_swift_package_manager Windows patch (0.40: isomer's targets for those platforms are only analyzed when built). That is the whole list: the bridge generator, the GPU layer and the map @@ -803,6 +799,52 @@ your rules_swift_package_manager graph reads) left this module at 0.34; the examples use it. C compiled for wasm, swift_sql's included, needs rules_swift#1989, which the registry's rules_swift carries. +**Isomer's Swift SDKs.** On Android and the web Foundation is the Swift +SDK's, so an app registers Isomer's SDKs (since 0.56) in the `swift` block +it already has, in place of `swift.android_sdk()` and `swift.wasm_sdk()`. +One snippet a platform, each standing alone: an app that builds for +Android alone takes the first and registers no wasm SDK. + +If you build for Android: + +```starlark +swift.android_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android.artifactbundle.tar.gz", + sha256 = "1fce2fe24ec9b7c54f97fe2aff41ceab01b5acbc5a09492c50cc918e1dbcdbac", +) +``` + +If you build for the web: + +```starlark +swift.wasm_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm.artifactbundle.tar.gz", + sha256 = "d63e3f15297575b634dcc07b36e19111fb3a24b7dbac0e9b217d3c3532b3bb11", +) +``` + +If your app formats dates, numbers or lists with Foundation (`formatted()`, +`Date.FormatStyle`, locales and calendars beyond English and the Gregorian), +take the -i18n SDK instead, whose Foundation has FoundationInternationalization +and ICU (tens of megabytes of data, which `icu_locales` trims on the web): + +```starlark +# Android, formatting: +swift.android_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android-i18n.artifactbundle.tar.gz", + sha256 = "4a726a303e53529ba2d8f6c97f735ce6b880313740efc53065028a460aee0296", +) +# The web, formatting: +swift.wasm_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm-i18n.artifactbundle.tar.gz", + sha256 = "d787225d4cb19003b6674272bb4643153aab751016d9f14c064ba58981e68f38", +) +``` + +The SDKs move on their own cadence (isomer_hermetic_toolchains' releases, +whose notes carry these lines); each is the Swift release isomer's toolchain +is (6.4.2), which `swift.toolchain`'s `swift_version` must match. + **Protocol buffers.** Isomer's wire protos are compiled as you build (`swift_proto_library`, shared/wire), against your graph's SwiftProtobuf (the swift-protobuf package your Package.swift resolves). Isomer asks for @@ -852,6 +894,31 @@ build --strategy=CppArchive=local Each release's notes have an Upgrading section; these things are easy to miss: +- **Foundation is the Swift SDK's on Android and the web (since 0.56).** + - Register Isomer's Swift SDKs ("Isomer's Swift SDKs" above): replace + `swift.android_sdk()` and `swift.wasm_sdk()` with the snippet of each + platform you build for, the plain URL, or the -i18n one if the app + formats dates or numbers. Without them `import Foundation` there is + swift.org's corelibs Foundation again, and links fail. + - Drop Foundation's edges: the `configure_package(target_deps = …)` + entries that gave a package `@isomer//:foundation`, and the + `@isomer//:foundation` and `@isomer//:isomer_foundation` in your + BUILD files' deps. Both labels stay, empty, so nothing breaks if you + leave them; `@isomer//foundation:for_swift_packages` and the + `@swiftpkg_isomer//:Foundation`, `:FoundationNetworking` and + `:IsomerFoundation` products are gone. + - `--@isomer//foundation:internationalization` no longer builds + FoundationInternationalization into Foundation: the -i18n SDK is what + has it. The setting stays, and on Android and the web it checks that + the SDK registered is the -i18n one (a build that sets it with the + plain SDK fails, saying which to register); keep it if your app sets + it, or drop it with the -i18n SDK in place. + - rules_swift is the registry's 4.2.2.isomer.4 (its + `swift.android_sdk(url = …)`); your own override of rules_swift, if you + kept one, has to be that version. + - `tools/foundation/check_link.py` is gone: there is one Foundation to + link. + - **Isomer's AndroidX is a module of its own (since 0.54).** isomer no longer declares any Maven for its consumers (docs/android_maven.md): - an app that used Isomer's AndroidX (left @@ -948,8 +1015,7 @@ Each release's notes have an Upgrading section; these things are easy to miss: isomer's own REPO.bazel turns the common ones off for its packages (a repository's `-feature` wins over the command line's), so its modules build as they are tested whatever you set; it can't do so for its - dependencies (swift-foundation's collections fail under Swift 6's strict - concurrency, its FoundationEssentials under warnings-as-errors) or yours. + dependencies or yours. - **Java 17 for Android's tools.** `--java_language_version=17` and `--tool_java_language_version=17` (with the remote JDK 17 runtimes, examples/.bazelrc's four lines): rules_android's dexer is Java with @@ -1366,8 +1432,11 @@ bazel test --@isomer//headless //headless/... //remote/... ``` swift_ffi/ Swift <-> Kotlin/TypeScript/C bindings: macros, analyzer, generator, Bazel rules, runtimes (and its own examples) -core_graphics/ Isomer's CoreGraphics (wasm, Android) -foundation/ Isomer's Foundation, over swift-foundation's Essentials +core_graphics/ Isomer's CoreGraphics (Linux, Windows; the Swift SDKs' + on wasm and Android) +foundation/ Foundation's build settings and tests (Isomer's + Foundation is in Isomer's Swift SDKs: + AttilaTheFun/isomer_hermetic_toolchains) metal/ Isomer's Metal: the API, the MSL→WGSL translator, the WebGPU backend and its JS executor swift_gpu/ the GPU abstraction: Metal (Apple's and Isomer's), diff --git a/TODO.md b/TODO.md index fce9f6e2..767de6c0 100644 --- a/TODO.md +++ b/TODO.md @@ -370,16 +370,24 @@ each to an Isomer version and a Swift toolchain, and the examples' modules do, everywhere); and its frame cost was measured only on the Storybook on an emulator, where Swift spends about 2 ms a frame: an app heavier in Swift, on a phone, may show what the Storybook couldn't. -- **Foundation for every Swift target on Android without wrappers**: a - `swift_library` that imports Foundation without depending on - `@isomer//:foundation` finds the SDK's corelibs Foundation, and links - two. rules_swift's non-Apple toolchains have no implicit dependencies, so - this is a rules_swift change (upstream): the Android toolchain taking - implicit deps from a label flag, which `@isomer//:foundation`'s own - `one_configuration` wrapper turns off for Foundation's build (else it - depends on itself). Until then, consumers wrap `swift_library` or patch - third-party BUILD files, and `tools/foundation/check_link.py` finds a - leak. +- **Foundation for every Swift target on Android without wrappers**: done + in 0.56 by Isomer's Swift SDKs (docs/hermetic_toolchains.md): the SDK's + Foundation is Isomer's, so a `swift_library` or a package that imports + Foundation links Isomer's with no dependency. Open there: + - Linux and Windows SDKs with Isomer's Foundation (their hosts and + Foundation tests move off corelibs), then the one-line toolchains + module (Apple's SDKs through rules_applecross beside them); + - swift-collections' modules are in the SDK under their own names + (DequeModule, OrderedCollections...): an app that builds + swift-collections itself sees two (private names in the SDK, as + swift.org's `_FoundationCollections`, are the likely answer); + - `tools/parity` reads Foundation, CoreGraphics and Combine on wasm and + Android from the SDK now (swift-symbolgraph-extract, as Observation's): + a run is due to check its report against the last, generated from + source; + - XCTest is out of the wasm SDKs (corelibs XCTest is built on corelibs + Foundation): SwiftPM's `--build-tests` there wants it back, built + against Isomer's Foundation. ## Warnings as errors, Swift 6 mode, complete concurrency checking (owner, 2026-11-13) @@ -489,12 +497,14 @@ has it. and the system-module scan never reaches libc++'s `std` or CxxStdlib. Nothing in Isomer to change: an app that needs explicit modules waits for those. -- **swift-foundation** (a Swift package through rules_swift_package_manager - at swift-6.4.2-RELEASE's commit, with patches; no fork since 0.40): +- **swift-foundation** (built into Isomer's Swift SDKs since 0.56, from + AttilaTheFun/isomer_hermetic_toolchains' `isomer-6.4.2` branch: + swift-6.4.2-RELEASE with these patches as commits; a Swift package + through rules_swift_package_manager from 0.40 to 0.55): - swiftlang/swift-foundation#2409 (merged): `createDirectory(withIntermediateDirectories:)` stops at "/" (WASI); patched in until a release has it; - CharacterSet, NSString's string API and `String(format:)` are in - //foundation; upstream's own CharacterSet (#2314) arrives with the + Isomer's Foundation; upstream's own CharacterSet (#2314) arrives with the next major release, and ours then gives way; - (the wasi-libc emulation defines its Swift targets' Clang importer needs: rules_swift_package_manager#2640 passes their cSettings, as SwiftPM @@ -502,7 +512,7 @@ has it. - Isomer's own, with no upstream form: ICU linked from the Swift SDK (not swift-foundation-icu from source), Apple's signatures and swift-foundation's extra declarations made internal, `package` on the - string helpers //foundation uses (a copy would need its 2.8 MB Unicode + string helpers Isomer's Foundation uses (a copy would need its 2.8 MB Unicode tables and the standard library's SPI: until upstream's next major release brings CharacterSet, #2314, and its string API). Off Darwin its `.diacriticInsensitive` and `.widthInsensitive` comparison is @@ -548,7 +558,7 @@ run`), CoreGraphics and ImageIO for images. copy); - the parity reports (`tools/parity`); - the SwiftUI audit (`tools/swiftui_audit`, nine scripts); - - `tools/foundation/check_link.py` and `tools/symbols/generate.py`; + - `tools/symbols/generate.py`; - the version stamp (`examples/tools/stamp_storybook.py`); - the pixel benchmark. diff --git a/core_graphics/BUILD.bazel b/core_graphics/BUILD.bazel index 24c9467e..bea320a8 100644 --- a/core_graphics/BUILD.bazel +++ b/core_graphics/BUILD.bazel @@ -1,18 +1,31 @@ # Isomer's CoreGraphics: the part of Apple's CoreGraphics that Swift code # (SwiftUI's interface above all) reaches for, written in Swift: geometry and # CGFloat, CGAffineTransform, CGColor and CGColorSpace, CGPath, line caps and -# joins, blend modes. Built as a module named `CoreGraphics` for the -# platforms that have no CoreGraphics (wasm, Android, Linux, Windows); Apple -# platforms use Apple's. docs/parity/CoreGraphics.md says what is +# joins, blend modes. A module named `CoreGraphics` for the platforms that +# have no CoreGraphics (wasm, Android, Linux, Windows); Apple platforms use +# Apple's. docs/parity/CoreGraphics.md says what is # implemented, what is not, and why. -load("@rules_swift//swift:swift.bzl", "swift_library") +load("@rules_swift//swift:swift.bzl", "swift_library", "swift_library_group") load("//foundation:defs.bzl", "one_configuration") package(default_visibility = ["//visibility:public"]) -one_configuration( +# Since 0.56 these sources build Linux's and Windows' CoreGraphics alone: on +# Android and the web it is the Swift SDK's (Isomer's SDKs carry it, built +# from isomer_hermetic_toolchains' copy, Isomer/Sources/CoreGraphics; a +# change here goes there too), so this label is nothing to link there. +alias( name = "core_graphics", + actual = select({ + "@platforms//os:android": ":none", + "@platforms//os:wasi": ":none", + "//conditions:default": ":package", + }), +) + +one_configuration( + name = "package", target_compatible_with = select({ "@platforms//os:macos": ["@platforms//:incompatible"], "@platforms//os:ios": ["@platforms//:incompatible"], @@ -24,11 +37,14 @@ one_configuration( actual = "@swiftpkg_isomer//:CoreGraphics", ) -# What dependents use (through @isomer//:core_graphics): built in one -# configuration whatever theirs (//foundation:defs.bzl). +swift_library_group(name = "none") + +# What dependents use (through @isomer//:core_graphics, on Linux and +# Windows): built in one configuration whatever theirs +# (//foundation:defs.bzl). one_configuration( name = "for_dependents", - actual = ":core_graphics", + actual = ":package", ) # The same sources under another module name, for tests that run on the diff --git a/docs/hermetic_toolchains.md b/docs/hermetic_toolchains.md index 81ca8e3e..6d832a56 100644 --- a/docs/hermetic_toolchains.md +++ b/docs/hermetic_toolchains.md @@ -1,34 +1,31 @@ -# Isomer's hermetic toolchains (0.55) +# Isomer's Swift SDKs (0.56) Isomer's Foundation built into the Swift SDKs themselves, so that every -`import Foundation` off Apple's platforms is Isomer's: an app's own Swift, +`import Foundation` on Android and the web is Isomer's: an app's own Swift, a Swift package's, a Bazel module's, with no `@isomer//:foundation` edge -anywhere and no corelibs Foundation beside it. One line of a consumer's -MODULE.bazel chooses the toolchains; for Apple's platforms that line can be -Xcode's instead, and the same apps build. +anywhere and no corelibs Foundation beside it. A consumer registers them +with one line a platform, in the `swift` block it already has (README, +"Isomer's Swift SDKs"). ## Why -Today every library that imports Foundation on Android or the web must -depend on `@isomer//:foundation` (a Swift package through -`configure_package(target_deps = …)`), or it finds the Swift SDK's corelibs -Foundation, which links beside Isomer's: duplicate symbols, or (on Android) -OpenSSL's symbols undefined, since the SDK's FoundationNetworking needs -them. Every package an app takes needs that edge declared for it, and a -package nobody declared fails late. With the SDK's Foundation being -Isomer's, nothing needs declaring. +Until 0.56 every library that imported Foundation on Android or the web had +to depend on `@isomer//:foundation` (a Swift package through +`configure_package(target_deps = …)`), or it found the Swift SDK's corelibs +Foundation, which linked beside Isomer's: duplicate symbols, or (on Android) +OpenSSL's symbols undefined, since corelibs' FoundationNetworking needs +them. Every package an app took needed that edge declared, and a package +nobody declared failed late. With the SDK's Foundation being Isomer's, +nothing needs declaring. ## The spike (2026-11-15) -Android arm64, swift.org's 6.4.2 SDK, in a leased container -(/tmp/sdk-foundation-spike): corelibs Foundation, CoreFoundation, curl, -libxml2 and OpenSSL taken out, Isomer's Foundation family put in, the SDK -registered with rules_swift as any other. A plain library that only -imports Foundation, a SwiftProtobuf user with its Foundation edge removed, -and the Android Storybook each linked exactly one Foundation, Isomer's. -The SDK's static libraries went from 208 MB to 144 MB; the Storybook's -native library from 64 MB to 45 MB and its APK from 28 MB to 22 MB (part of -that is the SDK's Foundation being optimized, not a like-for-like build). +Android arm64, swift.org's 6.4.2 SDK, in a leased container: corelibs +Foundation, CoreFoundation, curl, libxml2 and OpenSSL taken out, Isomer's +Foundation family put in, the SDK registered with rules_swift as any other. +A plain library that only imports Foundation, a SwiftProtobuf user with its +Foundation edge removed, and the Android Storybook each linked exactly one +Foundation, Isomer's. The SDK's static libraries went from 208 MB to 144 MB. What it taught: - **Autolink entries are fixed when the importing module compiles.** A @@ -37,87 +34,159 @@ What it taught: So the family is compiled with `-module-link-name` for every module, and the helpers no client imports are folded into the archives clients do autolink: swift-collections and the C shims into FoundationEssentials', - IsomerFoundation and IsomerDispatchTime into Foundation's. swift.org's - SDK does the same with swift-collections (`_FoundationCollections`). -- **The C shims' target is `_FoundationCShims.rspm_c`** under - rules_swift_package_manager. -- **rules_swift takes an SDK by checksum only** (`swift.android_sdk(sha256 - = …)`, its URL download.swift.org's), so the spike supplied the archive - through `--distdir`. + IsomerFoundation, IsomerDispatchTime and (on wasm) CWasiThreadIdentity + into Foundation's. swift.org's SDK does the same with swift-collections + (`_FoundationCollections`). +- **A module imported internally autolinks nothing for its clients.** + FoundationInternationalization imports ICU (`_FoundationICU`) internally, + so it asks its clients for it by `-public-autolink-library`, as + swift-foundation's CMake build does. +- **rules_swift took an Android SDK by checksum only**, its URL + download.swift.org's. rules_swift#2012 adds `url` (below). ## The repository -AttilaTheFun/isomer_hermetic_toolchains, a fork of -swiftlang/swift-foundation (renamed from AttilaTheFun/swift-foundation), -public. A branch per Swift release, `isomer-` (`isomer-6.4.2` -first): swift-foundation's release tag and Isomer's patches as commits -(those isomer applies today: #2409, the SDK's ICU and fts_open, the -package helpers, Apple's interface), rebased onto each new release. +[AttilaTheFun/isomer_hermetic_toolchains](https://github.com/AttilaTheFun/isomer_hermetic_toolchains), +a fork of swiftlang/swift-foundation, public. A branch per Swift release, +`isomer-` (`isomer-6.4.2` first): swift-foundation's release tag, +then Isomer's patches as commits (those isomer applied to swift-foundation +until 0.56: #2409's createDirectory at the root, the SDK's ICU linked by name +and Android's fts_open, `package` on the Essentials helpers Isomer's +Foundation searches strings with, Apple's signatures where swift-foundation's +differ), then Isomer's additions, rebased onto each new release. On that branch, beside swift-foundation's sources: -- `Isomer/`: what Isomer adds to Foundation (isomer's foundation/: the - classic-Foundation layer, URLSession over host transports, Bundle's - strings, UserDefaults, …), and the other modules an SDK carries with it: - CoreGraphics, Combine, IsomerFoundation, IsomerDispatchTime. They move - out of isomer, which then takes them from the SDK. -- A Bazel module, `isomer_hermetic_toolchains`: the SDKs it publishes, by - URL and checksum, and their registration. -- CI that builds each SDK in a container and publishes it as a release - asset: swift.org's SDK for the target, corelibs out, the family in - (built optimized, with link names, the helpers folded), its - `swift-sdk.json` and checksum kept. - -## The SDKs, in order - -1. Android: arm64 first (the spike's), then x86_64 and armv7. Gate: the - Storybook on an emulator, every story drawn as today, and isomer's - Foundation tests. -2. wasm (wasip1): the web Storybook in Chrome, the WASI Foundation tests. -3. Linux and Windows, which use corelibs Foundation today: their hosts and - their Foundation tests move to Isomer's. - -The threads SDK follows Swift 6.5 (TODO.md, "wasi-threads"). - -## Apple's platforms - -Apple's real Foundation, untouched. The module registers rules_applecross's -toolchains (Xcode's SDKs from an archive, its actool, ibtool and codesign), -so Xcode is needed only to run an iOS app, never to build one. The -constraint: a consumer's one line choosing the toolchains, swapped for -apple_support's local Xcode toolchain, builds the same apps with no other -change. +- `Isomer/Sources`: what Isomer adds to Foundation (isomer's `foundation/` + until 0.56: the classic-Foundation layer, URLSession over the host's + transports, Bundle's strings, UserDefaults, …), and the modules an SDK + carries with it: FoundationNetworking, IsomerFoundation, CoreGraphics, + Combine, IsomerDispatchTime, IsomerFoundationInternationalization. Their + targets follow swift-foundation's in its Package.swift, so a release's + manifest rebases under them. +- `sdk/build.sh `: swift.org's SDK for the target, corelibs Foundation + out, the family in, built `-c release` by SwiftPM in a Linux container; + then a client package built against the result and checked: what `import + Foundation` autolinks, that the program has Isomer's Foundation and + nothing of corelibs', that a resilient library at `-library-level api` + can publicly import Foundation, CoreGraphics and Combine, and on wasm the + program and two swift-testing tests run under the toolchain's WasmKit. + Reproducible: the same bundle from any checkout, its file times those of + the last commit to what goes into it. +- `.github/workflows/isomer_sdk.yml`: the four SDKs built on each push to an + `isomer-*` branch, and on an `isomer-*` tag a draft release with them, + their `.sha256` files, and notes giving the consumer's lines. + +## The SDKs + +Each a swift.org 6.4.2 SDK with the family switched in, in two variants: + +| | plain | -i18n | +| --- | --- | --- | +| Android (aarch64, x86_64, armv7) | `swift-6.4.2-RELEASE_android.artifactbundle.tar.gz` | `swift-6.4.2-RELEASE_android-i18n.artifactbundle.tar.gz` | +| WebAssembly (wasm32-unknown-wasip1) | `swift-6.4.2-RELEASE_wasm.artifactbundle.tar.gz` | `swift-6.4.2-RELEASE_wasm-i18n.artifactbundle.tar.gz` | + +released as `isomer-6.4.2.N` (from .1), at +`https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.N/`. + +- **Plain**: Foundation without FoundationInternationalization, and no ICU + linked: `Calendar`'s symbols English, formatting and parsing absent, as + isomer's Foundation was without `--@isomer//foundation:internationalization`. +- **-i18n**: Foundation re-exports FoundationInternationalization, which + links the SDK's own ICU (`lib_FoundationICU.a`, swift.org's): dates, + numbers, lists and measurements formatted as on Apple's platforms. ICU's + data is tens of megabytes of an app; on the web `isomer_web_app(icu_locales + = [...])` keeps only the languages named (tools/wasm/icu_data, as before: + it trims the data the link reads from the SDK's ICU), and ICU_DROP leaves + out the legacy converters and the CJK word dictionaries. +- **Resilient**: Isomer's own modules in the SDKs (Foundation, + FoundationNetworking, IsomerFoundation, CoreGraphics, Combine) are built + with library evolution, as an Apple SDK's Foundation is, so an app's + library built for distribution can import them publicly + (docs/library_evolution.md measured no frame time and about 3% of the + library for all of Isomer's modules). swift-foundation's own modules stay + as upstream builds them. +- **Not in them**: XCTest on wasm (corelibs XCTest is built on corelibs + Foundation; swift-testing stays, over this Foundation), corelibs' + FoundationXML, and, on Android, curl, libxml2 and OpenSSL, which only + corelibs' FoundationNetworking used. The Android SDKs' dynamic resources + stay swift.org's: rules_swift links Swift statically. ## What a consumer writes - bazel_dep(name = "isomer_hermetic_toolchains", version = "6.4.2.N") - toolchains = use_extension("@isomer_hermetic_toolchains//:extensions.bzl", "toolchains") - use_repo(toolchains, …) - register_toolchains("@isomer_hermetic_toolchains//:all") - -rules_swift's `swift` extension takes its SDK tags from one module only and -downloads from swift.org: until it takes a URL (a pull request through the -Upstream session, carried meanwhile as the registry's rules_swift -4.2.2.isomer.4), the module declares the SDKs' repositories itself. +One snippet a platform, each standing alone, in place of +`swift.android_sdk()` and `swift.wasm_sdk()` (README, "Isomer's Swift SDKs", +has them with their checksums): + +```starlark +# If you build for Android: +swift.android_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android.artifactbundle.tar.gz", + sha256 = "…", +) +# If you build for the web: +swift.wasm_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm.artifactbundle.tar.gz", + sha256 = "…", +) +``` + +and the `-i18n` URL (with its own sha256) if the app formats dates or +numbers. An app that builds for Android alone registers no wasm SDK. + +`swift.wasm_sdk` takes `url` through rules_swift#1860 and `swift.android_sdk` +through rules_swift#2012 (generic: any Swift SDK artifact bundle at any URL), +both in the registry's rules_swift 4.2.2.isomer.4, which isomer asks for and +MVS gives every consumer. ## isomer after the move -- Package.swift: Foundation, FoundationNetworking, CoreGraphics, Combine and - IsomerFoundation only on the platforms whose SDK lacks them; off Apple - they are the SDK's. -- `@isomer//:foundation` stays as an empty group on those platforms, so - existing BUILD files keep working, and the `configure_package(target_deps - = …)` an app declared for Foundation can go. -- isomer depends on `isomer_hermetic_toolchains` by version; the toolchains - move on their own cadence, a new Swift release a new branch and version. - -## Open - -- swift-collections inside the SDK under its own module names: an app that - builds swift-collections itself would see two. Private names in the SDK - (as swift.org's `_FoundationCollections`) are the likely answer. -- An archive folded from several modules keeps every object; whether a - conformance only reachable through one is kept needs a run, not just a - link (the gate above). -- FoundationInternationalization (ICU): a second SDK variant, or the ICU - data an app's flag adds. +- **Package.swift**: no Foundation, FoundationNetworking or IsomerFoundation + target, and no swift-foundation dependency: no target depends on a + Foundation, and `import Foundation` is the SDK's. CoreGraphics and Combine + stay, for Linux and Windows only, whose Foundation is still the + toolchain's corelibs. +- **`@isomer//:foundation` and `@isomer//:isomer_foundation`** stay as empty + dependencies, so BUILD files and `target_deps` that name them keep + working; isomer's own `configure_package(target_deps = …)` for Foundation + (SwiftProtobuf's, swift-foundation's patches, FoundationInternationalization's) + are gone, as are the examples'. `//core_graphics` and `//frameworks/combine` + are nothing on Android and the web (the SDK's) and the package's elsewhere. +- **`foundation/`'s sources moved** to isomer_hermetic_toolchains' + `Isomer/Sources`, the one copy Android and the web build from. + `core_graphics/` and `frameworks/combine/` stay here for Linux and Windows + (the SDK has a copy of each: a change goes to both until those platforms' + SDKs carry them), and so does FileWrapper.swift + (`shared/swift_ui_corelibs`), compiled into Linux's and Windows' SwiftUI. +- **`--@isomer//foundation:internationalization`** stays: on Android and the + web it checks that the SDK registered is the -i18n one (a module that + compiles only against it, foundation/internationalization), so a build + that asks for internationalization can't quietly get the plain SDK. + Nothing else follows it any more: the SDK chosen decides. +- **Foundation's tests** (`foundation/tests`, `frameworks/combine/tests`, + `core_graphics/tests`) build against the SDK's modules: isomer's own + module registers the -i18n SDKs (so the internationalization checks and + ICU's trimming run), the examples the plain ones (as the Storybook and + most apps use). +- **tools/parity** reads Foundation, CoreGraphics and Combine on the web from + the SDK (swift-symbolgraph-extract, as Observation's), and classes a + declaration of swift-foundation's by its module where the SDK's modules + carry no source locations. + +## Later + +- **Linux and Windows SDKs**, which use corelibs Foundation today: their + hosts and their Foundation tests move to Isomer's, and isomer's + `core_graphics/`, `frameworks/combine/` and FileWrapper.swift go with them. +- **A Bazel module with one line**, `isomer_hermetic_toolchains`, once the + SDKs are more than two: its SDKs by URL and checksum and their + registration, and Apple's platforms through rules_applecross's toolchains + (Xcode's SDKs from an archive, its actool, ibtool and codesign), so that + swapping that line for apple_support's local Xcode toolchain builds the + same apps with no other change. rules_swift's `swift` extension takes its + tags from the root module only, so until then the consumer's own block + registers the SDKs. +- **The threads SDK** follows Swift 6.5 (TODO.md, "wasi-threads"). +- **swift-collections inside the SDK under its own module names**: an app + that builds swift-collections itself would see two. Private names in the + SDK (as swift.org's `_FoundationCollections`) are the likely answer. diff --git a/docs/library_evolution.md b/docs/library_evolution.md index 9af98b8b..1419662e 100644 --- a/docs/library_evolution.md +++ b/docs/library_evolution.md @@ -10,7 +10,11 @@ os and the rest, which are built without it. Swift reports each such import using it means binary compatibility for 'MyLibrary' can't be guaranteed `--@isomer//:library_evolution` (off by default) builds Isomer's modules -resilient, and the report goes. This page is what it costs, measured on the +resilient, and the report goes. (Foundation, FoundationNetworking, +IsomerFoundation, and on Android and the web CoreGraphics and Combine, are +the Swift SDK's since 0.56: Isomer's SDKs build them resilient whatever the +flag, as an Apple SDK's are, so an app's library can import them publicly +either way; docs/hermetic_toolchains.md.) This page is what it costs, measured on the Android Storybook, and why it stays a flag. ## The report, exactly diff --git a/docs/prebuilt_swift_libraries.md b/docs/prebuilt_swift_libraries.md index 375e4774..fb60965c 100644 --- a/docs/prebuilt_swift_libraries.md +++ b/docs/prebuilt_swift_libraries.md @@ -30,9 +30,10 @@ dependencies, and off Apple's platforms none of them promises a stable binary interface: - **Isomer's modules are compiled without library evolution** (README, - "Swift features, Java and library evolution"): Foundation (Isomer's, over - swift-foundation's FoundationEssentials), FoundationNetworking, - IsomerFoundation, CoreGraphics, Combine, SwiftUI with IsomerSwiftUI + "Swift features, Java and library evolution"), but for Foundation, + FoundationNetworking, IsomerFoundation, CoreGraphics and Combine, which + Isomer's Swift SDKs build resilient since 0.56 (swift-foundation's + FoundationEssentials beneath them stays fragile): SwiftUI with IsomerSwiftUI beneath it, PhotosUI, UniformTypeIdentifiers, the Isomer module, os and OSLog, and swift_ffi's runtime. A library that uses any of them was compiled against their exact layouts: a struct's size and its fields' @@ -211,10 +212,10 @@ linked into `lib_runtime_bindings.so` with the app's Swift: one library, its one Foundation and its one copy of Isomer, as if the code were the app's. `deps` must name every Isomer target the library uses: Bazel reads no autolink entries from a prebuilt archive, so a library it -doesn't name is not linked (an undefined symbol at load), and a library -imported from the Swift SDK instead of Isomer's (the SDK's own Foundation) -would link a second Foundation (tools/foundation/check_link.py finds that -in a build). No `extra_binary_deps`: there is no second `.so`. It works +doesn't name is not linked (an undefined symbol at load). Foundation is +the Swift SDK's (Isomer's, since 0.56), so the library and the app link the +one Foundation whether `deps` names it or not; the library is built with +the same Isomer SDK as the app. No `extra_binary_deps`: there is no second `.so`. It works with the platform too (the archive is linked into the app's library, which binds to the platform). With `--config=android_release` the linker drops what of the archive the app doesn't reach, as it does Isomer's. diff --git a/examples/.bazelrc b/examples/.bazelrc index 220ff60a..3eb2d5ff 100644 --- a/examples/.bazelrc +++ b/examples/.bazelrc @@ -83,10 +83,9 @@ build:linux --action_env=C_INCLUDE_PATH=/usr/lib/glib-2.0/include:/usr/lib/dbus- # No `build --features=swift.…` here, and none in a consumer's .bazelrc: # --features apply to every repository in the build, isomer and every -# SwiftPM package and module beneath it included (swift-foundation's -# collections fail under swift.enable_v6/StrictConcurrency, its -# FoundationEssentials under swift.treat_warnings_as_errors, which conflicts -# with its own -suppress-warnings). Isomer's REPO.bazel turns the common +# SwiftPM package and module beneath it included (a package built for +# Swift 5 fails under swift.enable_v6/StrictConcurrency, one with its own +# -suppress-warnings under swift.treat_warnings_as_errors). Isomer's REPO.bazel turns the common # ones off for its own packages, but it can't for the others. Scope Swift # features to your own repository instead, in its REPO.bazel: # repo(features = ["swift.enable_v6", "swift.treat_warnings_as_errors"]) @@ -149,8 +148,9 @@ build:windows --action_env=PATH # exact versions). Don't read or write it. common --lockfile_mode=off -# Modules from the project's registry first (isomer's rules_swift and -# swift-foundation forks, by version), then the Bazel Central Registry. +# Modules from the project's registry first (isomer's releases and the forks +# it carries, rules_swift's among them, by version), then the Bazel Central +# Registry. common --registry=https://raw.githubusercontent.com/AttilaTheFun/bazel_registry/main common --registry=https://bcr.bazel.build diff --git a/examples/MODULE.bazel b/examples/MODULE.bazel index fef2229c..ffd368b8 100644 --- a/examples/MODULE.bazel +++ b/examples/MODULE.bazel @@ -52,9 +52,10 @@ local_path_override( # --- What isomer needs from its consumer ------------------------------- # rules_swift: isomer's patched version comes from the project's registry -# (.bazelrc lists it before the BCR), patches and all: 4.2.2.isomer.3, which -# sorts above the 4.2.2 rules_applecross asks for, so it needs no override. -bazel_dep(name = "rules_swift", version = "4.2.2.isomer.3") +# (.bazelrc lists it before the BCR), patches and all: 4.2.2.isomer.4, which +# sorts above the 4.2.2 rules_applecross asks for, so it needs no override +# (and takes `swift.android_sdk(url = …)`, below). +bazel_dep(name = "rules_swift", version = "4.2.2.isomer.4") # swift_ffi, swift_gpu and swift_map are part of the isomer module # (`@isomer//swift_ffi/...`, `@isomer//swift_gpu/...`, `@isomer//swift_map/...`): @@ -76,12 +77,24 @@ swift.toolchain( name = "swift_toolchain", swift_version = "6.4.2", ) -swift.wasm_sdk() +# Isomer's Swift SDKs, whose Foundation is Isomer's (README, "Upgrading +# isomer"): one line a platform an app builds for, each standing alone. The +# plain SDKs, as the Storybook formats nothing with Foundation; an app that +# formats dates or numbers takes the -i18n ones +# (swift-6.4.2-RELEASE_-i18n.artifactbundle.tar.gz, with their +# sha256 from the release's notes). +swift.wasm_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm.artifactbundle.tar.gz", + sha256 = "d63e3f15297575b634dcc07b36e19111fb3a24b7dbac0e9b217d3c3532b3bb11", +) # No wasi-threads SDK beside it since 0.41: Isomer's was a build of # Swift 6.3.2 with swiftlang/swift#92018, which reaches a release in 6.5; # reactors built for `@isomer//swift_ffi/rules:wasm32-wasip1-threads` wait # for it (TODO.md). -swift.android_sdk() +swift.android_sdk( + url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android.artifactbundle.tar.gz", + sha256 = "1fce2fe24ec9b7c54f97fe2aff41ceab01b5acbc5a09492c50cc918e1dbcdbac", +) use_repo( swift, "swift_toolchain", @@ -251,74 +264,8 @@ swift_deps.from_package( swift = "//third_party/swift_packages:Package.swift", ) -# On wasm and Android `import Foundation` is Isomer's (@isomer//foundation), -# which a library reaches only by depending on it: the packages built for -# those platforms depend on @isomer//:foundation (nothing on Apple, where -# Foundation is the system's). -swift_deps.configure_package( - name = "swift-protobuf", - target_deps = {"SwiftProtobuf": ["@isomer//:foundation"]}, -) - -swift_deps.configure_package( - name = "grpc-swift-2", - target_deps = {"GRPCCore": ["@isomer//:foundation"]}, -) - -swift_deps.configure_package( - name = "grpc-swift-protobuf", - target_deps = {"GRPCProtobuf": ["@isomer//:foundation"]}, -) - -# gRPC over HTTP/2 (the proto greeter's client): SwiftNIO, its TLS and -# the certificate packages under it. -swift_deps.configure_package( - name = "swift-nio", - target_deps = { - "NIO": ["@isomer//:foundation"], - "NIOPosix": ["@isomer//:foundation"], - }, -) - -swift_deps.configure_package( - name = "swift-nio-ssl", - target_deps = {"NIOSSL": ["@isomer//:foundation"]}, -) - -swift_deps.configure_package( - name = "swift-nio-extras", - target_deps = {"NIOCertificateReloading": ["@isomer//:foundation"]}, -) - -swift_deps.configure_package( - name = "swift-crypto", - target_deps = { - "Crypto": ["@isomer//:foundation"], - "CryptoBoringWrapper": ["@isomer//:foundation"], - "_CryptoExtras": ["@isomer//:foundation"], - }, -) - -swift_deps.configure_package( - name = "swift-certificates", - target_deps = {"X509": ["@isomer//:foundation"]}, -) - -swift_deps.configure_package( - name = "swift-asn1", - target_deps = {"SwiftASN1": ["@isomer//:foundation"]}, -) - -# UpdateKit (AttilaTheFun/update_kit): the Storybook's iPhone and Mac apps -# write the build they are for Applications. -# Apple's alone today, where the label resolves to nothing; on wasm and -# Android it would be Isomer's Foundation. -swift_deps.configure_package( - name = "update_kit", - target_deps = { - "UpdateKit": ["@isomer//:foundation"], - }, -) +# No package here needs a Foundation dependency declared (since 0.56): on wasm +# and Android `import Foundation` is the Swift SDK's, Isomer's (above). use_repo( swift_deps, "swift_package", @@ -333,7 +280,7 @@ use_repo( ) # The generated package repositories see rules_swift_package_manager's -# repositories; the target_deps above (and isomer's own) name @isomer. +# repositories; isomer's own target_deps (its wire protos) name @isomer. inject_repo(swift_deps, "isomer") bazel_dep(name = "rules_java", version = "9.3.0") diff --git a/examples/third_party/swift_packages/Package.resolved b/examples/third_party/swift_packages/Package.resolved index 6e11e506..94cd3a8f 100644 --- a/examples/third_party/swift_packages/Package.resolved +++ b/examples/third_party/swift_packages/Package.resolved @@ -90,23 +90,6 @@ "version" : "3.15.1" } }, - { - "identity" : "swift-foundation", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swiftlang/swift-foundation.git", - "state" : { - "revision" : "e4049b2d77e2d5d70c4cfcc99fd5eca32e1bcb06" - } - }, - { - "identity" : "swift-foundation-icu", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-foundation-icu", - "state" : { - "branch" : "release/6.4.x", - "revision" : "f986d0728da0766cf81f371521b909d4a11681d2" - } - }, { "identity" : "swift-http-structured-headers", "kind" : "remoteSourceControl", diff --git a/examples/third_party/swift_packages/Package.swift b/examples/third_party/swift_packages/Package.swift index 48c5644a..f12fa08a 100644 --- a/examples/third_party/swift_packages/Package.swift +++ b/examples/third_party/swift_packages/Package.swift @@ -10,7 +10,7 @@ let package = Package( name: "isomer_examples_swift_packages", platforms: [.macOS("15.0")], dependencies: [ - // Isomer's Swift (Foundation and the frameworks off Apple), this + // Isomer's Swift (SwiftUI and the frameworks off Apple), this // repository's: an application elsewhere lists it by revision. .package(path: "../../.."), .package(url: "https://github.com/apple/swift-protobuf.git", exact: "1.38.1"), diff --git a/foundation/BUILD.bazel b/foundation/BUILD.bazel index 6e019d49..acd362a6 100644 --- a/foundation/BUILD.bazel +++ b/foundation/BUILD.bazel @@ -1,13 +1,28 @@ -# Isomer's `Foundation` (see Foundation.swift). Apple platforms use Apple's. +# Foundation off Apple's platforms is the Swift SDK's (since 0.56): on Android +# and the web Isomer's Swift SDKs carry Isomer's Foundation, FoundationNetworking, +# IsomerFoundation, CoreGraphics and Combine in place of corelibs' +# (AttilaTheFun/isomer_hermetic_toolchains, whose Isomer/Sources were this +# directory's; docs/hermetic_toolchains.md), so every `import Foundation` there +# is Isomer's with no dependency declared. Linux and Windows keep the +# toolchain's corelibs Foundation. Apple platforms use Apple's. +# +# What is left here: the build settings below, the rule every isomer Swift +# package module is reached through (defs.bzl's one_configuration), and +# Foundation's tests, run against the SDK's Foundation (tests/). # # --@isomer//foundation:internationalization (default false) # -# adds FoundationInternationalization (formatting, locales, calendars and -# time zones beyond the Gregorian/UTC basics) and ICU with it. +# asked for Isomer's Foundation with FoundationInternationalization (dates, +# numbers and lists formatted as on Apple's platforms) and ICU when isomer +# built Foundation from source. With Foundation the SDK's, the SDK chosen +# says so: the -i18n SDK's Foundation has FoundationInternationalization, +# the plain one's hasn't (README, "Upgrading isomer"). The setting stays, and +# on Android and the web checks that the SDK registered is the -i18n one +# (internationalization/), so a build that asks for it can't quietly get +# the plain SDK. load("@bazel_skylib//rules:common_settings.bzl", "bool_flag", "string_flag") load("@rules_swift//swift:swift_library_group.bzl", "swift_library_group") -load(":defs.bzl", "one_configuration") package(default_visibility = ["//visibility:public"]) @@ -28,62 +43,20 @@ config_setting( flag_values = {":internationalization": "true"}, ) -# Isomer's Swift package's Foundation (Package.swift: the sources here, built -# in swift-foundation's package, whose `package` helpers the string API in -# StringProtocol+NSString.swift searches with), with FoundationInternationalization -# when the build asks for it (internationalization/, added by MODULE.bazel). -one_configuration( - name = "foundation", - # Apple platforms have the real one; this one would shadow it. - target_compatible_with = select({ - "@platforms//os:macos": ["@platforms//:incompatible"], - "@platforms//os:ios": ["@platforms//:incompatible"], - "@platforms//os:tvos": ["@platforms//:incompatible"], - "@platforms//os:watchos": ["@platforms//:incompatible"], - "@platforms//os:visionos": ["@platforms//:incompatible"], +# What @isomer//:foundation is where Foundation is Isomer's (Android, the +# web): the SDK's, so nothing to link, and with +# --@isomer//foundation:internationalization the check that the SDK is the +# -i18n one. +swift_library_group( + name = "from_sdk", + deps = select({ + ":with_internationalization": ["//foundation/internationalization"], "//conditions:default": [], }), - actual = "@swiftpkg_isomer//:Foundation", -) - -# What dependents use (through @isomer//:foundation): built in one -# configuration whatever theirs (defs.bzl). FoundationNetworking with it -# (networking/: Isomer's Foundation under corelibs' other name), so code -# that imports both sees one URLSession. -swift_library_group( - name = "foundation_and_networking", - deps = [ - ":foundation", - "//foundation/networking", - ], ) -one_configuration( - name = "for_dependents", - actual = ":foundation_and_networking", -) - -# FileWrapper, compiled into the SwiftUI of Linux and Windows too (their -# Foundation, the toolchain's, has none): what FileDocument hands over. -exports_files(["FileWrapper.swift"], visibility = [ - "//headless/libraries/swift_ui:__pkg__", - "//linux/libraries/swift_ui:__pkg__", - "//linux/libraries/swift_ui_wasm:__pkg__", - "//tests/snapshot:__pkg__", - "//windows/libraries/swift_ui:__pkg__", - "//windows/libraries/swift_ui_wasm:__pkg__", -]) - -# Isomer's Foundation for a Swift package's targets where it is the Foundation -# (the web, Android), and nothing elsewhere (Apple's, or the toolchain's): what -# MODULE.bazel's configure_package gives SwiftProtobuf. +# The label isomer's Foundation had before 0.56, for BUILD files that named it. alias( - name = "for_swift_packages", - actual = select({ - "@platforms//os:android": "//:foundation", - "@platforms//os:wasi": "//:foundation", - "//conditions:default": ":none", - }), + name = "foundation", + actual = "//:foundation", ) - -swift_library_group(name = "none") diff --git a/foundation/Bundle.swift b/foundation/Bundle.swift deleted file mode 100644 index d0e7a148..00000000 --- a/foundation/Bundle.swift +++ /dev/null @@ -1,356 +0,0 @@ -// Bundle, as Isomer's Foundation has it: a directory of resources, found on -// the file system. Apple's Bundle is an Objective-C class (and -// swift-foundation keeps only a package-internal stub of it); this one is -// Swift, with the part of Apple's API that reads resources and the main -// bundle's identity. There is no Info.plist reading: the info dictionary is -// what the host says of the app (its identifier, name and version, the -// `ISOMER_BUNDLE_*` environment), and no class-to-image -// lookup (`Bundle(for:)` is the main bundle) — docs/parity/Foundation.md. -// -// The main bundle is the directory in `ISOMER_BUNDLE_PATH` when the host sets -// it, else the executable's directory, else "/". - -import FoundationEssentials - -open class Bundle: Hashable, CustomStringConvertible, @unchecked Sendable { - /// The bundle's directory. - public let bundleURL: URL - - public init?(path: String) { - guard FileManager.default.itemType(atPath: path) == .typeDirectory else { - return nil - } - bundleURL = URL(fileURLWithPath: path, isDirectory: true) - } - - public convenience init?(url: URL) { - self.init(path: url.path) - } - - /// The bundle a class was loaded from: in Isomer always the main bundle. - public convenience init(for aClass: AnyClass) { - self.init(directory: Bundle.main.bundleURL) - } - - public convenience init?(identifier: String) { - guard identifier == Bundle.main.bundleIdentifier else { return nil } - self.init(directory: Bundle.main.bundleURL) - } - - init(directory: URL) { - bundleURL = directory - } - - nonisolated(unsafe) private static var mainBundle: Bundle? - - /// The application's bundle. - open class var main: Bundle { - if let bundle = mainBundle { return bundle } - let environment = ProcessInfo.processInfo.environment - let directory: URL - if let path = environment["ISOMER_BUNDLE_PATH"], !path.isEmpty { - directory = URL(fileURLWithPath: path, isDirectory: true) - } else if let executable = CommandLine.arguments.first, executable.contains("/") { - directory = URL(fileURLWithPath: executable).deletingLastPathComponent() - } else { - directory = URL(fileURLWithPath: "/", isDirectory: true) - } - let bundle = Bundle(directory: directory) - mainBundle = bundle - return bundle - } - - open class var allBundles: [Bundle] { [main] } - - open class var allFrameworks: [Bundle] { [] } - - open var bundlePath: String { bundleURL.path } - - open var resourceURL: URL? { bundleURL } - - open var resourcePath: String? { resourceURL?.path } - - open var executableURL: URL? { - CommandLine.arguments.first.map { URL(fileURLWithPath: $0) } - } - - open var executablePath: String? { executableURL?.path } - - /// The host's identifier for the app (`ISOMER_BUNDLE_IDENTIFIER`), if set. - open var bundleIdentifier: String? { - ProcessInfo.processInfo.environment["ISOMER_BUNDLE_IDENTIFIER"] - } - - /// The app as its host says it is, under Info.plist's keys: its - /// identifier, name and version (`ISOMER_BUNDLE_IDENTIFIER`, - /// `ISOMER_BUNDLE_NAME`, `ISOMER_BUNDLE_SHORT_VERSION`, - /// `ISOMER_BUNDLE_VERSION`; Android's package, label, versionName and - /// versionCode). - open var infoDictionary: [String: Any]? { - let environment = ProcessInfo.processInfo.environment - var info: [String: Any] = [:] - for (key, variable) in [("CFBundleIdentifier", "ISOMER_BUNDLE_IDENTIFIER"), ("CFBundleName", "ISOMER_BUNDLE_NAME"), - ("CFBundleDisplayName", "ISOMER_BUNDLE_NAME"), - ("CFBundleShortVersionString", "ISOMER_BUNDLE_SHORT_VERSION"), - ("CFBundleVersion", "ISOMER_BUNDLE_VERSION")] { - if let value = environment[variable], !value.isEmpty { info[key] = value } - } - return info - } - - open var localizedInfoDictionary: [String: Any]? { [:] } - - open func object(forInfoDictionaryKey key: String) -> Any? { - infoDictionary?[key] - } - - /// The bundle's `.lproj` folders, `Base` aside. - open var localizations: [String] { - guard let resources = resourceURL, - let names = try? FileManager.default.contentsOfDirectory(atPath: resources.path) else { return [] } - return names.filter { $0.hasSuffix(".lproj") && $0 != "Base.lproj" }.map { String($0.dropLast(6)) }.sorted() - } - - open var preferredLocalizations: [String] { - Bundle.preferredLocalizations(from: localizations) - } - - /// `ISOMER_BUNDLE_DEVELOPMENT_REGION` (Info.plist's - /// CFBundleDevelopmentRegion), else English. - open var developmentLocalization: String? { - let region = ProcessInfo.processInfo.environment["ISOMER_BUNDLE_DEVELOPMENT_REGION"] ?? "" - return region.isEmpty ? "en" : region - } - - open class func preferredLocalizations(from localizationsArray: [String]) -> [String] { - preferredLocalizations(from: localizationsArray, forPreferences: nil) - } - - /// Of `localizationsArray`, the best match for the first preferred - /// language that has one (`ISOMER_PREFERRED_LANGUAGES`, which a host sets - /// from the device's, else `LANGUAGE`, `LC_ALL`, `LC_MESSAGES` or `LANG`), - /// matched by the whole tag, then without its region, then by language: - /// "fr-CA" takes fr-CA.lproj, else fr.lproj. Else the development - /// localization, else the first. - open class func preferredLocalizations( - from localizationsArray: [String], forPreferences preferencesArray: [String]? - ) -> [String] { - func normal(_ tag: String) -> String { tag.replacingOccurrences(of: "_", with: "-").lowercased() } - let available = localizationsArray.map { ($0, normal($0)) } - for preference in preferencesArray ?? preferredLanguages { - var parts = normal(preference).split(separator: "-").map(String.init) - while !parts.isEmpty { - let tag = parts.joined(separator: "-") - if let match = available.first(where: { $0.1 == tag }) { return [match.0] } - parts.removeLast() - } - } - let development = normal(Bundle.main.developmentLocalization ?? "en") - if let match = available.first(where: { $0.1 == development }) { return [match.0] } - return localizationsArray.first.map { [$0] } ?? [] - } - - /// The languages the app prefers, most preferred first, as BCP 47 tags. - static var preferredLanguages: [String] { - let environment = ProcessInfo.processInfo.environment - if let list = environment["ISOMER_PREFERRED_LANGUAGES"], !list.isEmpty { - return list.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } - } - if let list = environment["LANGUAGE"], !list.isEmpty { - return list.split(separator: ":").map(String.init) - } - for name in ["LC_ALL", "LC_MESSAGES", "LANG"] { - // "fr_CA.UTF-8@euro" is fr-CA; C and POSIX name no language. - guard let value = environment[name], !value.isEmpty, value != "C", value != "POSIX" else { continue } - let tag = value.split(separator: ".").first.map(String.init) ?? value - return [String(tag.split(separator: "@").first ?? Substring(tag)).replacingOccurrences(of: "_", with: "-")] - } - return [] - } - - // MARK: Strings tables - - private var tables: [String: [String: String]] = [:] - private let tablesLock = NSLock() - - /// A `.strings` table in a localization's folder (nil: the bundle's - /// root), read once: Xcode's text format, UTF-8 or UTF-16, or a property - /// list (XML or binary) of strings. - func table(_ name: String, localization: String?) -> [String: String] { - let path = (localization.map { "\($0).lproj/" } ?? "") + name + ".strings" - tablesLock.lock() - defer { tablesLock.unlock() } - if let table = tables[path] { return table } - var table: [String: String] = [:] - if let resources = resourceURL, let data = FileManager.default.contents(atPath: resources.appendingPathComponent(path).path) { - table = StringsTable.parse(data) ?? [:] - } - tables[path] = table - return table - } - - // MARK: Resources - - open func url(forResource name: String?, withExtension ext: String?) -> URL? { - url(forResource: name, withExtension: ext, subdirectory: nil) - } - - open func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?) -> URL? { - guard let resources = resourceURL else { return nil } - let directory = subpath.map { resources.appendingPathComponent($0, isDirectory: true) } ?? resources - if let name { - var file = name - if let ext, !ext.isEmpty { file += "." + ext } - let candidate = directory.appendingPathComponent(file) - return FileManager.default.fileExists(atPath: candidate.path) ? candidate : nil - } - return urls(forResourcesWithExtension: ext, subdirectory: subpath)?.first - } - - open func url( - forResource name: String?, withExtension ext: String?, subdirectory subpath: String?, - localization localizationName: String? - ) -> URL? { - url(forResource: name, withExtension: ext, subdirectory: subpath) - } - - open func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?) -> [URL]? { - guard let resources = resourceURL else { return nil } - let directory = subpath.map { resources.appendingPathComponent($0, isDirectory: true) } ?? resources - guard let names = try? FileManager.default.contentsOfDirectory(atPath: directory.path) else { - return nil - } - return names.sorted() - .filter { ext == nil || ext == "" || $0.hasSuffix("." + ext!) } - .map { directory.appendingPathComponent($0) } - } - - open func path(forResource name: String?, ofType ext: String?) -> String? { - url(forResource: name, withExtension: ext)?.path - } - - open func path(forResource name: String?, ofType ext: String?, inDirectory subpath: String?) -> String? { - url(forResource: name, withExtension: ext, subdirectory: subpath)?.path - } - - open func paths(forResourcesOfType ext: String?, inDirectory subpath: String?) -> [String] { - urls(forResourcesWithExtension: ext, subdirectory: subpath)?.map(\.path) ?? [] - } - - /// The key's string in `.strings` (Localizable when nil), looked - /// up as Apple's Bundle does: in the preferred localization's folder, - /// then the development localization's, then Base.lproj's, then the - /// bundle's root. Not found: `value`, or the key when that is empty. - open func localizedString(forKey key: String, value: String?, table tableName: String?) -> String { - let name = (tableName ?? "").isEmpty ? "Localizable" : tableName! - var folders: [String?] = preferredLocalizations - if let development = developmentLocalization, localizations.contains(development) { folders.append(development) } - folders += ["Base", nil] - for folder in folders { - if let string = table(name, localization: folder)[key] { return string } - } - if let value, !value.isEmpty { return value } - return key - } - - // MARK: Equality - - public static func == (lhs: Bundle, rhs: Bundle) -> Bool { - lhs.bundleURL == rhs.bundleURL - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(bundleURL) - } - - open var description: String { "Bundle <\(bundlePath)>" } -} - -/// `key` localized from `bundle`'s strings tables (`localizedString(forKey:value:table:)`). -public func NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", - comment: String) -> String { - bundle.localizedString(forKey: key, value: value, table: tableName) -} - -/// Reads a `.strings` file: Xcode's text format (`"key" = "value";`, an -/// unquoted key or value of letters, digits and `_.-:/$`, `/* */` and `//` -/// comments, `\n \t \r \" \\ \Uxxxx` escapes) in UTF-8 or UTF-16 (by -/// its byte order mark), or a property list of strings (XML or binary, as -/// Xcode compiles them). -enum StringsTable { - static func parse(_ data: Data) -> [String: String]? { - let bytes = [UInt8](data) - if bytes.starts(with: Array("bplist".utf8)) || bytes.starts(with: Array(" String? { - skipSpace() - guard let first = scalars.first else { return nil } - var out = String.UnicodeScalarView() - if first == "\"" { - scalars = scalars.dropFirst() - while let next = scalars.popFirst() { - if next == "\"" { return String(out) } - guard next == "\\", let escaped = scalars.popFirst() else { out.append(next); continue } - switch escaped { - case "n": out.append("\n") - case "t": out.append("\t") - case "r": out.append("\r") - case "U", "u": - let hex = String(String.UnicodeScalarView(scalars.prefix(4))) - guard let code = UInt32(hex, radix: 16), let scalar = Unicode.Scalar(code) else { return nil } - out.append(scalar) - scalars = scalars.dropFirst(4) - default: out.append(escaped) - } - } - return nil // unterminated - } - while let next = scalars.first, next.properties.isAlphabetic || next.properties.numericType != nil - || "_.-:/$".unicodeScalars.contains(next) { - out.append(next) - scalars = scalars.dropFirst() - } - return out.isEmpty ? nil : String(out) - } - while true { - skipSpace() - if scalars.isEmpty { return table } - guard let key = token() else { return nil } - skipSpace() - if scalars.first == ";" { - scalars = scalars.dropFirst() - table[key] = key - continue - } - guard scalars.popFirst() == "=", let value = token() else { return nil } - skipSpace() - guard scalars.popFirst() == ";" else { return nil } - table[key] = value - } - } -} diff --git a/foundation/CalendarSymbols.swift b/foundation/CalendarSymbols.swift deleted file mode 100644 index 14baca40..00000000 --- a/foundation/CalendarSymbols.swift +++ /dev/null @@ -1,44 +0,0 @@ -// Calendar's symbol lists without FoundationInternationalization: English, -// as the `en_US_POSIX` locale names them, whatever the calendar's locale. -// With `--@isomer//foundation:internationalization` the lists are ICU's, -// localized, and these are not compiled (docs/parity/Foundation.md). - -#if !canImport(IsomerFoundationInternationalization) -import FoundationEssentials - -extension Calendar { - public var eraSymbols: [String] { ["BC", "AD"] } - public var longEraSymbols: [String] { ["Before Christ", "Anno Domini"] } - - public var monthSymbols: [String] { - ["January", "February", "March", "April", "May", "June", "July", "August", "September", - "October", "November", "December"] - } - public var shortMonthSymbols: [String] { - ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - } - public var veryShortMonthSymbols: [String] { - ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"] - } - public var standaloneMonthSymbols: [String] { monthSymbols } - public var shortStandaloneMonthSymbols: [String] { shortMonthSymbols } - public var veryShortStandaloneMonthSymbols: [String] { veryShortMonthSymbols } - - public var weekdaySymbols: [String] { - ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - } - public var shortWeekdaySymbols: [String] { ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] } - public var veryShortWeekdaySymbols: [String] { ["S", "M", "T", "W", "T", "F", "S"] } - public var standaloneWeekdaySymbols: [String] { weekdaySymbols } - public var shortStandaloneWeekdaySymbols: [String] { shortWeekdaySymbols } - public var veryShortStandaloneWeekdaySymbols: [String] { veryShortWeekdaySymbols } - - public var quarterSymbols: [String] { ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] } - public var shortQuarterSymbols: [String] { ["Q1", "Q2", "Q3", "Q4"] } - public var standaloneQuarterSymbols: [String] { quarterSymbols } - public var shortStandaloneQuarterSymbols: [String] { shortQuarterSymbols } - - public var amSymbol: String { "AM" } - public var pmSymbol: String { "PM" } -} -#endif diff --git a/foundation/CharacterSet.swift b/foundation/CharacterSet.swift deleted file mode 100644 index dc7251e7..00000000 --- a/foundation/CharacterSet.swift +++ /dev/null @@ -1,519 +0,0 @@ -// CharacterSet for platforms without Apple's framework. Upstream -// leaves it to swift-corelibs-foundation's NSCharacterSet; here it is a Swift -// value: explicit ranges of scalars, the built-in sets (by Unicode general -// category, CoreFoundation's bitmaps where Essentials has them, the URL -// component sets by RFC 3986), and their combinations, evaluated per scalar. - -import FoundationEssentials - -@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *) -public struct CharacterSet: Hashable, SetAlgebra, Sendable { - public typealias Element = Unicode.Scalar - public typealias ArrayLiteralElement = Unicode.Scalar - - enum BuiltIn: Hashable, Sendable { - case controlCharacters - case whitespaces - case whitespacesAndNewlines - case decimalDigits - case letters - case lowercaseLetters - case uppercaseLetters - case nonBaseCharacters - case alphanumerics - case decomposables - case illegalCharacters - case punctuationCharacters - case capitalizedLetters - case symbols - case newlines - case urlUserAllowed - case urlPasswordAllowed - case urlHostAllowed - case urlPathAllowed - case urlQueryAllowed - case urlFragmentAllowed - - func contains(_ scalar: Unicode.Scalar) -> Bool { - let value = scalar.value - switch self { - case .controlCharacters: - switch scalar.properties.generalCategory { - case .control, .format: return true - default: return false - } - case .whitespaces: - return value == 0x09 || scalar.properties.generalCategory == .spaceSeparator - case .whitespacesAndNewlines: - if (0x09...0x0D).contains(value) || value == 0x85 { return true } - switch scalar.properties.generalCategory { - case .spaceSeparator, .lineSeparator, .paragraphSeparator: return true - default: return false - } - case .newlines: - return (0x0A...0x0D).contains(value) || value == 0x85 || value == 0x2028 || value == 0x2029 - case .decimalDigits: - return scalar.properties.generalCategory == .decimalNumber - case .letters: - return Self.isLetter(scalar) || Self.isMark(scalar) - case .lowercaseLetters: - return BuiltInUnicodeScalarSet.lowercaseLetters.contains(scalar) - || scalar.properties.generalCategory == .lowercaseLetter - case .uppercaseLetters: - return BuiltInUnicodeScalarSet.uppercaseLetters.contains(scalar) - || scalar.properties.generalCategory == .uppercaseLetter - || scalar.properties.generalCategory == .titlecaseLetter - case .nonBaseCharacters: - return Self.isMark(scalar) - case .alphanumerics: - return Self.isLetter(scalar) || Self.isMark(scalar) || Self.isNumber(scalar) - case .decomposables: - return BuiltInUnicodeScalarSet.canonicalDecomposables.contains(scalar) - case .illegalCharacters: - return scalar.properties.generalCategory == .unassigned - case .punctuationCharacters: - switch scalar.properties.generalCategory { - case .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation, - .initialPunctuation, .finalPunctuation, .otherPunctuation: - return true - default: - return false - } - case .capitalizedLetters: - return scalar.properties.generalCategory == .titlecaseLetter - case .symbols: - switch scalar.properties.generalCategory { - case .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol: return true - default: return false - } - case .urlUserAllowed, .urlPasswordAllowed: - return Self.isUnreserved(value) || Self.isSubDelimiter(value) - case .urlHostAllowed: - return Self.isUnreserved(value) || Self.isSubDelimiter(value) - || value == 0x3A || value == 0x5B || value == 0x5D // : [ ] - case .urlPathAllowed: - return Self.isUnreserved(value) || Self.isSubDelimiter(value) - || value == 0x3A || value == 0x40 || value == 0x2F // : @ / - case .urlQueryAllowed, .urlFragmentAllowed: - return Self.isUnreserved(value) || Self.isSubDelimiter(value) - || value == 0x3A || value == 0x40 || value == 0x2F || value == 0x3F // : @ / ? - } - } - - static func isLetter(_ scalar: Unicode.Scalar) -> Bool { - switch scalar.properties.generalCategory { - case .uppercaseLetter, .lowercaseLetter, .titlecaseLetter, .modifierLetter, .otherLetter: return true - default: return false - } - } - - static func isMark(_ scalar: Unicode.Scalar) -> Bool { - switch scalar.properties.generalCategory { - case .nonspacingMark, .spacingMark, .enclosingMark: return true - default: return false - } - } - - static func isNumber(_ scalar: Unicode.Scalar) -> Bool { - switch scalar.properties.generalCategory { - case .decimalNumber, .letterNumber, .otherNumber: return true - default: return false - } - } - - /// RFC 3986 unreserved: ALPHA / DIGIT / "-" / "." / "_" / "~". - static func isUnreserved(_ value: UInt32) -> Bool { - (0x41...0x5A).contains(value) || (0x61...0x7A).contains(value) || (0x30...0x39).contains(value) - || value == 0x2D || value == 0x2E || value == 0x5F || value == 0x7E - } - - /// RFC 3986 sub-delims: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=". - static func isSubDelimiter(_ value: UInt32) -> Bool { - switch value { - case 0x21, 0x24, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x3B, 0x3D: return true - default: return false - } - } - } - - indirect enum Storage: Hashable, Sendable { - /// Sorted, non-overlapping, non-adjacent ranges of scalar values. - case ranges([ClosedRange]) - case builtIn(BuiltIn) - case inverted(Storage) - case union(Storage, Storage) - case intersection(Storage, Storage) - case subtracting(Storage, Storage) - case symmetricDifference(Storage, Storage) - - func contains(_ scalar: Unicode.Scalar) -> Bool { - switch self { - case .ranges(let ranges): - let value = scalar.value - var low = 0 - var high = ranges.count - 1 - while low <= high { - let middle = (low + high) / 2 - let range = ranges[middle] - if value < range.lowerBound { - high = middle - 1 - } else if value > range.upperBound { - low = middle + 1 - } else { - return true - } - } - return false - case .builtIn(let set): - return set.contains(scalar) - case .inverted(let set): - return !set.contains(scalar) - case .union(let a, let b): - return a.contains(scalar) || b.contains(scalar) - case .intersection(let a, let b): - return a.contains(scalar) && b.contains(scalar) - case .subtracting(let a, let b): - return a.contains(scalar) && !b.contains(scalar) - case .symmetricDifference(let a, let b): - return a.contains(scalar) != b.contains(scalar) - } - } - - var explicitRanges: [ClosedRange]? { - if case .ranges(let ranges) = self { return ranges } - return nil - } - } - - var storage: Storage - - init(storage: Storage) { - self.storage = storage - } - - // MARK: Making sets - - public init() { - storage = .ranges([]) - } - - public init(charactersIn range: Range) { - if range.isEmpty { - storage = .ranges([]) - } else { - storage = .ranges([range.lowerBound.value...(range.upperBound.value - 1)]) - } - } - - public init(charactersIn range: ClosedRange) { - storage = .ranges([range.lowerBound.value...range.upperBound.value]) - } - - public init(charactersIn string: __shared String) { - storage = .ranges(Self.normalized(string.unicodeScalars.map { $0.value...$0.value })) - } - - /// A set from a bitmap as `bitmapRepresentation` makes one. - public init(bitmapRepresentation data: __shared Data) { - var ranges: [ClosedRange] = [] - let bytes = [UInt8](data) - func addPlane(_ plane: UInt32, from offset: Int) { - guard offset < bytes.count else { return } - let end = min(offset + 8192, bytes.count) - for index in offset.. Bool { - storage.contains(member) - } - - public var inverted: CharacterSet { - if case .inverted(let inner) = storage { return CharacterSet(storage: inner) } - return CharacterSet(storage: .inverted(storage)) - } - - public mutating func invert() { - self = inverted - } - - public func hasMember(inPlane plane: UInt8) -> Bool { - let start = UInt32(plane) << 16 - for value in start...(start + 0xFFFF) { - if let scalar = Unicode.Scalar(value), contains(scalar) { return true } - } - return false - } - - /// The set as a bitmap: 8192 bytes for the Basic Multilingual Plane, then - /// for each other plane with members its number and 8192 bytes. - public var bitmapRepresentation: Data { - var result = Data(count: 8192) - for plane in UInt32(0)...16 { - var bitmap = [UInt8](repeating: 0, count: 8192) - var any = false - for low in UInt32(0)...0xFFFF { - if let scalar = Unicode.Scalar((plane << 16) | low), contains(scalar) { - bitmap[Int(low >> 3)] |= UInt8(1 << (low & 7)) - any = true - } - } - if plane == 0 { - result = Data(bitmap) - } else if any { - result.append(UInt8(plane)) - result.append(contentsOf: bitmap) - } - } - return result - } - - // MARK: Changing sets - - public mutating func insert(charactersIn range: Range) { - formUnion(CharacterSet(charactersIn: range)) - } - - public mutating func insert(charactersIn range: ClosedRange) { - formUnion(CharacterSet(charactersIn: range)) - } - - public mutating func remove(charactersIn range: Range) { - subtract(CharacterSet(charactersIn: range)) - } - - public mutating func remove(charactersIn range: ClosedRange) { - subtract(CharacterSet(charactersIn: range)) - } - - public mutating func insert(charactersIn string: String) { - formUnion(CharacterSet(charactersIn: string)) - } - - public mutating func remove(charactersIn string: String) { - subtract(CharacterSet(charactersIn: string)) - } - - @discardableResult - public mutating func insert(_ character: Unicode.Scalar) -> (inserted: Bool, memberAfterInsert: Unicode.Scalar) { - if contains(character) { return (false, character) } - formUnion(CharacterSet(charactersIn: character...character)) - return (true, character) - } - - @discardableResult - public mutating func update(with character: Unicode.Scalar) -> Unicode.Scalar? { - let present = contains(character) - formUnion(CharacterSet(charactersIn: character...character)) - return present ? character : nil - } - - @discardableResult - public mutating func remove(_ character: Unicode.Scalar) -> Unicode.Scalar? { - guard contains(character) else { return nil } - subtract(CharacterSet(charactersIn: character...character)) - return character - } - - // MARK: Set algebra - - public func union(_ other: CharacterSet) -> CharacterSet { - if let a = storage.explicitRanges, let b = other.storage.explicitRanges { - return CharacterSet(storage: .ranges(Self.normalized(a + b))) - } - return CharacterSet(storage: .union(storage, other.storage)) - } - - public mutating func formUnion(_ other: CharacterSet) { - self = union(other) - } - - public func intersection(_ other: CharacterSet) -> CharacterSet { - if let a = storage.explicitRanges, let b = other.storage.explicitRanges { - var result: [ClosedRange] = [] - var i = 0, j = 0 - while i < a.count && j < b.count { - let low = max(a[i].lowerBound, b[j].lowerBound) - let high = min(a[i].upperBound, b[j].upperBound) - if low <= high { result.append(low...high) } - if a[i].upperBound < b[j].upperBound { i += 1 } else { j += 1 } - } - return CharacterSet(storage: .ranges(result)) - } - return CharacterSet(storage: .intersection(storage, other.storage)) - } - - public mutating func formIntersection(_ other: CharacterSet) { - self = intersection(other) - } - - public func subtracting(_ other: CharacterSet) -> CharacterSet { - if let a = storage.explicitRanges, let b = other.storage.explicitRanges { - var result: [ClosedRange] = [] - for range in a { - var pieces = [range] - for cut in b where cut.overlaps(range) { - pieces = pieces.flatMap { piece -> [ClosedRange] in - guard piece.overlaps(cut) else { return [piece] } - var kept: [ClosedRange] = [] - if piece.lowerBound < cut.lowerBound { kept.append(piece.lowerBound...(cut.lowerBound - 1)) } - if piece.upperBound > cut.upperBound { kept.append((cut.upperBound + 1)...piece.upperBound) } - return kept - } - } - result.append(contentsOf: pieces) - } - return CharacterSet(storage: .ranges(Self.normalized(result))) - } - return CharacterSet(storage: .subtracting(storage, other.storage)) - } - - public mutating func subtract(_ other: CharacterSet) { - self = subtracting(other) - } - - public func symmetricDifference(_ other: CharacterSet) -> CharacterSet { - if storage.explicitRanges != nil, other.storage.explicitRanges != nil { - return subtracting(other).union(other.subtracting(self)) - } - return CharacterSet(storage: .symmetricDifference(storage, other.storage)) - } - - public mutating func formSymmetricDifference(_ other: CharacterSet) { - self = symmetricDifference(other) - } - - public func isSuperset(of other: CharacterSet) -> Bool { - other.subtracting(self).isEmpty - } - - public var isEmpty: Bool { - if let ranges = storage.explicitRanges { return ranges.isEmpty } - return materializedRanges.isEmpty - } - - // MARK: Equality - - /// Every member, as ranges: what equality compares when a set is not - /// already explicit ranges (it reads all 1,114,112 code points). - var materializedRanges: [ClosedRange] { - if let ranges = storage.explicitRanges { return ranges } - var ranges: [ClosedRange] = [] - var start: UInt32? - for value in UInt32(0)...0x10FFFF { - let member = Unicode.Scalar(value).map(contains) ?? false - if member, start == nil { start = value } - if !member, let first = start { - ranges.append(first...(value - 1)) - start = nil - } - } - if let first = start { ranges.append(first...0x10FFFF) } - return ranges - } - - public static func == (lhs: CharacterSet, rhs: CharacterSet) -> Bool { - if lhs.storage == rhs.storage { return true } - return lhs.materializedRanges == rhs.materializedRanges - } - - /// Hashes membership of the ASCII and Latin-1 range: equal sets hash - /// equally whatever their storage. - public func hash(into hasher: inout Hasher) { - var bits: UInt64 = 0 - var word = 0 - for value in UInt32(0)..<256 { - if contains(Unicode.Scalar(value)!) { bits |= 1 << UInt64(value & 63) } - if value & 63 == 63 { - hasher.combine(bits) - bits = 0 - word += 1 - } - } - } - - // MARK: Helpers - - static func normalized(_ ranges: [ClosedRange]) -> [ClosedRange] { - let sorted = ranges.sorted { $0.lowerBound < $1.lowerBound } - var result: [ClosedRange] = [] - for range in sorted { - if let last = result.last, range.lowerBound <= last.upperBound &+ 1 { - result[result.count - 1] = last.lowerBound...max(last.upperBound, range.upperBound) - } else { - result.append(range) - } - } - return result - } -} - -@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *) -extension CharacterSet: CustomStringConvertible, CustomDebugStringConvertible { - public var description: String { "" } - public var debugDescription: String { description } -} - -@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *) -extension CharacterSet: Codable { - private enum CodingKeys: String, CodingKey { - case bitmap - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.init(bitmapRepresentation: try container.decode(Data.self, forKey: .bitmap)) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(bitmapRepresentation, forKey: .bitmap) - } -} - diff --git a/foundation/Combine.swift b/foundation/Combine.swift deleted file mode 100644 index 9a4f5cf9..00000000 --- a/foundation/Combine.swift +++ /dev/null @@ -1,90 +0,0 @@ -// What Apple's Foundation gives Combine code: `ObservableObject` and -// `Published` named from Foundation (typealiases of Combine's, as Apple's -// Foundation declares them, so a model needs only `import Foundation`), and -// NotificationCenter's publisher. Combine is Isomer's (frameworks/combine), -// beneath Foundation; Foundation doesn't re-export it, as Apple's doesn't. - -import Combine - -public typealias Published = Combine.Published -public typealias ObservableObject = Combine.ObservableObject - -extension NotificationCenter { - /// The notifications of one name (and, given one, object) posted to a - /// center, as a publisher: each subscriber gets those posted while it - /// is subscribed and has demand for them (others are dropped, as - /// Apple's are). - public struct Publisher: Combine.Publisher { - public typealias Output = Notification - public typealias Failure = Never - - public let center: NotificationCenter - public let name: Notification.Name - public let object: AnyObject? - - public init(center: NotificationCenter, name: Notification.Name, object: AnyObject? = nil) { - self.center = center - self.name = name - self.object = object - } - - public func receive(subscriber: S) where S: Subscriber, S.Failure == Never, S.Input == Notification { - subscriber.receive(subscription: _NotificationSubscription(center: center, name: name, object: object, subscriber: subscriber)) - } - } - - public func publisher(for name: Notification.Name, object: AnyObject? = nil) -> NotificationCenter.Publisher { - Publisher(center: self, name: name, object: object) - } -} - -extension NotificationCenter.Publisher: Equatable { - public static func == (lhs: NotificationCenter.Publisher, rhs: NotificationCenter.Publisher) -> Bool { - lhs.center === rhs.center && lhs.name == rhs.name && lhs.object === rhs.object - } -} - -/// One subscriber's observer on the center: added at subscription, removed -/// when cancelled. -private final class _NotificationSubscription: Subscription, @unchecked Sendable -where S.Input == Notification, S.Failure == Never { - private let lock = NSLock() - private var subscriber: S? - private var demand: Subscribers.Demand = .none - private var observer: (any NSObjectProtocol)? - private let center: NotificationCenter - - init(center: NotificationCenter, name: Notification.Name, object: AnyObject?, subscriber: S) { - self.center = center - self.subscriber = subscriber - observer = center.addObserver(forName: name, object: object, queue: nil) { [weak self] notification in - self?.deliver(notification) - } - } - - private func deliver(_ notification: Notification) { - lock.lock() - guard let subscriber, demand > 0 else { lock.unlock(); return } - demand -= 1 - lock.unlock() - let more = subscriber.receive(notification) - lock.lock() - demand += more - lock.unlock() - } - - func request(_ demand: Subscribers.Demand) { - lock.lock() - self.demand += demand - lock.unlock() - } - - func cancel() { - lock.lock() - let observer = self.observer - self.observer = nil - subscriber = nil - lock.unlock() - if let observer { center.removeObserver(observer) } - } -} diff --git a/foundation/FileHandle.swift b/foundation/FileHandle.swift deleted file mode 100644 index f11b214b..00000000 --- a/foundation/FileHandle.swift +++ /dev/null @@ -1,223 +0,0 @@ -// FileHandle over a file descriptor (Apple's Foundation and corelibs have -// it; swift-foundation does not): reading, writing, seeking and closing. -// The run-loop-driven background reads and the readability handlers are -// not here (docs/parity/Foundation.md). - -import FoundationEssentials -#if canImport(Android) -import Android -#elseif canImport(Glibc) -import Glibc -#elseif canImport(WASILibc) -import WASILibc -#endif - -open class FileHandle: @unchecked Sendable { - public let fileDescriptor: Int32 - private let closeOnDealloc: Bool - private var closed = false - - public init(fileDescriptor fd: Int32, closeOnDealloc closeopt: Bool) { - fileDescriptor = fd - closeOnDealloc = closeopt - } - - public convenience init(fileDescriptor fd: Int32) { - self.init(fileDescriptor: fd, closeOnDealloc: false) - } - - deinit { - if closeOnDealloc && !closed { - _ = Self.systemClose(fileDescriptor) - } - } - - public static let standardInput = FileHandle(fileDescriptor: 0) - public static let standardOutput = FileHandle(fileDescriptor: 1) - public static let standardError = FileHandle(fileDescriptor: 2) - - public static var nullDevice: FileHandle { - FileHandle(forUpdatingAtPath: "/dev/null") ?? FileHandle(fileDescriptor: -1) - } - - private convenience init?(path: String, flags: Int32) { - let fd = systemOpen(path, flags) - guard fd >= 0 else { return nil } - self.init(fileDescriptor: fd, closeOnDealloc: true) - } - - private convenience init(url: URL, flags: Int32) throws { - let fd = systemOpen(url.path, flags) - guard fd >= 0 else { throw Self.lastError() } - self.init(fileDescriptor: fd, closeOnDealloc: true) - } - - public convenience init?(forReadingAtPath path: String) { - self.init(path: path, flags: O_RDONLY) - } - - public convenience init?(forWritingAtPath path: String) { - self.init(path: path, flags: O_WRONLY) - } - - public convenience init?(forUpdatingAtPath path: String) { - self.init(path: path, flags: O_RDWR) - } - - public convenience init(forReadingFrom url: URL) throws { - try self.init(url: url, flags: O_RDONLY) - } - - public convenience init(forWritingTo url: URL) throws { - try self.init(url: url, flags: O_WRONLY) - } - - public convenience init(forUpdating url: URL) throws { - try self.init(url: url, flags: O_RDWR) - } - - private static func lastError() -> POSIXError { - POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) - } - - private static func systemClose(_ fd: Int32) -> Int32 { - Glibc_close(fd) - } - - // MARK: Reading - - /// Up to `count` bytes; nil at the end of the file. - public func read(upToCount count: Int) throws -> Data? { - var data = Data() - var buffer = [UInt8](repeating: 0, count: min(max(count, 0), 64 << 10)) - while data.count < count { - let wanted = min(buffer.count, count - data.count) - let got = buffer.withUnsafeMutableBytes { Glibc_read(fileDescriptor, $0.baseAddress, wanted) } - if got < 0 { - if errno == EINTR { continue } - throw Self.lastError() - } - if got == 0 { break } - data.append(contentsOf: buffer[0.. 0 ? nil : data - } - - /// Everything to the end of the file; nil when there was nothing. - public func readToEnd() throws -> Data? { - var data = Data() - while let chunk = try read(upToCount: 64 << 10) { - data.append(chunk) - } - return data.isEmpty ? nil : data - } - - public var availableData: Data { - (try? read(upToCount: 64 << 10)) ?? Data() - } - - public func readDataToEndOfFile() -> Data { - (try? readToEnd()) ?? Data() - } - - public func readData(ofLength length: Int) -> Data { - (try? read(upToCount: length)) ?? Data() - } - - // MARK: Writing - - public func write(contentsOf data: T) throws { - for region in data.regions { - try region.withUnsafeBytes { bytes in - var offset = 0 - while offset < bytes.count { - let written = Glibc_write(fileDescriptor, bytes.baseAddress! + offset, bytes.count - offset) - if written < 0 { - if errno == EINTR { continue } - throw Self.lastError() - } - offset += written - } - } - } - } - - public func write(_ data: Data) { - try? write(contentsOf: data) - } - - // MARK: Position - - public func offset() throws -> UInt64 { - let position = lseek(fileDescriptor, 0, SEEK_CUR) - guard position >= 0 else { throw Self.lastError() } - return UInt64(position) - } - - @discardableResult - public func seekToEnd() throws -> UInt64 { - let position = lseek(fileDescriptor, 0, SEEK_END) - guard position >= 0 else { throw Self.lastError() } - return UInt64(position) - } - - public func seek(toOffset offset: UInt64) throws { - guard lseek(fileDescriptor, off_t(offset), SEEK_SET) >= 0 else { throw Self.lastError() } - } - - public var offsetInFile: UInt64 { (try? offset()) ?? 0 } - - @discardableResult - public func seekToEndOfFile() -> UInt64 { - (try? seekToEnd()) ?? 0 - } - - public func seek(toFileOffset offset: UInt64) { - try? seek(toOffset: offset) - } - - public func truncate(atOffset offset: UInt64) throws { - guard ftruncate(fileDescriptor, off_t(offset)) == 0 else { throw Self.lastError() } - try seek(toOffset: offset) - } - - public func truncateFile(atOffset offset: UInt64) { - try? truncate(atOffset: offset) - } - - public func synchronize() throws { - guard fsync(fileDescriptor) == 0 else { throw Self.lastError() } - } - - public func synchronizeFile() { - try? synchronize() - } - - public func close() throws { - guard !closed else { return } - closed = true - guard Self.systemClose(fileDescriptor) == 0 else { throw Self.lastError() } - } - - public func closeFile() { - try? close() - } -} - -// The C calls under names of their own: inside FileHandle, `read` and -// `write` are its methods. -private func Glibc_read(_ fd: Int32, _ buffer: UnsafeMutableRawPointer?, _ count: Int) -> Int { - read(fd, buffer, count) -} - -private func Glibc_write(_ fd: Int32, _ buffer: UnsafeRawPointer?, _ count: Int) -> Int { - write(fd, buffer, count) -} - -private func Glibc_close(_ fd: Int32) -> Int32 { - close(fd) -} - -private func systemOpen(_ path: String, _ flags: Int32) -> Int32 { - open(path, flags, 0o644) -} diff --git a/foundation/FileManager+ItemType.swift b/foundation/FileManager+ItemType.swift deleted file mode 100644 index fcc8b211..00000000 --- a/foundation/FileManager+ItemType.swift +++ /dev/null @@ -1,21 +0,0 @@ -// What is at a path, for Isomer's own code: Apple's way to ask is -// fileExists(atPath:isDirectory:) with an Objective-C ObjCBool, which -// Isomer's Foundation leaves out. - -import FoundationEssentials - -extension FileManager { - /// The type of the item at `path`, symbolic links followed (as - /// fileExists(atPath:isDirectory:) follows them), or nil when there is - /// none. - func itemType(atPath path: String) -> FileAttributeType? { - var current = path - for _ in 0..<8 { - guard let type = (try? attributesOfItem(atPath: current))?[.type] as? FileAttributeType else { return nil } - guard type == .typeSymbolicLink, let target = try? destinationOfSymbolicLink(atPath: current) else { return type } - current = target.hasPrefix("/") ? target - : URL(fileURLWithPath: current).deletingLastPathComponent().appendingPathComponent(target).path - } - return nil - } -} diff --git a/foundation/FileWrapper.swift b/foundation/FileWrapper.swift deleted file mode 100644 index cc8c1b35..00000000 --- a/foundation/FileWrapper.swift +++ /dev/null @@ -1,141 +0,0 @@ -// FileWrapper (Apple's Foundation has it; swift-foundation and corelibs do -// not): a file, a directory of them, or a symbolic link, held in memory, -// read from and written to the file system. What SwiftUI's FileDocument -// hands over. A Swift class, as Isomer's other Foundation classes are -// (Apple's is an NSObject). Also compiled into the SwiftUI of Linux and -// Windows, whose Foundation is the toolchain's: FileManager's own API -// only. In isomer's Swift package the SwiftUI target lists this file -// (shared/swift_ui_corelibs) on every platform, so it is compiled there only -// where SwiftUI's Foundation is the toolchain's. - -#if !ISOMER_SWIFTUI || os(Linux) || os(Windows) -import FoundationEssentials - -open class FileWrapper: @unchecked Sendable { - public struct ReadingOptions: OptionSet, Sendable { - public let rawValue: UInt - public init(rawValue: UInt) { self.rawValue = rawValue } - public static var immediate: ReadingOptions { ReadingOptions(rawValue: 1 << 0) } - public static var withoutMapping: ReadingOptions { ReadingOptions(rawValue: 1 << 1) } - } - - public struct WritingOptions: OptionSet, Sendable { - public let rawValue: UInt - public init(rawValue: UInt) { self.rawValue = rawValue } - public static var atomic: WritingOptions { WritingOptions(rawValue: 1 << 0) } - public static var withNameUpdating: WritingOptions { WritingOptions(rawValue: 1 << 1) } - } - - private enum Kind { - case file(Data) - case directory([String: FileWrapper]) - case link(URL) - } - - private var kind: Kind - open var preferredFilename: String? - open var filename: String? - open var fileAttributes: [String: Any] = [:] - - public init(regularFileWithContents contents: Data) { - kind = .file(contents) - } - - public init(directoryWithFileWrappers childrenByPreferredName: [String: FileWrapper]) { - for (name, child) in childrenByPreferredName where child.preferredFilename == nil { child.preferredFilename = name } - kind = .directory(childrenByPreferredName) - } - - public init(symbolicLinkWithDestinationURL url: URL) { - kind = .link(url) - } - - /// What is at `url` now: a file's contents, or a directory's files read - /// the same way, all at once. - public init(url: URL, options: ReadingOptions = []) throws { - let manager = FileManager.default - let path = url.path - guard let type = (try? manager.attributesOfItem(atPath: path))?[.type] as? FileAttributeType else { - throw CocoaError(.fileReadNoSuchFile) - } - if type == .typeSymbolicLink, let destination = try? manager.destinationOfSymbolicLink(atPath: path) { - kind = .link(URL(fileURLWithPath: destination)) - } else if type == .typeDirectory { - var children: [String: FileWrapper] = [:] - for name in try manager.contentsOfDirectory(atPath: path) { - children[name] = try FileWrapper(url: url.appendingPathComponent(name), options: options) - } - kind = .directory(children) - } else { - kind = .file(try Data(contentsOf: url)) - } - filename = url.lastPathComponent - preferredFilename = url.lastPathComponent - } - - open var isRegularFile: Bool { if case .file = kind { true } else { false } } - open var isDirectory: Bool { if case .directory = kind { true } else { false } } - open var isSymbolicLink: Bool { if case .link = kind { true } else { false } } - - open var regularFileContents: Data? { if case .file(let data) = kind { data } else { nil } } - open var fileWrappers: [String: FileWrapper]? { if case .directory(let children) = kind { children } else { nil } } - open var symbolicLinkDestinationURL: URL? { if case .link(let url) = kind { url } else { nil } } - - /// Adds a child to a directory, under its preferred name (made unique - /// with a number if taken): the name it is under. - @discardableResult - open func addFileWrapper(_ child: FileWrapper) -> String { - guard case .directory(var children) = kind else { return "" } - let wanted = child.preferredFilename ?? "Untitled" - var name = wanted - var number = 2 - while children[name] != nil { - name = "\(number) " + wanted - number += 1 - } - children[name] = child - kind = .directory(children) - return name - } - - @discardableResult - open func addRegularFile(withContents data: Data, preferredFilename fileName: String) -> String { - let child = FileWrapper(regularFileWithContents: data) - child.preferredFilename = fileName - return addFileWrapper(child) - } - - open func removeFileWrapper(_ child: FileWrapper) { - guard case .directory(var children) = kind, let key = keyForChildFileWrapper(child) else { return } - children[key] = nil - kind = .directory(children) - } - - open func keyForChildFileWrapper(_ child: FileWrapper) -> String? { - fileWrappers?.first { $0.value === child }?.key - } - - /// Writes it at `url`: a file's contents, a directory and its files, or - /// a link. - open func write(to url: URL, options: WritingOptions = [], originalContentsURL: URL?) throws { - let manager = FileManager.default - switch kind { - case .file(let data): - #if os(WASI) - // WASI has no temporary files to write atomically through. - try data.write(to: url) - #else - try data.write(to: url, options: options.contains(.atomic) ? .atomic : []) - #endif - case .directory(let children): - try manager.createDirectory(at: url, withIntermediateDirectories: true) - for (name, child) in children { - try child.write(to: url.appendingPathComponent(name), options: options, originalContentsURL: nil) - } - case .link(let destination): - try manager.createSymbolicLink(atPath: url.path, withDestinationPath: destination.path) - } - if options.contains(.withNameUpdating) { filename = url.lastPathComponent } - } -} -#endif diff --git a/foundation/Foundation.swift b/foundation/Foundation.swift deleted file mode 100644 index a07340cc..00000000 --- a/foundation/Foundation.swift +++ /dev/null @@ -1,43 +0,0 @@ -// Isomer's Foundation for the platforms that have no Foundation of Apple's -// (wasm, Android, Linux, Windows): swift-foundation's FoundationEssentials, -// with what corelibs gives Swift code elsewhere (CharacterSet, NSString's -// string API, String(format:) and the rest of this directory), -// FoundationInternationalization when the app asks for it -// (`--@isomer//foundation:internationalization`), and CoreGraphics' geometry, -// which Apple's Foundation re-exports too. There is no corelibs layer: no -// NS classes, CoreFoundation, FoundationNetworking or FoundationXML -// (docs/parity/Foundation.md). URLSession is in this module, as on Apple -// platforms, over the transports a host installs in IsomerFoundation -// (//foundation/isomer_foundation), which this module imports `internal`ly: -// nothing of it reaches an app through `import Foundation`. - -@_exported import CoreGraphics -@_exported import FoundationEssentials - -// As Apple's Foundation re-exports Darwin and Dispatch (and corelibs Glibc): -// code that imports Foundation reaches memcpy, ceil and DispatchQueue. -#if canImport(Glibc) -@_exported import Glibc -#elseif canImport(Musl) -@_exported import Musl -#elseif canImport(Android) -@_exported import Android -#elseif canImport(WASILibc) -@_exported import WASILibc -#elseif canImport(ucrt) -@_exported import ucrt -#endif -#if canImport(Dispatch) -@_exported import Dispatch -#endif -#if canImport(IsomerFoundationInternationalization) -@_exported import IsomerFoundationInternationalization -#endif - -// Dispatch's time constants (NSEC_PER_SEC and its family), which Apple's -// Foundation reaches through Dispatch: neither the Android SDK's libdispatch -// nor WASI (no Dispatch) gives them, so a module of their own does -// (//foundation/dispatch_time), re-exported here as Apple's re-exports Dispatch. -#if os(Android) || os(WASI) -@_exported import IsomerDispatchTime -#endif diff --git a/foundation/HTTPCookieStorage.swift b/foundation/HTTPCookieStorage.swift deleted file mode 100644 index def4a6a5..00000000 --- a/foundation/HTTPCookieStorage.swift +++ /dev/null @@ -1,18 +0,0 @@ -// Cookie and credential storage, as a session's configuration names them -// (`httpCookieStorage`, `urlCredentialStorage`): the types and their shared -// instances, so code that sets or passes them compiles, holding nothing. -// Isomer's sessions send requests through the host's stack (fetch, -// HttpURLConnection, URLSession), which keeps its own cookies and -// credentials; Isomer's keep none of their own (docs/parity/Foundation.md). - -open class HTTPCookieStorage: NSObject, @unchecked Sendable { - open class var shared: HTTPCookieStorage { sharedStorage } - - private static let sharedStorage = HTTPCookieStorage() -} - -open class URLCredentialStorage: NSObject, @unchecked Sendable { - open class var shared: URLCredentialStorage { sharedStorage } - - private static let sharedStorage = URLCredentialStorage() -} diff --git a/foundation/ISO8601DateFormatter.swift b/foundation/ISO8601DateFormatter.swift deleted file mode 100644 index 02282607..00000000 --- a/foundation/ISO8601DateFormatter.swift +++ /dev/null @@ -1,71 +0,0 @@ -// ISO8601DateFormatter (Apple's Foundation and corelibs have it; -// swift-foundation has the format style it is written over): a date as -// ISO 8601 text and back, its fields and separators chosen by `formatOptions`. -// A Swift class, as Isomer's other Foundation classes are (Apple's is a -// Formatter). - -import FoundationEssentials - -open class ISO8601DateFormatter: @unchecked Sendable { - /// Which fields the text has, and how they are separated (Apple's raw - /// values, CFISO8601DateFormatOptions). - public struct Options: OptionSet, Sendable { - public let rawValue: UInt - public init(rawValue: UInt) { self.rawValue = rawValue } - - public static var withYear: Options { Options(rawValue: 1 << 0) } - public static var withMonth: Options { Options(rawValue: 1 << 1) } - public static var withWeekOfYear: Options { Options(rawValue: 1 << 2) } - public static var withDay: Options { Options(rawValue: 1 << 4) } - public static var withTime: Options { Options(rawValue: 1 << 5) } - public static var withTimeZone: Options { Options(rawValue: 1 << 6) } - public static var withSpaceBetweenDateAndTime: Options { Options(rawValue: 1 << 7) } - public static var withDashSeparatorInDate: Options { Options(rawValue: 1 << 8) } - public static var withColonSeparatorInTime: Options { Options(rawValue: 1 << 9) } - public static var withColonSeparatorInTimeZone: Options { Options(rawValue: 1 << 10) } - public static var withFractionalSeconds: Options { Options(rawValue: 1 << 11) } - public static var withFullDate: Options { [.withYear, .withMonth, .withDay, .withDashSeparatorInDate] } - public static var withFullTime: Options { [.withTime, .withColonSeparatorInTime, .withTimeZone, .withColonSeparatorInTimeZone] } - public static var withInternetDateTime: Options { [.withFullDate, .withFullTime] } - } - - /// The time zone the text is in (GMT unless set). - open var timeZone: TimeZone! = TimeZone(secondsFromGMT: 0) - open var formatOptions: Options = .withInternetDateTime - - public init() {} - - open func string(from date: Date) -> String { - Self.style(formatOptions, timeZone ?? TimeZone(secondsFromGMT: 0)!).format(date) - } - - /// The date the text says, or nil when it isn't one in these options. - open func date(from string: String) -> Date? { - try? Self.style(formatOptions, timeZone ?? TimeZone(secondsFromGMT: 0)!).parse(string) - } - - open class func string(from date: Date, timeZone: TimeZone, formatOptions: Options = []) -> String { - style(formatOptions, timeZone).format(date) - } - - /// The format style the options say: its separators, then its fields - /// (a style given no field writes every one). - private static func style(_ options: Options, _ timeZone: TimeZone) -> Date.ISO8601FormatStyle { - var style = Date.ISO8601FormatStyle( - dateSeparator: options.contains(.withDashSeparatorInDate) ? .dash : .omitted, - dateTimeSeparator: options.contains(.withSpaceBetweenDateAndTime) ? .space : .standard, - timeSeparator: options.contains(.withColonSeparatorInTime) ? .colon : .omitted, - timeZoneSeparator: options.contains(.withColonSeparatorInTimeZone) ? .colon : .omitted, - includingFractionalSeconds: options.contains(.withFractionalSeconds), - timeZone: timeZone) - if options.contains(.withYear) { style = style.year() } - if options.contains(.withWeekOfYear) { style = style.weekOfYear() } - if options.contains(.withMonth) { style = style.month() } - if options.contains(.withDay) { style = style.day() } - if options.contains(.withTime) { style = style.time(includingFractionalSeconds: options.contains(.withFractionalSeconds)) } - if options.contains(.withTimeZone) { - style = style.timeZone(separator: options.contains(.withColonSeparatorInTimeZone) ? .colon : .omitted) - } - return style - } -} diff --git a/foundation/IndexSet.swift b/foundation/IndexSet.swift deleted file mode 100644 index e16dc68a..00000000 --- a/foundation/IndexSet.swift +++ /dev/null @@ -1,374 +0,0 @@ -// IndexSet, as Isomer's Foundation has it: a set of non-negative integers -// kept as sorted, non-overlapping ranges, with Apple's Swift API (a -// bidirectional collection of `Int`, set algebra, ranges, shifting). -// swift-foundation leaves IndexSet to swift-corelibs-foundation, where it -// wraps NSIndexSet; this one is Swift. - -import FoundationEssentials - -public struct IndexSet: Hashable, Sendable { - public typealias Element = Int - - /// Sorted, non-overlapping, non-adjacent half-open ranges. - var storage: [Range] - - public init() { - storage = [] - } - - public init(integer: Int) { - storage = [integer..<(integer + 1)] - } - - public init(integersIn range: Range) { - storage = range.isEmpty ? [] : [range] - } - - public init(integersIn range: R) where R.Bound == Int { - self.init(integersIn: range.relative(to: 0.. - let ranges: [Range] - public var startIndex: Int { ranges.startIndex } - public var endIndex: Int { ranges.endIndex } - public subscript(position: Int) -> Range { ranges[position] } - public func index(after i: Int) -> Int { i + 1 } - public func index(before i: Int) -> Int { i - 1 } - } - - public var rangeView: RangeView { RangeView(ranges: storage) } - - /// The set's ranges that overlap `range`, clipped to it. - public func rangeView(of range: Range) -> RangeView { - RangeView(ranges: storage.compactMap { r in - let clipped = r.clamped(to: range) - return clipped.isEmpty ? nil : clipped - }) - } - - public func rangeView(of range: R) -> RangeView where R.Bound == Int { - rangeView(of: range.relative(to: 0.. Bool { - position(of: integer) != nil - } - - public func contains(integersIn range: Range) -> Bool { - if range.isEmpty { return true } - return storage.contains { $0.lowerBound <= range.lowerBound && $0.upperBound >= range.upperBound } - } - - public func contains(integersIn range: R) -> Bool where R.Bound == Int { - contains(integersIn: range.relative(to: 0.. Bool { - indexSet.storage.allSatisfy { contains(integersIn: $0) } - } - - public func intersects(integersIn range: Range) -> Bool { - storage.contains { $0.overlaps(range) } - } - - public func intersects(integersIn range: R) -> Bool where R.Bound == Int { - intersects(integersIn: range.relative(to: 0..) -> Int { - storage.reduce(0) { $0 + $1.clamped(to: range).count } - } - - public func count(in range: R) -> Int where R.Bound == Int { - count(in: range.relative(to: 0.. Int? { - for range in storage where range.upperBound > integer + 1 { - return Swift.max(range.lowerBound, integer + 1) - } - return nil - } - - public func integerGreaterThanOrEqualTo(_ integer: Int) -> Int? { - integerGreaterThan(integer - 1) - } - - public func integerLessThan(_ integer: Int) -> Int? { - for range in storage.reversed() where range.lowerBound < integer { - return Swift.min(range.upperBound, integer) - 1 - } - return nil - } - - public func integerLessThanOrEqualTo(_ integer: Int) -> Int? { - integerLessThan(integer + 1) - } - - // MARK: Changing - - @discardableResult - public mutating func insert(_ integer: Int) -> (inserted: Bool, memberAfterInsert: Int) { - if contains(integer) { return (false, integer) } - insert(integersIn: integer..<(integer + 1)) - return (true, integer) - } - - @discardableResult - public mutating func update(with integer: Int) -> Int? { - let present = contains(integer) - insert(integer) - return present ? integer : nil - } - - public mutating func insert(integersIn range: Range) { - guard !range.isEmpty else { return } - storage = IndexSet.normalized(storage + [range]) - } - - public mutating func insert(integersIn range: R) where R.Bound == Int { - insert(integersIn: range.relative(to: 0.. Int? { - guard contains(integer) else { return nil } - remove(integersIn: integer..<(integer + 1)) - return integer - } - - public mutating func remove(integersIn range: Range) { - guard !range.isEmpty else { return } - var result: [Range] = [] - for r in storage { - if !r.overlaps(range) { - result.append(r) - continue - } - if r.lowerBound < range.lowerBound { result.append(r.lowerBound.. range.upperBound { result.append(range.upperBound..) { - remove(integersIn: Range(range)) - } - - public mutating func removeAll() { - storage = [] - } - - /// Moves every integer at or above `integer` by `delta`. A negative - /// `delta` first removes the integers in `integer + delta ..< integer`. - public mutating func shift(startingAt integer: Int, by delta: Int) { - guard delta != 0 else { return } - if delta < 0 { remove(integersIn: Swift.max(0, integer + delta)..] = [] - for r in storage { - if r.upperBound <= integer { - result.append(r) - } else if r.lowerBound >= integer { - result.append((r.lowerBound + delta)..<(r.upperBound + delta)) - } else { - result.append(r.lowerBound.., includeInteger: (Int) throws -> Bool) rethrows -> IndexSet { - var result = IndexSet() - for integer in self where range.contains(integer) { - if try includeInteger(integer) { result.insert(integer) } - } - return result - } - - public func filteredIndexSet(includeInteger: (Int) throws -> Bool) rethrows -> IndexSet { - var result = IndexSet() - for integer in self where try includeInteger(integer) { - result.insert(integer) - } - return result - } - - // MARK: Helpers - - func position(of integer: Int) -> Int? { - var low = 0 - var high = storage.count - 1 - while low <= high { - let middle = (low + high) / 2 - let range = storage[middle] - if integer < range.lowerBound { - high = middle - 1 - } else if integer >= range.upperBound { - low = middle + 1 - } else { - return middle - } - } - return nil - } - - static func normalized(_ ranges: [Range]) -> [Range] { - var result: [Range] = [] - for range in ranges.filter({ !$0.isEmpty }).sorted(by: { $0.lowerBound < $1.lowerBound }) { - if let last = result.last, range.lowerBound <= last.upperBound { - result[result.count - 1] = last.lowerBound.. Bool { - lhs.rangeIndex < rhs.rangeIndex || (lhs.rangeIndex == rhs.rangeIndex && lhs.value < rhs.value) - } - - public var description: String { "index \(value) in a range \(rangeIndex)" } - } - - public var startIndex: Index { - Index(value: storage.first?.lowerBound ?? 0, rangeIndex: storage.isEmpty ? 0 : 0) - } - - public var endIndex: Index { - Index(value: storage.last?.upperBound ?? 0, rangeIndex: storage.count) - } - - public subscript(position: Index) -> Int { position.value } - - public func index(after i: Index) -> Index { - let next = i.value + 1 - if next < storage[i.rangeIndex].upperBound { - return Index(value: next, rangeIndex: i.rangeIndex) - } - let nextRange = i.rangeIndex + 1 - if nextRange < storage.count { - return Index(value: storage[nextRange].lowerBound, rangeIndex: nextRange) - } - return endIndex - } - - public func index(before i: Index) -> Index { - if i.rangeIndex < storage.count, i.value > storage[i.rangeIndex].lowerBound { - return Index(value: i.value - 1, rangeIndex: i.rangeIndex) - } - let previous = i.rangeIndex - 1 - return Index(value: storage[previous].upperBound - 1, rangeIndex: previous) - } - - public var isEmpty: Bool { storage.isEmpty } - - public func index(of integer: Int) -> Index? { - position(of: integer).map { Index(value: integer, rangeIndex: $0) } - } -} - -// MARK: - Set algebra - -extension IndexSet: SetAlgebra { - public init(arrayLiteral elements: Int...) { - self.init() - for element in elements { insert(element) } - } - - public func union(_ other: IndexSet) -> IndexSet { - var result = IndexSet() - result.storage = IndexSet.normalized(storage + other.storage) - return result - } - - public mutating func formUnion(_ other: IndexSet) { - self = union(other) - } - - public func intersection(_ other: IndexSet) -> IndexSet { - var result: [Range] = [] - var i = 0, j = 0 - while i < storage.count && j < other.storage.count { - let overlap = storage[i].clamped(to: other.storage[j]) - if !overlap.isEmpty { result.append(overlap) } - if storage[i].upperBound < other.storage[j].upperBound { i += 1 } else { j += 1 } - } - var set = IndexSet() - set.storage = result - return set - } - - public mutating func formIntersection(_ other: IndexSet) { - self = intersection(other) - } - - public func subtracting(_ other: IndexSet) -> IndexSet { - var result = self - for range in other.storage { result.remove(integersIn: range) } - return result - } - - public mutating func subtract(_ other: IndexSet) { - self = subtracting(other) - } - - public func symmetricDifference(_ other: IndexSet) -> IndexSet { - subtracting(other).union(other.subtracting(self)) - } - - public mutating func formSymmetricDifference(_ other: IndexSet) { - self = symmetricDifference(other) - } -} - -extension IndexSet: CustomStringConvertible, CustomDebugStringConvertible { - public var description: String { "\(count) indexes" } - public var debugDescription: String { description } -} - -extension IndexSet: Codable { - private enum CodingKeys: String, CodingKey { - case indexes - } - - private struct RangeRecord: Codable { - var location: Int - var length: Int - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let records = try container.decode([RangeRecord].self, forKey: .indexes) - self.init() - storage = IndexSet.normalized(records.map { $0.location..<($0.location + $0.length) }) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(storage.map { RangeRecord(location: $0.lowerBound, length: $0.count) }, forKey: .indexes) - } -} diff --git a/foundation/JSONSerialization.swift b/foundation/JSONSerialization.swift deleted file mode 100644 index 7431d04b..00000000 --- a/foundation/JSONSerialization.swift +++ /dev/null @@ -1,375 +0,0 @@ -// JSONSerialization and NSNull (Apple's Foundation and corelibs have them; -// swift-foundation has JSONEncoder and JSONDecoder): JSON text to and from -// Foundation's untyped values. Objects are [String: Any], arrays [Any], -// strings String, numbers and booleans NSNumber, null NSNull. Written as -// Apple's writes it: slashes escaped unless asked not to, pretty printing -// two spaces deep with " : " after a key. - -import FoundationEssentials - -/// JSON's null, in collections of Foundation's untyped values. -open class NSNull: Hashable, CustomStringConvertible, @unchecked Sendable { - public init() {} - public static func == (lhs: NSNull, rhs: NSNull) -> Bool { true } - public func hash(into hasher: inout Hasher) {} - open var description: String { "" } -} - -open class JSONSerialization: @unchecked Sendable { - public struct ReadingOptions: OptionSet, Sendable { - public let rawValue: UInt - public init(rawValue: UInt) { self.rawValue = rawValue } - public static var mutableContainers: ReadingOptions { ReadingOptions(rawValue: 1 << 0) } - public static var mutableLeaves: ReadingOptions { ReadingOptions(rawValue: 1 << 1) } - public static var fragmentsAllowed: ReadingOptions { ReadingOptions(rawValue: 1 << 2) } - public static var json5Allowed: ReadingOptions { ReadingOptions(rawValue: 1 << 3) } - public static var topLevelDictionaryAssumed: ReadingOptions { ReadingOptions(rawValue: 1 << 4) } - } - - public struct WritingOptions: OptionSet, Sendable { - public let rawValue: UInt - public init(rawValue: UInt) { self.rawValue = rawValue } - public static var prettyPrinted: WritingOptions { WritingOptions(rawValue: 1 << 0) } - public static var sortedKeys: WritingOptions { WritingOptions(rawValue: 1 << 1) } - public static var fragmentsAllowed: WritingOptions { WritingOptions(rawValue: 1 << 2) } - public static var withoutEscapingSlashes: WritingOptions { WritingOptions(rawValue: 1 << 3) } - } - - /// Whether `obj` can be written: an array or an object at the top, - /// holding only JSON's values, objects keyed by strings, numbers finite. - open class func isValidJSONObject(_ obj: Any) -> Bool { - guard obj is [Any] || obj is [String: Any] || obj is [AnyHashable: Any] else { return false } - var writer = Writer(options: []) - return (try? writer.write(obj)) != nil - } - - open class func data(withJSONObject obj: Any, options opt: WritingOptions = []) throws -> Data { - if !opt.contains(.fragmentsAllowed), !(obj is [Any] || obj is [String: Any] || obj is [AnyHashable: Any]) { - throw CocoaError(.propertyListWriteInvalid) - } - var writer = Writer(options: opt) - try writer.write(obj) - return Data(writer.text.utf8) - } - - open class func jsonObject(with data: Data, options opt: ReadingOptions = []) throws -> Any { - var reader = Reader(bytes: Array(data)) - reader.skipWhitespace() - let value = try reader.value() - reader.skipWhitespace() - guard reader.atEnd else { throw Reader.corrupt("Garbage at end around line \(reader.line).") } - if !opt.contains(.fragmentsAllowed), !(value is [Any] || value is [String: Any]) { - throw Reader.corrupt("JSON text did not start with array or object and option to allow fragments not set.") - } - return value - } - - // MARK: Writing - - private struct Writer { - let options: WritingOptions - var text = "" - var depth = 0 - - init(options: WritingOptions) { self.options = options } - - mutating func write(_ value: Any) throws { - switch value { - case let string as String: writeString(string) - case let number as NSNumber: try writeNumber(number) - case let bool as Bool: text += bool ? "true" : "false" - case let int as Int: text += String(int) - case let int as Int8: text += String(int) - case let int as Int16: text += String(int) - case let int as Int32: text += String(int) - case let int as Int64: text += String(int) - case let int as UInt: text += String(int) - case let int as UInt8: text += String(int) - case let int as UInt16: text += String(int) - case let int as UInt32: text += String(int) - case let int as UInt64: text += String(int) - case let double as Double: try writeDouble(double) - case let float as Float: try writeDouble(Double(float)) - case is NSNull: text += "null" - case let array as [Any]: try writeArray(array) - case let object as [String: Any]: try writeObject(object.map { ($0.key, $0.value) }) - case let object as [AnyHashable: Any]: - var pairs: [(String, Any)] = [] - for (key, value) in object { - guard let key = key.base as? String else { throw CocoaError(.propertyListWriteInvalid) } - pairs.append((key, value)) - } - try writeObject(pairs) - default: - // An Optional's nil (`name as Any`, a nil String?: a cast - // above unwraps one that holds a value), or anything else - // JSON has no word for. - let mirror = Mirror(reflecting: value) - if mirror.displayStyle == .optional, mirror.children.isEmpty { text += "null"; return } - throw CocoaError(.propertyListWriteInvalid) - } - } - - mutating func writeNumber(_ number: NSNumber) throws { - guard let json = number.jsonText else { throw CocoaError(.propertyListWriteInvalid) } - text += json - } - - mutating func writeDouble(_ double: Double) throws { - guard let json = NSNumber.jsonText(of: double) else { throw CocoaError(.propertyListWriteInvalid) } - text += json - } - - mutating func writeString(_ string: String) { - text += "\"" - for scalar in string.unicodeScalars { - switch scalar { - case "\"": text += "\\\"" - case "\\": text += "\\\\" - case "/": text += options.contains(.withoutEscapingSlashes) ? "/" : "\\/" - case "\n": text += "\\n" - case "\r": text += "\\r" - case "\t": text += "\\t" - case "\u{08}": text += "\\b" - case "\u{0C}": text += "\\f" - default: - if scalar.value < 0x20 { - let hex = String(scalar.value, radix: 16) - text += "\\u" + String(repeating: "0", count: 4 - hex.count) + hex - } else { - text.unicodeScalars.append(scalar) - } - } - } - text += "\"" - } - - mutating func writeArray(_ array: [Any]) throws { - text += "[" - depth += 1 - for (index, element) in array.enumerated() { - if index > 0 { text += "," } - newline() - try write(element) - } - depth -= 1 - if !array.isEmpty { newline() } - text += "]" - } - - mutating func writeObject(_ pairs: [(String, Any)]) throws { - let ordered = options.contains(.sortedKeys) ? pairs.sorted { $0.0 < $1.0 } : pairs - text += "{" - depth += 1 - for (index, pair) in ordered.enumerated() { - if index > 0 { text += "," } - newline() - writeString(pair.0) - text += options.contains(.prettyPrinted) ? " : " : ":" - try write(pair.1) - } - depth -= 1 - if !ordered.isEmpty { newline() } - text += "}" - } - - mutating func newline() { - guard options.contains(.prettyPrinted) else { return } - text += "\n" + String(repeating: " ", count: depth) - } - } - - // MARK: Reading - - private struct Reader { - let bytes: [UInt8] - var index = 0 - var line = 1 - - init(bytes: [UInt8]) { self.bytes = bytes } - - var atEnd: Bool { index >= bytes.count } - - static func corrupt(_ reason: String) -> CocoaError { - CocoaError(.propertyListReadCorrupt, userInfo: [NSDebugDescriptionErrorKey: reason]) - } - - mutating func skipWhitespace() { - while index < bytes.count { - switch bytes[index] { - case 0x20, 0x09, 0x0D: index += 1 - case 0x0A: index += 1; line += 1 - default: return - } - } - } - - mutating func value() throws -> Any { - guard index < bytes.count else { throw Self.corrupt("Unexpected end of file during JSON parse.") } - switch bytes[index] { - case UInt8(ascii: "{"): return try object() - case UInt8(ascii: "["): return try array() - case UInt8(ascii: "\""): return try string() - case UInt8(ascii: "t"): try literal("true"); return NSNumber(value: true) - case UInt8(ascii: "f"): try literal("false"); return NSNumber(value: false) - case UInt8(ascii: "n"): try literal("null"); return NSNull() - default: return try number() - } - } - - mutating func literal(_ word: String) throws { - for byte in word.utf8 { - guard index < bytes.count, bytes[index] == byte else { throw Self.corrupt("Invalid value around line \(line).") } - index += 1 - } - } - - mutating func object() throws -> [String: Any] { - index += 1 - var object: [String: Any] = [:] - skipWhitespace() - if index < bytes.count, bytes[index] == UInt8(ascii: "}") { index += 1; return object } - while true { - skipWhitespace() - guard index < bytes.count, bytes[index] == UInt8(ascii: "\"") else { - throw Self.corrupt("No string key for value in object around line \(line).") - } - let key = try string() - skipWhitespace() - guard index < bytes.count, bytes[index] == UInt8(ascii: ":") else { - throw Self.corrupt("No value for key in object around line \(line).") - } - index += 1 - skipWhitespace() - object[key] = try value() - skipWhitespace() - guard index < bytes.count else { throw Self.corrupt("Unexpected end of file during JSON parse.") } - if bytes[index] == UInt8(ascii: ",") { index += 1; continue } - if bytes[index] == UInt8(ascii: "}") { index += 1; return object } - throw Self.corrupt("Badly formed object around line \(line).") - } - } - - mutating func array() throws -> [Any] { - index += 1 - var array: [Any] = [] - skipWhitespace() - if index < bytes.count, bytes[index] == UInt8(ascii: "]") { index += 1; return array } - while true { - skipWhitespace() - array.append(try value()) - skipWhitespace() - guard index < bytes.count else { throw Self.corrupt("Unexpected end of file during JSON parse.") } - if bytes[index] == UInt8(ascii: ",") { index += 1; continue } - if bytes[index] == UInt8(ascii: "]") { index += 1; return array } - throw Self.corrupt("Badly formed array around line \(line).") - } - } - - mutating func string() throws -> String { - index += 1 - var scalars = String.UnicodeScalarView() - var run = index - func flush(_ end: Int, into scalars: inout String.UnicodeScalarView) { - if end > run { scalars.append(contentsOf: String(decoding: bytes[run.. UInt32 { - guard index + 4 < bytes.count else { throw Self.corrupt("Invalid unicode escape around line \(line).") } - var code: UInt32 = 0 - for offset in 1...4 { - guard let digit = Character(Unicode.Scalar(bytes[index + offset])).hexDigitValue else { - throw Self.corrupt("Invalid unicode escape around line \(line).") - } - code = code * 16 + UInt32(digit) - } - index += 4 - return code - } - - mutating func number() throws -> NSNumber { - let start = index - var integral = true - while index < bytes.count, Self.numberBytes.contains(bytes[index]) { - switch bytes[index] { - case UInt8(ascii: "."), UInt8(ascii: "e"), UInt8(ascii: "E"): integral = false - default: break - } - index += 1 - } - let text = String(decoding: bytes[start.. = Set("0123456789.eE+-".utf8) - } -} - -extension NSNumber { - /// How JSONSerialization writes this number: a boolean as true or - /// false, an integer as its digits, a double as short as reads back the - /// same (nil for one JSON can't hold: not finite). - var jsonText: String? { - if let flag = boolStorage { return flag ? "true" : "false" } - if isFloatingStorage { return Self.jsonText(of: doubleValue) } - return isUnsignedStorage ? String(uint64Value) : String(int64Value) - } - - static func jsonText(of double: Double) -> String? { - guard double.isFinite else { return nil } - if double == double.rounded(), abs(double) < 1e15 { return String(Int64(double)) } - return "\(double)" - } -} diff --git a/foundation/Locks.swift b/foundation/Locks.swift deleted file mode 100644 index a73c668d..00000000 --- a/foundation/Locks.swift +++ /dev/null @@ -1,184 +0,0 @@ -// NSLock and NSRecursiveLock (Apple's Foundation and corelibs have them; -// swift-foundation does not), over a pthread mutex. A WebAssembly program -// without threads has nothing to exclude: there they only count. - -import FoundationEssentials -#if canImport(Android) -import Android -#elseif canImport(Glibc) -import Glibc -#elseif canImport(WASILibc) -import WASILibc -#if _runtime(_multithreaded) -import wasi_pthread -#endif -#endif - -public protocol NSLocking { - func lock() - func unlock() -} - -extension NSLocking { - public func withLock(_ body: () throws -> R) rethrows -> R { - lock() - defer { unlock() } - return try body() - } -} - -#if os(WASI) && !_runtime(_multithreaded) -/// One thread: a lock is always free when asked for. -private final class _Mutex: @unchecked Sendable { - private var depth = 0 - init(recursive: Bool) {} - func lock() { depth += 1 } - func unlock() { depth -= 1 } - func tryLock() -> Bool { - depth += 1 - return true - } -} -#else -private final class _Mutex: @unchecked Sendable { - private let mutex = UnsafeMutablePointer.allocate(capacity: 1) - - init(recursive: Bool) { - var attributes = pthread_mutexattr_t() - pthread_mutexattr_init(&attributes) - if recursive { - pthread_mutexattr_settype(&attributes, Int32(PTHREAD_MUTEX_RECURSIVE)) - } - pthread_mutex_init(mutex, &attributes) - pthread_mutexattr_destroy(&attributes) - } - - deinit { - pthread_mutex_destroy(mutex) - mutex.deallocate() - } - - func lock() { pthread_mutex_lock(mutex) } - func unlock() { pthread_mutex_unlock(mutex) } - func tryLock() -> Bool { pthread_mutex_trylock(mutex) == 0 } -} -#endif - -open class NSLock: NSLocking, @unchecked Sendable { - private let mutex = _Mutex(recursive: false) - open var name: String? - - public init() {} - - open func lock() { - mutex.lock() - } - - open func unlock() { - mutex.unlock() - } - - open func `try`() -> Bool { - mutex.tryLock() - } - - /// Tries until `limit`, a few milliseconds apart. - open func lock(before limit: Date) -> Bool { - repeat { - if mutex.tryLock() { return true } - #if !os(WASI) - usleep(1000) - #endif - } while Date() < limit - return false - } -} - -open class NSRecursiveLock: NSLocking, @unchecked Sendable { - private let mutex = _Mutex(recursive: true) - open var name: String? - - public init() {} - - open func lock() { - mutex.lock() - } - - open func unlock() { - mutex.unlock() - } - - open func `try`() -> Bool { - mutex.tryLock() - } - - open func lock(before limit: Date) -> Bool { - repeat { - if mutex.tryLock() { return true } - #if !os(WASI) - usleep(1000) - #endif - } while Date() < limit - return false - } -} - -/// A lock with a condition to wait on (pthread's mutex and condition -/// variable). Without threads, waiting returns at once: no other thread -/// could signal. -open class NSCondition: NSLocking, @unchecked Sendable { - open var name: String? - #if os(WASI) && !_runtime(_multithreaded) - public init() {} - open func lock() {} - open func unlock() {} - open func wait() {} - open func wait(until limit: Date) -> Bool { false } - open func signal() {} - open func broadcast() {} - #else - private let mutex = UnsafeMutablePointer.allocate(capacity: 1) - private let condition = UnsafeMutablePointer.allocate(capacity: 1) - - public init() { - pthread_mutex_init(mutex, nil) - pthread_cond_init(condition, nil) - } - - deinit { - pthread_cond_destroy(condition) - pthread_mutex_destroy(mutex) - condition.deallocate() - mutex.deallocate() - } - - open func lock() { - pthread_mutex_lock(mutex) - } - - open func unlock() { - pthread_mutex_unlock(mutex) - } - - open func wait() { - pthread_cond_wait(condition, mutex) - } - - /// False when `limit` passed first. - open func wait(until limit: Date) -> Bool { - let seconds = limit.timeIntervalSince1970 - var deadline = timespec() - deadline.tv_sec = time_t(seconds) - deadline.tv_nsec = Int((seconds - Double(Int(seconds))) * 1_000_000_000) - return pthread_cond_timedwait(condition, mutex, &deadline) == 0 - } - - open func signal() { - pthread_cond_signal(condition) - } - - open func broadcast() { - pthread_cond_broadcast(condition) - } - #endif -} diff --git a/foundation/NSError.swift b/foundation/NSError.swift deleted file mode 100644 index be25b15c..00000000 --- a/foundation/NSError.swift +++ /dev/null @@ -1,172 +0,0 @@ -// NSError, as Apple's Foundation has it: an error's domain, code and user -// info, and `error as NSError` for any Swift error (the compiler calls -// `_convertErrorToNSError` for it, as it does with corelibs Foundation). -// Off Apple platforms the errors themselves stay Swift values (URLError, -// CocoaError, POSIXError, an app's own); an NSError is made from one when -// asked for, keeps it, and `as?` back from the NSError finds it again. - -import FoundationEssentials - -// MARK: - Keys and domains - -/// The user info's description of the error, for a person. -public let NSLocalizedDescriptionKey = "NSLocalizedDescription" -/// Why the error happened, for a person. -public let NSLocalizedFailureReasonErrorKey = "NSLocalizedFailureReason" -/// What a person might do about it. -public let NSLocalizedRecoverySuggestionErrorKey = "NSLocalizedRecoverySuggestion" -/// The help anchor for the error. -public let NSHelpAnchorErrorKey = "NSHelpAnchor" -/// The error that led to this one. -public let NSUnderlyingErrorKey = "NSUnderlyingError" -/// The errors that led to this one, as an array. -public let NSMultipleUnderlyingErrorsKey = "NSMultipleUnderlyingErrorsKey" -/// A description for a developer, not a person. -public let NSDebugDescriptionErrorKey = "NSDebugDescription" -/// The errors Foundation's own APIs throw. -public let NSCocoaErrorDomain = "NSCocoaErrorDomain" -/// The errors of POSIX calls (`errno`). -public let NSPOSIXErrorDomain = "NSPOSIXErrorDomain" -/// The errors of URL loading. -public let NSURLErrorDomain = "NSURLErrorDomain" - -// MARK: - CustomNSError - -/// An error that says its own domain, code and user info, as an NSError -/// made from it has them. -public protocol CustomNSError: Error { - /// The domain of the error. - static var errorDomain: String { get } - /// The error code within the domain. - var errorCode: Int { get } - /// The user info dictionary. - var errorUserInfo: [String: Any] { get } -} - -extension CustomNSError { - /// The type's fully qualified name. - public static var errorDomain: String { String(reflecting: self) } - - /// The code Swift gives the error (an enum's case number). - public var errorCode: Int { _code } - - /// None. - public var errorUserInfo: [String: Any] { [:] } -} - -extension CustomNSError where Self: RawRepresentable, Self.RawValue: FixedWidthInteger { - /// The raw value. - public var errorCode: Int { numericCast(rawValue) } -} - -extension URLError: CustomNSError {} - -// MARK: - NSError - -/// An error's domain, code and user info. -open class NSError: Error, @unchecked Sendable { - private let errorDomain: String - private let errorCode: Int - private let errorUserInfo: [String: Any] - /// The Swift error this one was made from (`error as NSError`), which - /// `as?` finds again. - fileprivate var swiftError: (any Error)? - - public init(domain: String, code: Int, userInfo dict: [String: Any]? = nil) { - errorDomain = domain - errorCode = code - errorUserInfo = dict ?? [:] - } - - /// The error's domain. - open var domain: String { errorDomain } - - /// The error's code within its domain. - open var code: Int { errorCode } - - /// The error's user info. - open var userInfo: [String: Any] { errorUserInfo } - - /// The error described for a person: the user info's description, else - /// that of the Swift error it was made from, else "The operation - /// couldn’t be completed." with the domain and code. - open var localizedDescription: String { - if let description = userInfo[NSLocalizedDescriptionKey] as? String { return description } - if let swiftError { return swiftError.localizedDescription } - return "The operation couldn’t be completed. (\(domain) error \(code).)" - } - - /// Why the error happened, if the user info says. - open var localizedFailureReason: String? { - userInfo[NSLocalizedFailureReasonErrorKey] as? String ?? (swiftError as? any LocalizedError)?.failureReason - } - - /// What a person might do about it, if the user info says. - open var localizedRecoverySuggestion: String? { - userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String ?? (swiftError as? any LocalizedError)?.recoverySuggestion - } - - /// The help anchor, if the user info has one. - open var helpAnchor: String? { - userInfo[NSHelpAnchorErrorKey] as? String ?? (swiftError as? any LocalizedError)?.helpAnchor - } - - /// The errors that led to this one: the user info's underlying error, - /// then its multiple underlying errors. - open var underlyingErrors: [any Error] { - var errors: [any Error] = [] - if let underlying = userInfo[NSUnderlyingErrorKey] as? any Error { errors.append(underlying) } - if let more = userInfo[NSMultipleUnderlyingErrorsKey] as? [any Error] { errors.append(contentsOf: more) } - return errors - } - - public var _domain: String { domain } - - public var _code: Int { code } -} - -// MARK: - Bridging - -/// The error itself when it is an NSError, else nil. Not `as? NSError`: -/// that bridges, making an NSError of any error (through the function -/// below), so it always succeeds. -func _existingNSError(_ error: any Error) -> NSError? { - guard type(of: error) is NSError.Type else { return nil } - return unsafeDowncast(error as AnyObject, to: NSError.self) -} - -/// The NSError for a Swift error (`error as NSError`): the error itself if -/// it is one; else its domain, code and user info (a CustomNSError's own, -/// CocoaError's and POSIXError's, a LocalizedError's words), kept with the -/// error for `as?` back. -public func _convertErrorToNSError(_ error: any Error) -> NSError { - if let error = _existingNSError(error) { return error } - let made: NSError - if let error = error as? any CustomNSError { - made = NSError(domain: type(of: error).errorDomain, code: error.errorCode, userInfo: error.errorUserInfo) - } else if let error = error as? CocoaError { - made = NSError(domain: CocoaError.errorDomain, code: error.code.rawValue, userInfo: error.userInfo) - } else if let error = error as? POSIXError { - made = NSError(domain: POSIXError.errorDomain, code: Int(error.code.rawValue)) - } else { - var userInfo: [String: Any] = [:] - if let error = error as? any LocalizedError { - userInfo[NSLocalizedDescriptionKey] = error.errorDescription - userInfo[NSLocalizedFailureReasonErrorKey] = error.failureReason - userInfo[NSLocalizedRecoverySuggestionErrorKey] = error.recoverySuggestion - userInfo[NSHelpAnchorErrorKey] = error.helpAnchor - } - made = NSError(domain: error._domain, code: error._code, userInfo: userInfo) - } - made.swiftError = error - return made -} - -/// The Swift error an NSError stands for: the one it was made from, else -/// the NSError itself. -public func _convertNSErrorToError(_ error: NSError?) -> any Error { - if let error { - return error.swiftError ?? error - } - return NSError(domain: "Foundation._GenericObjCError", code: 0) -} diff --git a/foundation/NSNumber.swift b/foundation/NSNumber.swift deleted file mode 100644 index 087b82c6..00000000 --- a/foundation/NSNumber.swift +++ /dev/null @@ -1,132 +0,0 @@ -// NSNumber (Apple's Foundation and corelibs have it; swift-foundation does -// not): a number of any of Swift's numeric types, read back as any. A Swift -// class; Swift's numbers bridge to it as Apple's do (NSNumberBridging.swift: -// `as? Int` on an NSNumber is exact, `intValue` truncates). - -import FoundationEssentials - -open class NSNumber: Hashable, CustomStringConvertible, ExpressibleByIntegerLiteral, - ExpressibleByFloatLiteral, ExpressibleByBooleanLiteral, @unchecked Sendable { - enum Storage: Hashable { - case signed(Int64) - case unsigned(UInt64) - case floating(Double) - case boolean(Bool) - } - - let storage: Storage - - public init(value: Int) { storage = .signed(Int64(value)) } - public init(value: Int8) { storage = .signed(Int64(value)) } - public init(value: Int16) { storage = .signed(Int64(value)) } - public init(value: Int32) { storage = .signed(Int64(value)) } - public init(value: Int64) { storage = .signed(value) } - public init(value: UInt) { storage = .unsigned(UInt64(value)) } - public init(value: UInt8) { storage = .unsigned(UInt64(value)) } - public init(value: UInt16) { storage = .unsigned(UInt64(value)) } - public init(value: UInt32) { storage = .unsigned(UInt64(value)) } - public init(value: UInt64) { storage = .unsigned(value) } - public init(value: Float) { storage = .floating(Double(value)) } - public init(value: Double) { storage = .floating(value) } - public init(value: Bool) { storage = .boolean(value) } - - /// What the number was made from, for JSONSerialization's writing. - var boolStorage: Bool? { if case .boolean(let v) = storage { v } else { nil } } - var isFloatingStorage: Bool { if case .floating = storage { true } else { false } } - var isUnsignedStorage: Bool { if case .unsigned = storage { true } else { false } } - - public required convenience init(integerLiteral value: Int) { self.init(value: value) } - public required convenience init(floatLiteral value: Double) { self.init(value: value) } - public required convenience init(booleanLiteral value: Bool) { self.init(value: value) } - - open var int64Value: Int64 { - switch storage { - case .signed(let v): return v - case .unsigned(let v): return Int64(truncatingIfNeeded: v) - case .floating(let v): return v.isFinite ? Int64(v.rounded(.towardZero).clamped(-9.2e18, 9.2e18)) : 0 - case .boolean(let v): return v ? 1 : 0 - } - } - - open var uint64Value: UInt64 { - switch storage { - case .unsigned(let v): return v - case .signed(let v): return UInt64(truncatingIfNeeded: v) - case .floating(let v): return v.isFinite && v > 0 ? UInt64(v.rounded(.towardZero).clamped(0, 1.8e19)) : 0 - case .boolean(let v): return v ? 1 : 0 - } - } - - open var doubleValue: Double { - switch storage { - case .signed(let v): return Double(v) - case .unsigned(let v): return Double(v) - case .floating(let v): return v - case .boolean(let v): return v ? 1 : 0 - } - } - - open var boolValue: Bool { - switch storage { - case .boolean(let v): return v - case .floating(let v): return v != 0 - default: return int64Value != 0 - } - } - - open var intValue: Int { Int(truncatingIfNeeded: int64Value) } - open var int8Value: Int8 { Int8(truncatingIfNeeded: int64Value) } - open var int16Value: Int16 { Int16(truncatingIfNeeded: int64Value) } - open var int32Value: Int32 { Int32(truncatingIfNeeded: int64Value) } - open var uintValue: UInt { UInt(truncatingIfNeeded: uint64Value) } - open var uint8Value: UInt8 { UInt8(truncatingIfNeeded: uint64Value) } - open var uint16Value: UInt16 { UInt16(truncatingIfNeeded: uint64Value) } - open var uint32Value: UInt32 { UInt32(truncatingIfNeeded: uint64Value) } - open var floatValue: Float { Float(doubleValue) } - - open var stringValue: String { - switch storage { - case .signed(let v): return String(v) - case .unsigned(let v): return String(v) - case .floating(let v): return v == v.rounded() && abs(v) < 1e15 ? String(Int64(v)) : String(v) - case .boolean(let v): return v ? "1" : "0" - } - } - - open var description: String { stringValue } - - open func compare(_ otherNumber: NSNumber) -> ComparisonResult { - let a = doubleValue, b = otherNumber.doubleValue - return a < b ? .orderedAscending : a > b ? .orderedDescending : .orderedSame - } - - open func isEqual(to number: NSNumber) -> Bool { - compare(number) == .orderedSame - } - - public static func == (a: NSNumber, b: NSNumber) -> Bool { - a.isEqual(to: b) - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(doubleValue) - } -} - -extension Double { - fileprivate func clamped(_ low: Double, _ high: Double) -> Double { - Swift.min(Swift.max(self, low), high) - } -} - -extension Int { - public init(truncating number: NSNumber) { self = number.intValue } -} - -extension Double { - public init(truncating number: NSNumber) { self = number.doubleValue } -} - -extension Bool { - public init(truncating number: NSNumber) { self = number.boolValue } -} diff --git a/foundation/NSNumberBridging.swift b/foundation/NSNumberBridging.swift deleted file mode 100644 index f20bc974..00000000 --- a/foundation/NSNumberBridging.swift +++ /dev/null @@ -1,407 +0,0 @@ -// `as? Int` (and the other numbers) on an NSNumber, as Apple's Foundation -// has it: each number type bridges to NSNumber, and Swift's runtime casts -// through `_ObjectiveCBridgeable` on every platform, Objective-C or not. A -// cast succeeds only when the number is exactly one of the type (SE-0170): -// `2.5 as? Int` is nil, `1 as? Double` 1.0, `true as? Int` 1; a Double that -// isn't exactly a Float becomes the nearest one, as Apple's does. What -// JSONSerialization reads, `json["count"] as? Int`, works so. - -import FoundationEssentials - -extension NSNumber { - /// The number as `T`, when it is exactly one. - func exactly(_: T.Type) -> T? { - switch storage { - case .signed(let v): return T(exactly: v) - case .unsigned(let v): return T(exactly: v) - case .floating(let v): return T(exactly: v) - case .boolean(let v): return v ? 1 : 0 - } - } - - /// The number as `T`, when it is exactly one (a Double within a - /// Float's range is one, rounded). - func exactly(_: T.Type) -> T? { - switch storage { - case .signed(let v): return T(exactly: v) - case .unsigned(let v): return T(exactly: v) - case .floating(let v): - if v.isNaN { return T.nan } - if let exact = T(exactly: v) { return exact } - return abs(v) <= Double(T.greatestFiniteMagnitude) || v.isInfinite ? T(v) : nil - case .boolean(let v): return v ? 1 : 0 - } - } -} - -extension Bool { - /// True for a number that is 1 (or true), false for 0 (or false), else nil. - public init?(exactly number: NSNumber) { - if let value = number.boolStorage { - self = value - } else if number.doubleValue == 1 { - self = true - } else if number.doubleValue == 0 { - self = false - } else { - return nil - } - } -} - -extension Int { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(Int.self) else { return nil } - self = value - } -} - -extension Int: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Int?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Int?) -> Bool { - result = Int(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int { - guard let source, let value = Int(exactly: source) else { fatalError("Unable to bridge NSNumber to Int") } - return value - } -} - -extension Int8 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(Int8.self) else { return nil } - self = value - } -} - -extension Int8: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Int8?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Int8?) -> Bool { - result = Int8(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int8 { - guard let source, let value = Int8(exactly: source) else { fatalError("Unable to bridge NSNumber to Int8") } - return value - } -} - -extension Int16 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(Int16.self) else { return nil } - self = value - } -} - -extension Int16: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Int16?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Int16?) -> Bool { - result = Int16(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int16 { - guard let source, let value = Int16(exactly: source) else { fatalError("Unable to bridge NSNumber to Int16") } - return value - } -} - -extension Int32 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(Int32.self) else { return nil } - self = value - } -} - -extension Int32: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Int32?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Int32?) -> Bool { - result = Int32(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int32 { - guard let source, let value = Int32(exactly: source) else { fatalError("Unable to bridge NSNumber to Int32") } - return value - } -} - -extension Int64 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(Int64.self) else { return nil } - self = value - } -} - -extension Int64: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Int64?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Int64?) -> Bool { - result = Int64(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int64 { - guard let source, let value = Int64(exactly: source) else { fatalError("Unable to bridge NSNumber to Int64") } - return value - } -} - -extension UInt { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(UInt.self) else { return nil } - self = value - } -} - -extension UInt: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt?) -> Bool { - result = UInt(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt { - guard let source, let value = UInt(exactly: source) else { fatalError("Unable to bridge NSNumber to UInt") } - return value - } -} - -extension UInt8 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(UInt8.self) else { return nil } - self = value - } -} - -extension UInt8: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt8?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt8?) -> Bool { - result = UInt8(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt8 { - guard let source, let value = UInt8(exactly: source) else { fatalError("Unable to bridge NSNumber to UInt8") } - return value - } -} - -extension UInt16 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(UInt16.self) else { return nil } - self = value - } -} - -extension UInt16: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt16?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt16?) -> Bool { - result = UInt16(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt16 { - guard let source, let value = UInt16(exactly: source) else { fatalError("Unable to bridge NSNumber to UInt16") } - return value - } -} - -extension UInt32 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(UInt32.self) else { return nil } - self = value - } -} - -extension UInt32: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt32?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt32?) -> Bool { - result = UInt32(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt32 { - guard let source, let value = UInt32(exactly: source) else { fatalError("Unable to bridge NSNumber to UInt32") } - return value - } -} - -extension UInt64 { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(UInt64.self) else { return nil } - self = value - } -} - -extension UInt64: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt64?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout UInt64?) -> Bool { - result = UInt64(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt64 { - guard let source, let value = UInt64(exactly: source) else { fatalError("Unable to bridge NSNumber to UInt64") } - return value - } -} - -extension Float { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(Float.self) else { return nil } - self = value - } -} - -extension Float: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Float?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Float?) -> Bool { - result = Float(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Float { - guard let source, let value = Float(exactly: source) else { fatalError("Unable to bridge NSNumber to Float") } - return value - } -} - -extension Double { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(Double.self) else { return nil } - self = value - } -} - -extension Double: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Double?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Double?) -> Bool { - result = Double(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Double { - guard let source, let value = Double(exactly: source) else { fatalError("Unable to bridge NSNumber to Double") } - return value - } -} - -extension CGFloat { - public init?(exactly number: NSNumber) { - guard let value = number.exactly(CGFloat.self) else { return nil } - self = value - } -} - -extension CGFloat: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: Double(self)) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout CGFloat?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout CGFloat?) -> Bool { - result = CGFloat(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> CGFloat { - guard let source, let value = CGFloat(exactly: source) else { fatalError("Unable to bridge NSNumber to CGFloat") } - return value - } -} - -extension Bool: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSNumber { NSNumber(value: self) } - - public static func _forceBridgeFromObjectiveC(_ source: NSNumber, result: inout Bool?) { - result = _unconditionallyBridgeFromObjectiveC(source) - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ source: NSNumber, result: inout Bool?) -> Bool { - result = Bool(exactly: source) - return result != nil - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Bool { - guard let source, let value = Bool(exactly: source) else { fatalError("Unable to bridge NSNumber to Bool") } - return value - } -} diff --git a/foundation/NSObject.swift b/foundation/NSObject.swift deleted file mode 100644 index fb4f3c3b..00000000 --- a/foundation/NSObject.swift +++ /dev/null @@ -1,39 +0,0 @@ -// NSObject and NSObjectProtocol, without the Objective-C runtime: what Swift -// code asks of them (a model class that subclasses NSObject, a type checked -// against NSObjectProtocol), as swift-corelibs-foundation has them. Equal by -// identity unless a subclass says otherwise, its hash from its identity, -// described by its type and address. No selectors, key-value coding or -// messaging: Isomer's Foundation has no runtime to send them through. -// Isomer's own classes (Bundle, URLSessionTask, …) are plain Swift classes -// and don't subclass it. - -/// What every NSObject answers. -public protocol NSObjectProtocol: AnyObject { - func isEqual(_ object: Any?) -> Bool - var hash: Int { get } - var description: String { get } -} - -open class NSObject: NSObjectProtocol, Hashable, CustomStringConvertible, CustomDebugStringConvertible { - public init() {} - - /// The same object; a subclass compares what it holds. - open func isEqual(_ object: Any?) -> Bool { - guard let other = object as? NSObject else { return false } - return other === self - } - - /// Its identity's, unless a subclass that overrides `isEqual(_:)` - /// overrides this too (objects that are equal hash alike). - open var hash: Int { ObjectIdentifier(self).hashValue } - - open var description: String { - "<\(type(of: self)): 0x\(String(UInt(bitPattern: Unmanaged.passUnretained(self).toOpaque()), radix: 16))>" - } - - open var debugDescription: String { description } - - public static func == (lhs: NSObject, rhs: NSObject) -> Bool { lhs.isEqual(rhs) } - - public func hash(into hasher: inout Hasher) { hasher.combine(hash) } -} diff --git a/foundation/NSRange.swift b/foundation/NSRange.swift deleted file mode 100644 index ad2db12a..00000000 --- a/foundation/NSRange.swift +++ /dev/null @@ -1,127 +0,0 @@ -// NSRange: a location and a length, in UTF-16 code units when it is a -// string's (as Apple's Foundation and corelibs have it; swift-foundation -// has none), with the conversions to and from a string's indices. - -import FoundationEssentials - -public struct _NSRange: Hashable, Sendable { - public var location: Int - public var length: Int - - public init() { - location = 0 - length = 0 - } - - public init(location: Int, length: Int) { - self.location = location - self.length = length - } -} - -public typealias NSRange = _NSRange -public typealias NSRangePointer = UnsafeMutablePointer - -/// A location that is no location. -public let NSNotFound: Int = .max - -public func NSMakeRange(_ location: Int, _ length: Int) -> NSRange { - NSRange(location: location, length: length) -} - -public func NSMaxRange(_ range: NSRange) -> Int { - range.location + range.length -} - -public func NSLocationInRange(_ location: Int, _ range: NSRange) -> Bool { - location >= range.location && location - range.location < range.length -} - -public func NSEqualRanges(_ a: NSRange, _ b: NSRange) -> Bool { - a == b -} - -public func NSUnionRange(_ a: NSRange, _ b: NSRange) -> NSRange { - let start = min(a.location, b.location) - return NSRange(location: start, length: max(NSMaxRange(a), NSMaxRange(b)) - start) -} - -public func NSIntersectionRange(_ a: NSRange, _ b: NSRange) -> NSRange { - let start = max(a.location, b.location) - let end = min(NSMaxRange(a), NSMaxRange(b)) - return end > start ? NSRange(location: start, length: end - start) : NSRange(location: 0, length: 0) -} - -public func NSStringFromRange(_ range: NSRange) -> String { - "{\(range.location), \(range.length)}" -} - -public func NSRangeFromString(_ string: String) -> NSRange { - let numbers = string.split(whereSeparator: { !$0.isNumber && $0 != "-" }).compactMap { Int($0) } - return NSRange(location: numbers.first ?? 0, length: numbers.count > 1 ? numbers[1] : 0) -} - -extension NSRange: CustomStringConvertible, CustomDebugStringConvertible { - public var description: String { "{\(location), \(length)}" } - public var debugDescription: String { - location == NSNotFound ? "{NSNotFound, \(length)}" : description - } -} - -extension NSRange { - public var lowerBound: Int { location } - public var upperBound: Int { location + length } - - public init(_ x: Range) { - self.init(location: x.lowerBound, length: x.count) - } - - public init(_ region: R) where R.Bound: FixedWidthInteger { - let range = region.relative(to: 0..(_ region: R, in target: S) where R.Bound == String.Index { - let range = region.relative(to: target) - let start = target.utf16.distance(from: target.startIndex, to: range.lowerBound) - let length = target.utf16.distance(from: range.lowerBound, to: range.upperBound) - self.init(location: start, length: length) - } - - public func contains(_ index: Int) -> Bool { - NSLocationInRange(index, self) - } - - public func union(_ other: NSRange) -> NSRange { - NSUnionRange(self, other) - } - - public func intersection(_ other: NSRange) -> NSRange? { - let start = max(location, other.location) - let end = min(upperBound, other.upperBound) - return end >= start ? NSRange(location: start, length: end - start) : nil - } -} - -extension Range where Bound == String.Index { - /// The string's indices for a UTF-16 range; nil when it is out of the - /// string or splits a character's code units. - public init?(_ range: NSRange, in string: S) { - guard range.location != NSNotFound, range.location >= 0, range.length >= 0 else { return nil } - let utf16 = string.utf16 - guard let start = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex), - let end = utf16.index(start, offsetBy: range.length, limitedBy: utf16.endIndex), - let lower = String.Index(start, within: string), let upper = String.Index(end, within: string) else { - return nil - } - self = lower.. - - /// Throws when the pattern is not a regular expression Swift reads. - public init(pattern: String, options: Options = []) throws { - self.pattern = pattern - self.options = options - var source = options.contains(.ignoreMetacharacters) ? Self.escapedPattern(for: pattern) : pattern - if options.contains(.allowCommentsAndWhitespace) { - source = "(?x)" + source - } - var regex = try Regex(source) - if options.contains(.caseInsensitive) { regex = regex.ignoresCase() } - if options.contains(.dotMatchesLineSeparators) { regex = regex.dotMatchesNewlines() } - if options.contains(.anchorsMatchLines) { regex = regex.anchorsMatchLineEndings() } - if !options.contains(.useUnicodeWordBoundaries) { regex = regex.wordBoundaryKind(.simple) } - self.regex = regex.matchingSemantics(.unicodeScalar) - numberOfCaptureGroups = Self.captureGroups(in: options.contains(.ignoreMetacharacters) ? "" : pattern) - } - - /// Opening parentheses that capture: not escaped, not in a character - /// class, not `(?:`, `(?=`, `(?!`, `(?<=`, `(? Int { - let characters = Array(pattern) - var count = 0 - var index = 0 - var inClass = false - while index < characters.count { - let character = characters[index] - if character == "\\" { - index += 2 - continue - } - if inClass { - if character == "]" { inClass = false } - } else if character == "[" { - inClass = true - } else if character == "(" { - if index + 1 < characters.count, characters[index + 1] == "?" { - // Named groups capture: (?…), (?P…), (?'name'…). - let rest = characters[(index + 2)...].prefix(2) - if let first = rest.first, (first == "<" && rest.dropFirst().first.map { $0 != "=" && $0 != "!" } ?? false) - || first == "'" || first == "P" { - count += 1 - } - } else { - count += 1 - } - } - index += 1 - } - return count - } - - public class func escapedPattern(for string: String) -> String { - var result = "" - for character in string { - if "\\^$.|?*+()[]{}".contains(character) { result.append("\\") } - result.append(character) - } - return result - } - - public class func escapedTemplate(for string: String) -> String { - var result = "" - for character in string { - if character == "\\" || character == "$" { result.append("\\") } - result.append(character) - } - return result - } - - // MARK: Matching - - private func results(in string: String, options: MatchingOptions, range: NSRange, first: Bool) -> [NSTextCheckingResult] { - guard let bounds = Range(range, in: string) else { return [] } - let text = string[bounds] - if options.contains(.anchored) { - guard let match = try? regex.prefixMatch(in: text) else { return [] } - return [result(for: match, in: string)] - } - if first { - guard let match = try? regex.firstMatch(in: text) else { return [] } - return [result(for: match, in: string)] - } - return text.matches(of: regex).map { result(for: $0, in: string) } - } - - private func result(for match: Regex.Match, in string: String) -> NSTextCheckingResult { - var ranges: [NSRange] = [] - var names: [String: Int] = [:] - for (index, element) in match.output.enumerated() { - if let range = element.range { - ranges.append(NSRange(range, in: string)) - } else { - ranges.append(NSRange(location: NSNotFound, length: 0)) - } - if let name = element.name { names[name] = index } - } - return NSTextCheckingResult(ranges: ranges, names: names, regularExpression: self) - } - - public func matches(in string: String, options: MatchingOptions = [], range: NSRange) -> [NSTextCheckingResult] { - results(in: string, options: options, range: range, first: false) - } - - public func firstMatch(in string: String, options: MatchingOptions = [], range: NSRange) -> NSTextCheckingResult? { - results(in: string, options: options, range: range, first: true).first - } - - public func numberOfMatches(in string: String, options: MatchingOptions = [], range: NSRange) -> Int { - matches(in: string, options: options, range: range).count - } - - public func rangeOfFirstMatch(in string: String, options: MatchingOptions = [], range: NSRange) -> NSRange { - firstMatch(in: string, options: options, range: range)?.range ?? NSRange(location: NSNotFound, length: 0) - } - - public func enumerateMatches( - in string: String, options: MatchingOptions = [], range: NSRange, - using block: (NSTextCheckingResult?, MatchingFlags, UnsafeMutablePointer) -> Void - ) { - var stop = ObjCBool(false) - for result in matches(in: string, options: options, range: range) { - block(result, [], &stop) - if stop.boolValue { return } - } - if options.contains(.reportCompletion) { - block(nil, .completed, &stop) - } - } - - // MARK: Replacing - - /// `$0`…`$9` (and `${name}`) are a match's groups; `\` escapes. - public func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String { - var output = "" - let characters = Array(templ) - var index = 0 - func group(_ range: NSRange) -> String { - let shifted = NSRange(location: range.location + offset, length: range.length) - guard range.location != NSNotFound, let bounds = Range(shifted, in: string) else { return "" } - return String(string[bounds]) - } - while index < characters.count { - let character = characters[index] - if character == "\\", index + 1 < characters.count { - output.append(characters[index + 1]) - index += 2 - continue - } - if character == "$", index + 1 < characters.count { - if characters[index + 1] == "{", let close = characters[(index + 2)...].firstIndex(of: "}") { - let name = String(characters[(index + 2).. String { - let found = matches(in: string, options: options, range: range) - guard !found.isEmpty else { return string } - var output = "" - var position = string.startIndex - for result in found { - guard let bounds = Range(result.range, in: string) else { continue } - output += string[position.. NSRange { - idx >= 0 && idx < ranges.count ? ranges[idx] : NSRange(location: NSNotFound, length: 0) - } - - public func range(withName name: String) -> NSRange { - names[name].map { range(at: $0) } ?? NSRange(location: NSNotFound, length: 0) - } - - public func adjustingRanges(offset: Int) -> NSTextCheckingResult { - NSTextCheckingResult( - ranges: ranges.map { $0.location == NSNotFound ? $0 : NSRange(location: $0.location + offset, length: $0.length) }, - names: names, regularExpression: regularExpression) - } - - public class func regularExpressionCheckingResult(ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) -> NSTextCheckingResult { - NSTextCheckingResult(ranges: Array(UnsafeBufferPointer(start: ranges, count: count)), names: [:], regularExpression: regularExpression) - } -} diff --git a/foundation/NSUUID.swift b/foundation/NSUUID.swift deleted file mode 100644 index 56abee01..00000000 --- a/foundation/NSUUID.swift +++ /dev/null @@ -1,77 +0,0 @@ -// NSUUID, as swift-corelibs-foundation has it: a class over swift-foundation's -// UUID, for code written against the Objective-C API (a reference to share, -// `getBytes(_:)` into a C buffer). Equal when their bytes are, described by -// its string. No NSCopying or NSSecureCoding: Isomer's Foundation has no -// coders. UUID and NSUUID bridge as Swift's numbers and NSNumber do -// (NSNumberBridging.swift): `value as? UUID` on an NSUUID held as Any, and -// back. - -import FoundationEssentials - -open class NSUUID: NSObject, @unchecked Sendable { - let value: UUID - - /// A new random (version 4) UUID. - public override init() { - value = UUID() - super.init() - } - - init(value: UUID) { - self.value = value - super.init() - } - - /// A UUID from its string ("E621E1F8-C36C-495A-93FC-0C247A3E6E5F"), or nil. - public convenience init?(uuidString string: String) { - guard let value = UUID(uuidString: string) else { return nil } - self.init(value: value) - } - - /// A UUID from its 16 bytes (all zero for nil). - public convenience init(uuidBytes bytes: UnsafePointer?) { - var uuid: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - if let bytes { - withUnsafeMutableBytes(of: &uuid) { $0.copyMemory(from: UnsafeRawBufferPointer(start: bytes, count: 16)) } - } - self.init(value: UUID(uuid: uuid)) - } - - /// Writes its 16 bytes into `uuid`. - open func getBytes(_ uuid: UnsafeMutablePointer) { - withUnsafeBytes(of: value.uuid) { UnsafeMutableRawPointer(uuid).copyMemory(from: $0.baseAddress!, byteCount: 16) } - } - - /// Ordered by bytes, as UUID is. - open func compare(_ otherUUID: UUID) -> ComparisonResult { - value == otherUUID ? .orderedSame : (value < otherUUID ? .orderedAscending : .orderedDescending) - } - - open var uuidString: String { value.uuidString } - - open override func isEqual(_ object: Any?) -> Bool { - (object as? NSUUID)?.value == value - } - - open override var hash: Int { value.hashValue } - - open override var description: String { value.uuidString } -} - -extension UUID: _ObjectiveCBridgeable { - public func _bridgeToObjectiveC() -> NSUUID { NSUUID(value: self) } - - public static func _forceBridgeFromObjectiveC(_ x: NSUUID, result: inout UUID?) { - result = x.value - } - - @discardableResult - public static func _conditionallyBridgeFromObjectiveC(_ input: NSUUID, result: inout UUID?) -> Bool { - result = input.value - return true - } - - public static func _unconditionallyBridgeFromObjectiveC(_ source: NSUUID?) -> UUID { - source?.value ?? UUID(uuid: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) - } -} diff --git a/foundation/NotificationCenter.swift b/foundation/NotificationCenter.swift deleted file mode 100644 index b002a923..00000000 --- a/foundation/NotificationCenter.swift +++ /dev/null @@ -1,167 +0,0 @@ -// Notifications by name, as Apple's Foundation posts and observes them: -// `Notification`, `NSNotification` (for its `Name`), and NotificationCenter's -// `post` and block-based `addObserver(forName:object:queue:using:)`, over the -// registrar swift-foundation's NotificationCenter keeps for its messages (the -// SPI swift-corelibs-foundation builds the same API on). An observer with no -// queue runs on the poster's thread, before `post` returns; one with a queue -// runs as that queue's operation (OperationQueue.swift: the main queue's on -// the main actor). No selector-based observers: there's no runtime to send -// a selector through. - -@_spi(SwiftCorelibsFoundation) import FoundationEssentials - -/// What a notification carries: its name, the object that posted it, and -/// what it adds. -public struct Notification: Equatable, Hashable, CustomStringConvertible, CustomDebugStringConvertible, @unchecked Sendable { - public typealias Name = NSNotification.Name - - public var name: Name - public var object: Any? - public var userInfo: [AnyHashable: Any]? - - public init(name: Name, object: Any? = nil, userInfo: [AnyHashable: Any]? = nil) { - self.name = name - self.object = object - self.userInfo = userInfo - } - - /// The same name and the same object (by identity; equal values when - /// the objects aren't classes), as Apple's compares them. - public static func == (lhs: Notification, rhs: Notification) -> Bool { - guard lhs.name == rhs.name else { return false } - switch (lhs.object, rhs.object) { - case (nil, nil): return true - case let (left?, right?): - if type(of: left) is AnyClass, type(of: right) is AnyClass { return (left as AnyObject) === (right as AnyObject) } - if let left = left as? AnyHashable, let right = right as? AnyHashable { return left == right } - return false - default: return false - } - } - - public func hash(into hasher: inout Hasher) { hasher.combine(name) } - - public var description: String { - "name = \(name.rawValue), object = \(object.map { String(describing: $0) } ?? "nil"), userInfo = \(userInfo.map { String(describing: $0) } ?? "nil")" - } - - public var debugDescription: String { description } -} - -/// Apple's reference type for a notification; Swift code meets it for its -/// `Name`. -open class NSNotification: NSObject, @unchecked Sendable { - /// A notification's name: a string, typed. - public struct Name: RawRepresentable, Hashable, Equatable, Sendable { - public var rawValue: String - - public init(_ rawValue: String) { self.rawValue = rawValue } - public init(rawValue: String) { self.rawValue = rawValue } - } - - open var name: Name - open var object: Any? - open var userInfo: [AnyHashable: Any]? - - public init(name: Name, object: Any?, userInfo: [AnyHashable: Any]? = nil) { - self.name = name - self.object = object - self.userInfo = userInfo - } -} - -/// What `addObserver(forName:object:queue:using:)` hands back: given to -/// `removeObserver(_:)`, it ends the observation. -private final class NotificationObserver: NSObject, @unchecked Sendable { - let token: NotificationCenter._NotificationObserverToken - weak var center: NotificationCenter? - let name: String? - let object: ObjectIdentifier? - - init(token: NotificationCenter._NotificationObserverToken, center: NotificationCenter, name: String?, object: ObjectIdentifier?) { - self.token = token - self.center = center - self.name = name - self.object = object - } -} - -extension NotificationCenter { - public func post(_ notification: Notification) { - _post(notification.name.rawValue, subject: notification.object, message: notification) - } - - public func post(name aName: NSNotification.Name, object anObject: Any?) { - post(Notification(name: aName, object: anObject)) - } - - public func post(name aName: NSNotification.Name, object anObject: Any?, userInfo aUserInfo: [AnyHashable: Any]? = nil) { - post(Notification(name: aName, object: anObject, userInfo: aUserInfo)) - } - - /// `block` called with each notification of `name` (every name when - /// nil) from `obj` (any object when nil): on the poster's thread when - /// `queue` is nil, as an operation of `queue` otherwise. Observing lasts - /// until the returned object is given to `removeObserver(_:)`. - public func addObserver(forName name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, - using block: @escaping @Sendable (Notification) -> Void) -> any NSObjectProtocol { - let token = _addObserver(name?.rawValue, object: obj) { (notification: Notification) in - if let queue { - queue.addOperation { block(notification) } - } else { - block(notification) - } - } - return NotificationObserver(token: token, center: self, name: name?.rawValue, object: obj.map { ObjectIdentifier($0 as AnyObject) }) - } - - /// An observation `addObserver(forName:object:queue:using:)` began, ended. - public func removeObserver(_ observer: Any) { - guard let observer = observer as? NotificationObserver, observer.center === self else { return } - _removeObserver(observer.token) - } - - /// The observation ended if it is of `aName` (or any, when nil) and - /// `anObject` (or any). - public func removeObserver(_ observer: Any, name aName: NSNotification.Name?, object anObject: Any?) { - guard let observer = observer as? NotificationObserver, observer.center === self else { return } - if let aName, observer.name != aName.rawValue { return } - if let anObject, observer.object != ObjectIdentifier(anObject as AnyObject) { return } - _removeObserver(observer.token) - } - - /// The notifications of `name` (from `object`, when given) as they're - /// posted, from the time this is called, for as long as it's iterated. - public func notifications(named name: Notification.Name, object: (any AnyObject & Sendable)? = nil) -> Notifications { - Notifications(center: self, name: name, object: object) - } - - /// An asynchronous sequence of notifications: what `notifications(named: - /// object:)` gives. - public final class Notifications: AsyncSequence, @unchecked Sendable { - public typealias Element = Notification - public typealias AsyncIterator = Iterator - - private let stream: AsyncStream - private let observer: any NSObjectProtocol - private weak var center: NotificationCenter? - - init(center: NotificationCenter, name: Notification.Name, object: (any AnyObject & Sendable)?) { - let (stream, continuation) = AsyncStream.makeStream() - self.stream = stream - self.center = center - observer = center.addObserver(forName: name, object: object, queue: nil) { continuation.yield($0) } - } - - deinit { center?.removeObserver(observer) } - - public struct Iterator: AsyncIteratorProtocol { - public typealias Element = Notification - var base: AsyncStream.Iterator - - public mutating func next() async -> Notification? { await base.next() } - } - - public func makeAsyncIterator() -> Iterator { Iterator(base: stream.makeAsyncIterator()) } - } -} diff --git a/foundation/OperationQueue.swift b/foundation/OperationQueue.swift deleted file mode 100644 index bf63387e..00000000 --- a/foundation/OperationQueue.swift +++ /dev/null @@ -1,34 +0,0 @@ -// OperationQueue, as far as code hands it blocks: the main queue (what -// NotificationCenter's `addObserver(forName:object:queue:using:)` is most -// often given) and queues of an app's own. A block runs as a Swift task: the -// main queue's on the main actor, in the order added; another queue's off -// it. No Operation objects, dependencies, priorities or suspension: Swift -// concurrency is how Isomer's apps schedule work (docs/parity/Foundation.md). - -open class OperationQueue: NSObject, @unchecked Sendable { - private let isMain: Bool - - /// The queue whose operations run on the main actor. - open class var main: OperationQueue { mainQueue } - - public override init() { - isMain = false - } - - private init(main: Bool) { - isMain = main - } - - open var name: String? - - /// `block` run soon, after the blocks added before it on the main queue. - open func addOperation(_ block: @escaping @Sendable () -> Void) { - if isMain { - Task { @MainActor in block() } - } else { - Task.detached { block() } - } - } - - private static let mainQueue = OperationQueue(main: true) -} diff --git a/foundation/Paths.swift b/foundation/Paths.swift deleted file mode 100644 index 0feed509..00000000 --- a/foundation/Paths.swift +++ /dev/null @@ -1,53 +0,0 @@ -// The path functions corelibs and Apple's Foundation have beside -// FileManager (swift-foundation has only FileManager's). - -import FoundationEssentials - -/// The temporary directory's path, ending in "/". -public func NSTemporaryDirectory() -> String { - var path = FileManager.default.temporaryDirectory.path - if !path.hasSuffix("/") { path += "/" } - return path -} - -/// The current user's home directory. -public func NSHomeDirectory() -> String { - FileManager.default.homeDirectoryForCurrentUser.path -} - -// URL's directories, which swift-foundation declares for Apple's framework -// only: each is the first of FileManager's search paths for it, as Apple's -// are. Off Apple those come from the environment (HOME, XDG_DATA_HOME, -// XDG_CACHE_HOME); the hosts give an app an iOS container's layout -// (wasm/libraries/swift_ui/runtime/file_system.js). The directories with -// no search path off Apple (applications, the library) are left out. -extension URL { - private static func url(for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask) -> URL { - FileManager.default.urls(for: directory, in: domain).first! - } - - /// The app's documents directory. - public static var documentsDirectory: URL { url(for: .documentDirectory, in: .userDomainMask) } - - /// The app's support files (Library/Application Support). - public static var applicationSupportDirectory: URL { url(for: .applicationSupportDirectory, in: .userDomainMask) } - - /// The app's discardable cache files (Library/Caches). - public static var cachesDirectory: URL { url(for: .cachesDirectory, in: .userDomainMask) } - - public static var userDirectory: URL { url(for: .userDirectory, in: .localDomainMask) } - - public static var desktopDirectory: URL { url(for: .desktopDirectory, in: .userDomainMask) } - - public static var downloadsDirectory: URL { url(for: .downloadsDirectory, in: .userDomainMask) } - - public static var moviesDirectory: URL { url(for: .moviesDirectory, in: .userDomainMask) } - - public static var musicDirectory: URL { url(for: .musicDirectory, in: .userDomainMask) } - - public static var picturesDirectory: URL { url(for: .picturesDirectory, in: .userDomainMask) } - - public static var sharedPublicDirectory: URL { url(for: .sharedPublicDirectory, in: .userDomainMask) } - - public static var trashDirectory: URL { url(for: .trashDirectory, in: .userDomainMask) } -} diff --git a/foundation/RelativeDateTimeFormatter.swift b/foundation/RelativeDateTimeFormatter.swift deleted file mode 100644 index 9a77a321..00000000 --- a/foundation/RelativeDateTimeFormatter.swift +++ /dev/null @@ -1,127 +0,0 @@ -// RelativeDateTimeFormatter: a date relative to another as words ("2 hours -// ago", "in 3 days", "yesterday"), by the largest unit that differs. A -// Swift class, as Isomer's other formatters are (Apple's is a Formatter), -// and English whatever the locale: Isomer's Foundation formats without ICU -// unless an app asks for it (docs/parity/Foundation.md). - -import FoundationEssentials - -open class RelativeDateTimeFormatter: @unchecked Sendable { - /// Numbers ("1 day ago"), or the names a language has for some of them - /// ("yesterday", "last week", "now"). - public enum DateTimeStyle: Int, Sendable { - case numeric = 0 - case named = 1 - } - - /// "2 hours", "two hours", "2 hr.", "2h". - public enum UnitsStyle: Int, Sendable { - case full = 0 - case spellOut = 1 - case short = 2 - case abbreviated = 3 - } - - open var dateTimeStyle: DateTimeStyle = .numeric - open var unitsStyle: UnitsStyle = .full - open var calendar: Calendar! = .current - open var locale: Locale! = .current - - public init() {} - - /// The largest of the components' year, month, week, day, hour, minute - /// and second that isn't zero, as a time from now ("in 2 days") or - /// before it ("2 days ago"); none: "in 0 seconds", or "now". - open func localizedString(from dateComponents: DateComponents) -> String { - let units: [(Unit, Int?)] = [ - (.year, dateComponents.year), (.month, dateComponents.month), - (.week, dateComponents.weekOfMonth ?? dateComponents.weekOfYear), (.day, dateComponents.day), - (.hour, dateComponents.hour), (.minute, dateComponents.minute), (.second, dateComponents.second), - ] - for (unit, value) in units { - if let value, value != 0 { return phrase(value, unit) } - } - return phrase(0, .second) - } - - open func localizedString(fromTimeInterval timeInterval: TimeInterval) -> String { - let now = Date() - return localizedString(for: now.addingTimeInterval(timeInterval), relativeTo: now) - } - - open func localizedString(for date: Date, relativeTo referenceDate: Date) -> String { - let calendar: Calendar = self.calendar ?? .current - let components = calendar.dateComponents([.year, .month, .weekOfMonth, .day, .hour, .minute, .second], - from: referenceDate, to: date) - return localizedString(from: components) - } - - /// A date relative to now; nil for anything else. - open func string(for obj: Any?) -> String? { - guard let date = obj as? Date else { return nil } - return localizedString(for: date, relativeTo: Date()) - } - - // MARK: English - - enum Unit { - case year, month, week, day, hour, minute, second - } - - func phrase(_ value: Int, _ unit: Unit) -> String { - if dateTimeStyle == .named, let named = named(value, unit) { return named } - let amount = quantity(abs(value), unit) - return value < 0 ? "\(amount) ago" : "in \(amount)" - } - - func named(_ value: Int, _ unit: Unit) -> String? { - switch (unit, value) { - case (.second, 0): return "now" - case (.day, -1): return "yesterday" - case (.day, 1): return "tomorrow" - case (.week, -1): return "last week" - case (.week, 1): return "next week" - case (.month, -1): return "last month" - case (.month, 1): return "next month" - case (.year, -1): return "last year" - case (.year, 1): return "next year" - default: return nil - } - } - - func quantity(_ count: Int, _ unit: Unit) -> String { - let (word, short, letter): (String, String, String) - switch unit { - case .year: (word, short, letter) = ("year", "yr.", "y") - case .month: (word, short, letter) = ("month", "mo.", "mo") - case .week: (word, short, letter) = ("week", "wk.", "w") - case .day: (word, short, letter) = ("day", count == 1 ? "day" : "days", "d") - case .hour: (word, short, letter) = ("hour", "hr.", "h") - case .minute: (word, short, letter) = ("minute", "min.", "m") - case .second: (word, short, letter) = ("second", "sec.", "s") - } - let plural = count == 1 ? word : word + "s" - switch unitsStyle { - case .full: return "\(count) \(plural)" - case .spellOut: return "\(spelledOut(count)) \(plural)" - case .short: return "\(count) \(short)" - case .abbreviated: return "\(count)\(letter)" - } - } - - /// English words for a count ("twenty-one"); digits from a million up. - func spelledOut(_ number: Int) -> String { - let ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", - "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] - let tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] - switch number { - case 0..<20: return ones[number] - case 20..<100: return tens[number / 10] + (number % 10 == 0 ? "" : "-" + ones[number % 10]) - case 100..<1000: - return ones[number / 100] + " hundred" + (number % 100 == 0 ? "" : " " + spelledOut(number % 100)) - case 1000..<1_000_000: - return spelledOut(number / 1000) + " thousand" + (number % 1000 == 0 ? "" : " " + spelledOut(number % 1000)) - default: return String(number) - } - } -} diff --git a/foundation/Stream.swift b/foundation/Stream.swift deleted file mode 100644 index effa45d5..00000000 --- a/foundation/Stream.swift +++ /dev/null @@ -1,223 +0,0 @@ -// Stream, InputStream and OutputStream, as Isomer's Foundation has them: -// Swift classes for streams over memory and files, read and written -// synchronously. Apple's are Objective-C classes scheduled on run loops; -// these have no run loop, no delegate events and no sockets -// (docs/parity/Foundation.md). SwiftProtobuf's delimited messages, for one, -// read and write through them. - -import FoundationEssentials - -#if canImport(Glibc) -import Glibc -#elseif canImport(Musl) -import Musl -#elseif canImport(Android) -import Android -#elseif canImport(WASILibc) -import WASILibc -#elseif canImport(ucrt) -import ucrt -#endif - -open class Stream: @unchecked Sendable { - public enum Status: UInt, Sendable { - case notOpen = 0 - case opening = 1 - case open = 2 - case reading = 3 - case writing = 4 - case atEnd = 5 - case closed = 6 - case error = 7 - } - - public struct Event: OptionSet, Sendable { - public let rawValue: UInt - public init(rawValue: UInt) { self.rawValue = rawValue } - public static let openCompleted = Event(rawValue: 1 << 0) - public static let hasBytesAvailable = Event(rawValue: 1 << 1) - public static let hasSpaceAvailable = Event(rawValue: 1 << 2) - public static let errorOccurred = Event(rawValue: 1 << 3) - public static let endEncountered = Event(rawValue: 1 << 4) - } - - public struct PropertyKey: RawRepresentable, Hashable, Sendable { - public let rawValue: String - public init(rawValue: String) { self.rawValue = rawValue } - public init(_ rawValue: String) { self.rawValue = rawValue } - public static let dataWrittenToMemoryStreamKey = PropertyKey("NSStreamDataWrittenToMemoryStreamKey") - public static let fileCurrentOffsetKey = PropertyKey("NSStreamFileCurrentOffsetKey") - } - - public internal(set) var streamStatus: Status = .notOpen - public internal(set) var streamError: (any Error)? - - init() {} - - open func open() { - if streamStatus == .notOpen { streamStatus = .open } - } - - open func close() { - streamStatus = .closed - } - - open func property(forKey key: PropertyKey) -> Any? { nil } - - open func setProperty(_ property: Any?, forKey key: PropertyKey) -> Bool { false } -} - -open class InputStream: Stream, @unchecked Sendable { - private var bytes: [UInt8] = [] - private var offset = 0 - private var pendingFile: String? - - public init(data: Data) { - bytes = Array(data) - super.init() - } - - public init?(url: URL) { - guard url.isFileURL else { return nil } - pendingFile = url.path - super.init() - } - - public convenience init?(fileAtPath path: String) { - self.init(url: URL(fileURLWithPath: path)) - } - - open override func open() { - guard streamStatus == .notOpen else { return } - if let path = pendingFile { - do { - bytes = Array(try Data(contentsOf: URL(fileURLWithPath: path))) - } catch { - streamError = error - streamStatus = .error - return - } - } - streamStatus = bytes.isEmpty ? .atEnd : .open - } - - /// Copies up to `len` bytes into `buffer`: how many, 0 at the end, -1 on - /// an error. - open func read(_ buffer: UnsafeMutablePointer, maxLength len: Int) -> Int { - if streamStatus == .error { return -1 } - guard streamStatus == .open || streamStatus == .atEnd else { return -1 } - let count = min(len, bytes.count - offset) - if count <= 0 { - streamStatus = .atEnd - return 0 - } - bytes.withUnsafeBufferPointer { source in - buffer.update(from: source.baseAddress! + offset, count: count) - } - offset += count - if offset == bytes.count { streamStatus = .atEnd } - return count - } - - open func getBuffer( - _ buffer: UnsafeMutablePointer?>, length len: UnsafeMutablePointer - ) -> Bool { false } - - open var hasBytesAvailable: Bool { streamStatus == .open && offset < bytes.count } - - open override func property(forKey key: PropertyKey) -> Any? { - key == .fileCurrentOffsetKey ? offset : nil - } -} - -open class OutputStream: Stream, @unchecked Sendable { - private enum Target { - case memory - case buffer(UnsafeMutablePointer, capacity: Int) - case file(path: String, append: Bool) - } - - private let target: Target - private var written: [UInt8] = [] - - public required init(toMemory: ()) { - target = .memory - super.init() - } - - public init(toBuffer buffer: UnsafeMutablePointer, capacity: Int) { - target = .buffer(buffer, capacity: capacity) - super.init() - } - - public init?(url: URL, append shouldAppend: Bool) { - guard url.isFileURL else { return nil } - target = .file(path: url.path, append: shouldAppend) - super.init() - } - - public convenience init?(toFileAtPath path: String, append shouldAppend: Bool) { - self.init(url: URL(fileURLWithPath: path), append: shouldAppend) - } - - open class func toMemory() -> Self { - self.init(toMemory: ()) - } - - /// Writes up to `len` bytes from `buffer`: how many, -1 on an error. - open func write(_ buffer: UnsafePointer, maxLength len: Int) -> Int { - guard streamStatus == .open || streamStatus == .writing else { return -1 } - var count = len - if case .buffer(_, let capacity) = target { - count = min(len, capacity - written.count) - if count <= 0 { - streamStatus = .atEnd - return 0 - } - } - written.append(contentsOf: UnsafeBufferPointer(start: buffer, count: count)) - if case .buffer(let destination, _) = target { - (destination + written.count - count).update(from: buffer, count: count) - } - if case .file = target, !flush() { return -1 } - return count - } - - open var hasSpaceAvailable: Bool { - if case .buffer(_, let capacity) = target { return written.count < capacity } - return streamStatus == .open - } - - open override func property(forKey key: PropertyKey) -> Any? { - switch key { - case .dataWrittenToMemoryStreamKey: - if case .memory = target { return Data(written) } - return nil - case .fileCurrentOffsetKey: - return written.count - default: - return nil - } - } - - /// A file stream writes what it has through to the file. - private func flush() -> Bool { - guard case .file(let path, let append) = target else { return true } - do { - var data = Data() - if append, let existing = try? Data(contentsOf: URL(fileURLWithPath: path)) { - data = existing - } - data.append(contentsOf: written) - try data.write(to: URL(fileURLWithPath: path)) - if append { - written.removeAll() - } - return true - } catch { - streamError = error - streamStatus = .error - return false - } - } -} diff --git a/foundation/String+Format.swift b/foundation/String+Format.swift deleted file mode 100644 index 364fa21c..00000000 --- a/foundation/String+Format.swift +++ /dev/null @@ -1,244 +0,0 @@ -// String(format:) for platforms without Apple's framework (upstream -// leaves it to swift-corelibs-foundation's CFString formatting). The format -// is read here: `%@` describes any value, `%s` takes a Swift string or a C -// string, positions (`%2$@`), widths and precisions (also `*`) and flags -// work; each numeric conversion is written by the C library's vsnprintf, so -// numbers come out as printf writes them. The locale is not applied. - -import FoundationEssentials - -#if canImport(Glibc) -@preconcurrency import Glibc -#elseif canImport(Musl) -@preconcurrency import Musl -#elseif canImport(Android) -@preconcurrency import Android -#elseif canImport(WASILibc) -@preconcurrency import WASILibc -#elseif canImport(ucrt) -import ucrt -#elseif canImport(Darwin) -import Darwin -#endif - -/// A String passed to a C variadic function arrives as a C string (a copy -/// that lives as long as the program). -extension String: @retroactive CVarArg { - public var _cVarArgEncoding: [Int] { - let copy = withCString { strdup($0) } - return copy!._cVarArgEncoding - } -} - -@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *) -extension String { - public init(format: __shared String, _ arguments: any CVarArg...) { - self = _IsomerFormatter.format(format, arguments) - } - - public init(format: __shared String, arguments: __shared [any CVarArg]) { - self = _IsomerFormatter.format(format, arguments) - } - - public init(format: __shared String, locale: Locale?, _ args: any CVarArg...) { - self = _IsomerFormatter.format(format, args) - } - - public init(format: __shared String, locale: Locale?, arguments: [any CVarArg]) { - self = _IsomerFormatter.format(format, arguments) - } - - public static func localizedStringWithFormat(_ format: String, _ arguments: any CVarArg...) -> String { - _IsomerFormatter.format(format, arguments) - } -} - -@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *) -extension StringProtocol { - public func appendingFormat(_ format: T, _ arguments: any CVarArg...) -> String { - String(self) + _IsomerFormatter.format(String(format), arguments) - } -} - -enum _IsomerFormatter { - struct Spec { - var flags = "" - var width: Int? - var precision: Int? - var length = "" - var conversion: Character = "@" - } - - static func format(_ format: String, _ arguments: [any CVarArg]) -> String { - var result = "" - var nextArgument = 0 - let characters = Array(format) - var index = 0 - - func argument(_ position: Int?) -> (any CVarArg)? { - let at: Int - if let position { - at = position - 1 - } else { - at = nextArgument - nextArgument += 1 - } - return at >= 0 && at < arguments.count ? arguments[at] : nil - } - - func number(_ start: inout Int) -> Int? { - var value: Int? - while start < characters.count, let digit = characters[start].wholeNumberValue, characters[start].isASCII { - value = (value ?? 0) * 10 + digit - start += 1 - } - return value - } - - while index < characters.count { - let character = characters[index] - guard character == "%" else { - result.append(character) - index += 1 - continue - } - index += 1 - guard index < characters.count else { - result.append("%") - break - } - if characters[index] == "%" { - result.append("%") - index += 1 - continue - } - - var spec = Spec() - // A position: digits then "$". - var position: Int? - var lookahead = index - if let value = number(&lookahead), lookahead < characters.count, characters[lookahead] == "$" { - position = value - index = lookahead + 1 - } - while index < characters.count, "-+ #0'".contains(characters[index]) { - if characters[index] != "'" { spec.flags.append(characters[index]) } - index += 1 - } - if index < characters.count, characters[index] == "*" { - index += 1 - spec.width = argument(nil).flatMap(Self.integer)?.value.map { Int($0) } - } else { - spec.width = number(&index) - } - if index < characters.count, characters[index] == "." { - index += 1 - if index < characters.count, characters[index] == "*" { - index += 1 - spec.precision = argument(nil).flatMap(Self.integer)?.value.map { Int($0) } - } else { - spec.precision = number(&index) ?? 0 - } - } - while index < characters.count, "hlqLzjt".contains(characters[index]) { - spec.length.append(characters[index]) - index += 1 - } - guard index < characters.count else { break } - spec.conversion = characters[index] - index += 1 - - if spec.conversion == "n" { continue } - guard let value = argument(position) else { continue } - result += render(value, spec) - } - return result - } - - static func integer(_ value: any CVarArg) -> (value: Int64?, unsigned: UInt64?)? { - if let bool = value as? Bool { return (bool ? 1 : 0, bool ? 1 : 0) } - if let integer = value as? any BinaryInteger { - return (Int64(truncatingIfNeeded: integer), UInt64(truncatingIfNeeded: integer)) - } - if let floating = value as? any BinaryFloatingPoint { - let double = Double(floating) - return (Int64(exactly: double.rounded(.towardZero)) ?? 0, UInt64(exactly: double.rounded(.towardZero)) ?? 0) - } - return nil - } - - static func padded(_ text: String, _ spec: Spec) -> String { - var text = text - if let precision = spec.precision, "@sS".contains(spec.conversion) { - text = String(text.prefix(precision)) - } - guard let width = spec.width, text.count < width else { return text } - let padding = String(repeating: " ", count: width - text.count) - return spec.flags.contains("-") ? text + padding : padding + text - } - - static func render(_ value: any CVarArg, _ spec: Spec) -> String { - switch spec.conversion { - case "@": - return padded(String(describing: value), spec) - case "s", "S": - if let string = value as? String { return padded(string, spec) } - if let pointer = value as? UnsafePointer { return padded(String(cString: pointer), spec) } - if let pointer = value as? UnsafeMutablePointer { return padded(String(cString: pointer), spec) } - return padded(String(describing: value), spec) - case "c", "C": - if let integer = integer(value)?.unsigned, let scalar = Unicode.Scalar(UInt32(truncatingIfNeeded: integer)) { - return padded(String(Character(scalar)), spec) - } - return padded(String(describing: value), spec) - case "d", "i", "D": - guard let number = integer(value)?.value else { return padded(String(describing: value), spec) } - return printf(spec, "lld", number) - case "u", "o", "x", "X", "U", "O": - guard let number = integer(value)?.unsigned else { return padded(String(describing: value), spec) } - let conversion = String(spec.conversion).lowercased() == "u" ? "u" : String(spec.conversion).lowercased() == "o" ? "o" : String(spec.conversion) - return printf(spec, "ll" + conversion, number) - case "f", "F", "e", "E", "g", "G", "a", "A": - let double: Double - if let floating = value as? any BinaryFloatingPoint { - double = Double(floating) - } else if let number = integer(value)?.value { - double = Double(number) - } else { - return padded(String(describing: value), spec) - } - return printf(spec, String(spec.conversion), double) - case "p": - if let integer = integer(value)?.unsigned { - return padded("0x" + String(integer, radix: 16), spec) - } - return padded(String(describing: value), spec) - default: - return padded(String(describing: value), spec) - } - } - - /// One conversion through the C library. - static func printf(_ spec: Spec, _ conversion: String, _ value: any CVarArg) -> String { - var format = "%" + spec.flags - if let width = spec.width { format += String(width) } - if let precision = spec.precision { format += "." + String(precision) } - format += conversion - var capacity = 128 - while true { - let buffer = UnsafeMutablePointer.allocate(capacity: capacity) - defer { buffer.deallocate() } - let written = format.withCString { cFormat in - withVaList([value]) { list in - vsnprintf(buffer, capacity, cFormat, list) - } - } - if written < 0 { return "" } - if Int(written) < capacity { - return String(cString: buffer) - } - capacity = Int(written) + 1 - } - } -} - diff --git a/foundation/StringProtocol+NSString.swift b/foundation/StringProtocol+NSString.swift deleted file mode 100644 index 8a63a9a5..00000000 --- a/foundation/StringProtocol+NSString.swift +++ /dev/null @@ -1,281 +0,0 @@ -// The string API Swift code reaches through NSString on Apple -// platforms and through swift-corelibs-foundation elsewhere, for platforms -// that have neither: searching, replacing, trimming and splitting by -// character sets, unlocalized comparison, percent encoding, padding. They are -// built on Essentials' own search and comparison (String+Comparison.swift). -// The "localized" comparisons compare without locale data -// (FoundationInternationalization supplies the locale-aware case mappings). - -import FoundationEssentials - -@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *) -extension StringProtocol { - // MARK: Finding - - /// The first range of `aString` in the string (the last, with - /// `.backwards`), within `searchRange`. - public func range( - of aString: T, options mask: String.CompareOptions = [], range searchRange: Range? = nil, - locale: Locale? = nil - ) -> Range? { - var substring = Substring(self) - if let searchRange { substring = substring[searchRange] } - guard let found = try? substring._range(of: Substring(aString), options: mask) else { return nil } - return found - } - - /// The first range of a scalar from `aSet` (the last, with - /// `.backwards`), within `aRange`. - public func rangeOfCharacter( - from aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range? = nil - ) -> Range? { - var substring = Substring(self) - if let aRange { substring = substring[aRange] } - guard !substring.isEmpty else { return nil } - return substring.unicodeScalars._rangeOfCharacter( - anchored: mask.contains(.anchored), backwards: mask.contains(.backwards), - matchingPredicate: aSet.contains) - } - - public func localizedStandardRange(of str: T) -> Range? { - range(of: str, options: [.caseInsensitive, .diacriticInsensitive]) - } - - public func localizedCaseInsensitiveContains(_ other: T) -> Bool { - range(of: other, options: .caseInsensitive) != nil - } - - public func localizedStandardContains(_ str: T) -> Bool { - localizedStandardRange(of: str) != nil - } - - // MARK: Comparing - - public func caseInsensitiveCompare(_ aString: T) -> ComparisonResult { - compare(aString, options: .caseInsensitive) - } - - public func localizedCompare(_ aString: T) -> ComparisonResult { - compare(aString) - } - - public func localizedCaseInsensitiveCompare(_ aString: T) -> ComparisonResult { - compare(aString, options: .caseInsensitive) - } - - /// Finder-style ordering: case-insensitive, numbers by value. - public func localizedStandardCompare(_ string: T) -> ComparisonResult { - compare(string, options: [.caseInsensitive, .numeric]) - } - - // MARK: Replacing - - /// The string with every occurrence of `target` in `searchRange` replaced. - /// With `.regularExpression`, `target` is a pattern and `replacement` a - /// template (`$0`…`$9` for the match and its groups, `\` escaping). - public func replacingOccurrences( - of target: Target, with replacement: Replacement, options: String.CompareOptions = [], - range searchRange: Range? = nil - ) -> String { - let whole = Substring(self) - let scope = searchRange.map { whole[$0] } ?? whole - let replacementString = String(replacement) - guard !target.isEmpty else { return String(self) } - - var result = String(whole[whole.startIndex...Match, in scope: Substring) -> String { - var result = "" - var iterator = template.makeIterator() - while let character = iterator.next() { - if character == "\\" { - if let next = iterator.next() { result.append(next) } - } else if character == "$", let next = iterator.next() { - if let digit = next.wholeNumberValue, digit < match.output.count { - if let range = match.output[digit].range { result += scope[range] } - } else { - result.append(character) - result.append(next) - } - } else { - result.append(character) - } - } - return result - } - #endif - - /// The string with the characters in `range` replaced by `replacement`. - public func replacingCharacters( - in range: R, with replacement: T - ) -> String where R.Bound == Index { - let bounds = range.relative(to: self) - return String(self[startIndex.. String { - let scalars = Substring(self).unicodeScalars - var start = scalars.startIndex - var end = scalars.endIndex - while start < end, set.contains(scalars[start]) { - scalars.formIndex(after: &start) - } - while end > start { - let before = scalars.index(before: end) - if !set.contains(scalars[before]) { break } - end = before - } - return String(Substring(scalars[start.. [String] { - let scalars = Substring(self).unicodeScalars - var result: [String] = [] - var pieceStart = scalars.startIndex - var index = scalars.startIndex - while index < scalars.endIndex { - if separator.contains(scalars[index]) { - result.append(String(Substring(scalars[pieceStart.. Void) { - var stop = false - var lineStart = startIndex - var index = startIndex - while index < endIndex { - let character = self[index] - if character.isNewline { - body(String(self[lineStart..(_ aString: T) -> String { - String(self) + String(aString) - } - - /// The string padded with `padString` (from `padIndex`) or cut, to - /// `newLength` UTF-16 code units. - public func padding(toLength newLength: Int, withPad padString: T, startingAt padIndex: Int) -> String { - let units = Array(utf16) - if units.count >= newLength { - return String(decoding: units[0.. String? { - var result = "" - let hex: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] - for scalar in unicodeScalars { - if allowedCharacters.contains(scalar) { - result.unicodeScalars.append(scalar) - } else { - for byte in String(scalar).utf8 { - result.append("%") - result.append(hex[Int(byte >> 4)]) - result.append(hex[Int(byte & 0xF)]) - } - } - } - return result - } - - /// The string with its `%XX` sequences decoded, or nil when they are not - /// valid UTF-8 or a `%` is not followed by two hex digits. - public var removingPercentEncoding: String? { - var bytes: [UInt8] = [] - let source = Array(utf8) - var index = 0 - func hexValue(_ byte: UInt8) -> UInt8? { - switch byte { - case 0x30...0x39: return byte - 0x30 - case 0x41...0x46: return byte - 0x41 + 10 - case 0x61...0x66: return byte - 0x61 + 10 - default: return nil - } - } - while index < source.count { - if source[index] == 0x25 { - guard index + 2 < source.count, - let high = hexValue(source[index + 1]), let low = hexValue(source[index + 2]) - else { return nil } - bytes.append(high << 4 | low) - index += 3 - } else { - bytes.append(source[index]) - index += 1 - } - } - return String(validating: bytes, as: UTF8.self) - } -} - diff --git a/foundation/Thread.swift b/foundation/Thread.swift deleted file mode 100644 index 46c6b965..00000000 --- a/foundation/Thread.swift +++ /dev/null @@ -1,189 +0,0 @@ -// Thread (Apple's Foundation and corelibs have it; swift-foundation does -// not), over pthreads: a block run on a thread of its own, the current -// thread with its name and dictionary, the main thread, sleeping. In -// WebAssembly without threads there is one thread, the main one, and -// starting another stops the program. No `threadDictionary`: Apple's is -// an NSMutableDictionary (Objective-C), which Isomer leaves out. - -import FoundationEssentials -#if canImport(Android) -import Android -#elseif canImport(Glibc) -import Glibc -#elseif canImport(WASILibc) -import WASILibc -#if _runtime(_multithreaded) -import wasi_pthread -import CWasiThreadIdentity -#endif -#endif - -public enum QualityOfService: Int, Sendable { - case userInteractive = 0x21 - case userInitiated = 0x19 - case utility = 0x11 - case background = 0x09 - case `default` = -1 -} - -open class Thread: @unchecked Sendable { - private var block: (() -> Void)? - open var name: String? - open var qualityOfService: QualityOfService = .default - open var stackSize = 0 - public private(set) var isExecuting = false - public private(set) var isFinished = false - public private(set) var isCancelled = false - private let isMain: Bool - - public init() { - isMain = false - } - - public convenience init(block: @escaping @Sendable () -> Void) { - self.init() - self.block = block - } - - private init(main: Bool) { - isMain = main - } - - /// What a subclass's thread runs: the block it was made with. - open func main() { - block?() - } - - open func cancel() { - isCancelled = true - } - - open var isMainThread: Bool { isMain } - - open func start() { - #if os(WASI) && !_runtime(_multithreaded) - fatalError("Thread.start(): this WebAssembly program has no threads") - #else - isExecuting = true - let context = Unmanaged.passRetained(self).toOpaque() - var attributes = pthread_attr_t() - pthread_attr_init(&attributes) - if stackSize > 0 { pthread_attr_setstacksize(&attributes, stackSize) } - pthread_attr_setdetachstate(&attributes, Int32(PTHREAD_CREATE_DETACHED)) - #if os(WASI) - var thread: pthread_t? = nil - #else - var thread = pthread_t() - #endif - let result = pthread_create(&thread, &attributes, { context in - let thread = Unmanaged.fromOpaque(_pointer(context)).takeRetainedValue() - pthread_setspecific(_threadKey, Unmanaged.passUnretained(thread).toOpaque()) - #if !os(WASI) - if let name = thread.name { - _ = name.withCString { pthread_setname_np(pthread_self(), $0) } - } - #endif - thread.main() - thread.isExecuting = false - thread.isFinished = true - pthread_setspecific(_threadKey, nil) - // A detached thread's result goes unread (Bionic's start routine - // returns a non-optional pointer). - return context - }, context) - pthread_attr_destroy(&attributes) - if result != 0 { - Unmanaged.fromOpaque(context).release() - isExecuting = false - } - #endif - } - - // MARK: The current thread - - public static let main = Thread(main: true) - - public static var isMainThread: Bool { - #if os(WASI) && !_runtime(_multithreaded) - return true - #else - #if os(WASI) - return iso_wasi_is_main_thread() != 0 - #else - return gettid() == getpid() - #endif - #endif - } - - public static var current: Thread { - #if os(WASI) && !_runtime(_multithreaded) - return main - #else - if let pointer = pthread_getspecific(_threadKey) { - return Unmanaged.fromOpaque(pointer).takeUnretainedValue() - } - if isMainThread { return main } - // A thread Foundation did not start: a Thread of its own, kept for - // the thread's life. - let thread = Thread(main: false) - pthread_setspecific(_threadKey, Unmanaged.passRetained(thread).toOpaque()) - return thread - #endif - } - - public class func isMultiThreaded() -> Bool { - #if os(WASI) && !_runtime(_multithreaded) - return false - #else - return true - #endif - } - - public class func detachNewThread(_ block: @escaping @Sendable () -> Void) { - Thread(block: block).start() - } - - public class func sleep(forTimeInterval interval: TimeInterval) { - guard interval > 0 else { return } - var request = timespec() - request.tv_sec = time_t(interval) - request.tv_nsec = Int((interval - Double(Int(interval))) * 1_000_000_000) - var remaining = timespec() - while nanosleep(&request, &remaining) != 0 && errno == EINTR { - request = remaining - } - } - - public class func sleep(until date: Date) { - sleep(forTimeInterval: date.timeIntervalSinceNow) - } - - public class func exit() { - #if os(WASI) && !_runtime(_multithreaded) - Foundation_exit(0) - #else - #if os(WASI) - fatalError("Thread.exit is unavailable in wasi-libc; return from the thread entry instead") - #else - pthread_exit(nil) - #endif - #endif - } -} - -#if !(os(WASI) && !_runtime(_multithreaded)) -// A thread's start argument: optional in Glibc's pthread_create, not in -// Bionic's. -private func _pointer(_ pointer: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer { pointer! } -private func _pointer(_ pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { pointer } - -nonisolated(unsafe) private let _threadKey: pthread_key_t = { - var key = pthread_key_t() - pthread_key_create(&key, nil) - return key -}() -#else -private func Foundation_exit(_ code: Int32) -> Never { - exit(code) -} -#endif diff --git a/foundation/URLError.swift b/foundation/URLError.swift deleted file mode 100644 index a744baae..00000000 --- a/foundation/URLError.swift +++ /dev/null @@ -1,304 +0,0 @@ -// URLError, as Apple's Foundation has it: a code from NSURLErrorDomain and -// the user info that goes with it (the failing URL above all). Off Apple -// platforms it is a plain Swift error, like swift-foundation's CocoaError -// and POSIXError: no NSError behind it. And `localizedDescription` on every -// error, which apps show; in English (there are no strings tables). - -import FoundationEssentials - -public struct URLError: Error, Hashable, Sendable { - /// The error's code, one of the static members below. - public struct Code: RawRepresentable, Hashable, Sendable { - public let rawValue: Int - - public init(rawValue: Int) { - self.rawValue = rawValue - } - - /// An error matches a code when it is a URLError with that code: - /// `catch URLError.Code.timedOut`. - public static func ~= (match: Self, error: any Error) -> Bool { - (error as? URLError)?.code == match - } - } - - /// Why the network was unavailable to a request that allowed less of - /// it (`allowsCellularAccess`, `allowsExpensiveNetworkAccess`…). - public enum NetworkUnavailableReason: Int, Sendable { - case cellular = 0 - case expensive = 1 - case constrained = 2 - case ultraConstrained = 3 - } - - /// Why the system cancelled a background session's task. - public enum BackgroundTaskCancelledReason: Int, Sendable { - case userForceQuitApplication = 0 - case backgroundUpdatesDisabled = 1 - case insufficientSystemResources = 2 - } - - public let code: Code - - // Apple's is an NSDictionary, which holds anything. - public nonisolated(unsafe) let userInfo: [String: Any] - - public init(_ code: Self.Code, userInfo: [String: Any] = [:]) { - self.code = code - self.userInfo = userInfo - } - - public static var errorDomain: String { "NSURLErrorDomain" } - - public var errorCode: Int { code.rawValue } - - public var errorUserInfo: [String: Any] { userInfo } - - /// The URL that failed (`NSURLErrorFailingURLErrorKey`). - public var failingURL: URL? { - userInfo[_URLErrorKey.failingURL] as? URL - ?? (userInfo[_URLErrorKey.failingURLString] as? String).flatMap { URL(string: $0) } - } - - public var networkUnavailableReason: NetworkUnavailableReason? { - (userInfo[_URLErrorKey.networkUnavailableReason] as? Int).flatMap(NetworkUnavailableReason.init(rawValue:)) - } - - public var backgroundTaskCancelledReason: BackgroundTaskCancelledReason? { - (userInfo[_URLErrorKey.backgroundTaskCancelledReason] as? Int) - .flatMap(BackgroundTaskCancelledReason.init(rawValue:)) - } - - /// What a cancelled download leaves to resume it from; Isomer's - /// downloads do not resume, so there is none. - public var downloadTaskResumeData: Data? { - userInfo[_URLErrorKey.downloadTaskResumeData] as? Data - } - - /// What a cancelled upload leaves to resume it from; Isomer's uploads do - /// not resume, so there is none. - public var uploadTaskResumeData: Data? { - userInfo[_URLErrorKey.uploadTaskResumeData] as? Data - } - - // Equal as NSErrors are: the same code about the same URL. - public static func == (lhs: URLError, rhs: URLError) -> Bool { - lhs.code == rhs.code && lhs.failingURL == rhs.failingURL - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(code) - } -} - -/// The keys of a URLError's user info, as Apple's Foundation names them. -enum _URLErrorKey { - static let failingURL = "NSErrorFailingURLKey" - static let failingURLString = "NSErrorFailingURLStringKey" - static let localizedDescription = "NSLocalizedDescription" - static let debugDescription = "NSDebugDescription" - static let underlyingError = "NSUnderlyingError" - static let networkUnavailableReason = "NSURLErrorNetworkUnavailableReasonKey" - static let backgroundTaskCancelledReason = "NSURLErrorBackgroundTaskCancelledReasonKey" - static let downloadTaskResumeData = "NSURLSessionDownloadTaskResumeData" - static let uploadTaskResumeData = "NSURLSessionUploadTaskResumeData" -} - -extension URLError { - /// An error about `url`, with the user info Apple's has for it. - init(_ code: Code, url: URL?, debugDescription: String = "", underlying: (any Error)? = nil) { - var userInfo: [String: Any] = [:] - if let url { - userInfo[_URLErrorKey.failingURL] = url - userInfo[_URLErrorKey.failingURLString] = url.absoluteString - } - if !debugDescription.isEmpty { userInfo[_URLErrorKey.debugDescription] = debugDescription } - if let underlying { userInfo[_URLErrorKey.underlyingError] = underlying } - self.init(code, userInfo: userInfo) - } - - /// The description Apple's Foundation gives the code, in English; nil - /// for the codes it describes only by number. - var _description: String? { - switch code { - case .unknown: "unknown error" - case .cancelled: "cancelled" - case .badURL: "bad URL" - case .timedOut: "The request timed out." - case .unsupportedURL: "unsupported URL" - case .cannotFindHost: "A server with the specified hostname could not be found." - case .cannotConnectToHost: "Could not connect to the server." - case .networkConnectionLost: "The network connection was lost." - case .dnsLookupFailed: "DNS lookup error" - case .httpTooManyRedirects: "too many HTTP redirects" - case .resourceUnavailable: "resource unavailable" - case .notConnectedToInternet: "The Internet connection appears to be offline." - case .redirectToNonExistentLocation: "redirected to nowhere" - case .badServerResponse: "bad server response" - case .userAuthenticationRequired: "user authentication required" - case .zeroByteResource: "zero byte resource" - case .cannotDecodeRawData: "cannot decode raw data" - case .cannotDecodeContentData: "cannot decode content data" - case .cannotParseResponse: "cannot parse response" - case .appTransportSecurityRequiresSecureConnection: - "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." - case .fileDoesNotExist: "The requested URL was not found on this server." - case .fileIsDirectory: "file is directory" - case .noPermissionsToReadFile: "You do not have permission to access the requested resource." - case .dataLengthExceedsMaximum: "resource exceeds maximum size" - case .secureConnectionFailed: "An SSL error has occurred and a secure connection to the server cannot be made." - case .serverCertificateHasBadDate: "The certificate for this server has expired." - case .serverCertificateUntrusted: "The certificate for this server is invalid." - case .serverCertificateHasUnknownRoot: - "The certificate for this server was signed by an unknown certifying authority." - case .serverCertificateNotYetValid: "The certificate for this server is not yet valid." - case .clientCertificateRejected: "The server did not accept the certificate." - case .clientCertificateRequired: "The server requires a client certificate." - case .cannotLoadFromNetwork: "can’t load from network" - case .internationalRoamingOff: "International roaming is currently off." - case .callIsActive: "A data connection cannot be established since a call is currently active." - case .dataNotAllowed: "A data connection is not currently allowed." - default: nil - } - } -} - -// The codes, on Code and on URLError both, as Apple's Foundation has them. -extension URLError.Code { - public static var unknown: URLError.Code { URLError.Code(rawValue: -1) } - public static var cancelled: URLError.Code { URLError.Code(rawValue: -999) } - public static var badURL: URLError.Code { URLError.Code(rawValue: -1000) } - public static var timedOut: URLError.Code { URLError.Code(rawValue: -1001) } - public static var unsupportedURL: URLError.Code { URLError.Code(rawValue: -1002) } - public static var cannotFindHost: URLError.Code { URLError.Code(rawValue: -1003) } - public static var cannotConnectToHost: URLError.Code { URLError.Code(rawValue: -1004) } - public static var networkConnectionLost: URLError.Code { URLError.Code(rawValue: -1005) } - public static var dnsLookupFailed: URLError.Code { URLError.Code(rawValue: -1006) } - public static var httpTooManyRedirects: URLError.Code { URLError.Code(rawValue: -1007) } - public static var resourceUnavailable: URLError.Code { URLError.Code(rawValue: -1008) } - public static var notConnectedToInternet: URLError.Code { URLError.Code(rawValue: -1009) } - public static var redirectToNonExistentLocation: URLError.Code { URLError.Code(rawValue: -1010) } - public static var badServerResponse: URLError.Code { URLError.Code(rawValue: -1011) } - public static var userCancelledAuthentication: URLError.Code { URLError.Code(rawValue: -1012) } - public static var userAuthenticationRequired: URLError.Code { URLError.Code(rawValue: -1013) } - public static var zeroByteResource: URLError.Code { URLError.Code(rawValue: -1014) } - public static var cannotDecodeRawData: URLError.Code { URLError.Code(rawValue: -1015) } - public static var cannotDecodeContentData: URLError.Code { URLError.Code(rawValue: -1016) } - public static var cannotParseResponse: URLError.Code { URLError.Code(rawValue: -1017) } - public static var internationalRoamingOff: URLError.Code { URLError.Code(rawValue: -1018) } - public static var callIsActive: URLError.Code { URLError.Code(rawValue: -1019) } - public static var dataNotAllowed: URLError.Code { URLError.Code(rawValue: -1020) } - public static var requestBodyStreamExhausted: URLError.Code { URLError.Code(rawValue: -1021) } - public static var appTransportSecurityRequiresSecureConnection: URLError.Code { URLError.Code(rawValue: -1022) } - public static var fileDoesNotExist: URLError.Code { URLError.Code(rawValue: -1100) } - public static var fileIsDirectory: URLError.Code { URLError.Code(rawValue: -1101) } - public static var noPermissionsToReadFile: URLError.Code { URLError.Code(rawValue: -1102) } - public static var dataLengthExceedsMaximum: URLError.Code { URLError.Code(rawValue: -1103) } - public static var secureConnectionFailed: URLError.Code { URLError.Code(rawValue: -1200) } - public static var serverCertificateHasBadDate: URLError.Code { URLError.Code(rawValue: -1201) } - public static var serverCertificateUntrusted: URLError.Code { URLError.Code(rawValue: -1202) } - public static var serverCertificateHasUnknownRoot: URLError.Code { URLError.Code(rawValue: -1203) } - public static var serverCertificateNotYetValid: URLError.Code { URLError.Code(rawValue: -1204) } - public static var clientCertificateRejected: URLError.Code { URLError.Code(rawValue: -1205) } - public static var clientCertificateRequired: URLError.Code { URLError.Code(rawValue: -1206) } - public static var cannotLoadFromNetwork: URLError.Code { URLError.Code(rawValue: -2000) } - public static var cannotCreateFile: URLError.Code { URLError.Code(rawValue: -3000) } - public static var cannotOpenFile: URLError.Code { URLError.Code(rawValue: -3001) } - public static var cannotCloseFile: URLError.Code { URLError.Code(rawValue: -3002) } - public static var cannotWriteToFile: URLError.Code { URLError.Code(rawValue: -3003) } - public static var cannotRemoveFile: URLError.Code { URLError.Code(rawValue: -3004) } - public static var cannotMoveFile: URLError.Code { URLError.Code(rawValue: -3005) } - public static var downloadDecodingFailedMidStream: URLError.Code { URLError.Code(rawValue: -3006) } - public static var downloadDecodingFailedToComplete: URLError.Code { URLError.Code(rawValue: -3007) } - public static var backgroundSessionRequiresSharedContainer: URLError.Code { URLError.Code(rawValue: -995) } - public static var backgroundSessionInUseByAnotherProcess: URLError.Code { URLError.Code(rawValue: -996) } - public static var backgroundSessionWasDisconnected: URLError.Code { URLError.Code(rawValue: -997) } -} - -extension URLError { - public static var unknown: URLError.Code { .unknown } - public static var cancelled: URLError.Code { .cancelled } - public static var badURL: URLError.Code { .badURL } - public static var timedOut: URLError.Code { .timedOut } - public static var unsupportedURL: URLError.Code { .unsupportedURL } - public static var cannotFindHost: URLError.Code { .cannotFindHost } - public static var cannotConnectToHost: URLError.Code { .cannotConnectToHost } - public static var networkConnectionLost: URLError.Code { .networkConnectionLost } - public static var dnsLookupFailed: URLError.Code { .dnsLookupFailed } - public static var httpTooManyRedirects: URLError.Code { .httpTooManyRedirects } - public static var resourceUnavailable: URLError.Code { .resourceUnavailable } - public static var notConnectedToInternet: URLError.Code { .notConnectedToInternet } - public static var redirectToNonExistentLocation: URLError.Code { .redirectToNonExistentLocation } - public static var badServerResponse: URLError.Code { .badServerResponse } - public static var userCancelledAuthentication: URLError.Code { .userCancelledAuthentication } - public static var userAuthenticationRequired: URLError.Code { .userAuthenticationRequired } - public static var zeroByteResource: URLError.Code { .zeroByteResource } - public static var cannotDecodeRawData: URLError.Code { .cannotDecodeRawData } - public static var cannotDecodeContentData: URLError.Code { .cannotDecodeContentData } - public static var cannotParseResponse: URLError.Code { .cannotParseResponse } - public static var internationalRoamingOff: URLError.Code { .internationalRoamingOff } - public static var callIsActive: URLError.Code { .callIsActive } - public static var dataNotAllowed: URLError.Code { .dataNotAllowed } - public static var requestBodyStreamExhausted: URLError.Code { .requestBodyStreamExhausted } - public static var appTransportSecurityRequiresSecureConnection: URLError.Code { - .appTransportSecurityRequiresSecureConnection - } - public static var fileDoesNotExist: URLError.Code { .fileDoesNotExist } - public static var fileIsDirectory: URLError.Code { .fileIsDirectory } - public static var noPermissionsToReadFile: URLError.Code { .noPermissionsToReadFile } - public static var dataLengthExceedsMaximum: URLError.Code { .dataLengthExceedsMaximum } - public static var secureConnectionFailed: URLError.Code { .secureConnectionFailed } - public static var serverCertificateHasBadDate: URLError.Code { .serverCertificateHasBadDate } - public static var serverCertificateUntrusted: URLError.Code { .serverCertificateUntrusted } - public static var serverCertificateHasUnknownRoot: URLError.Code { .serverCertificateHasUnknownRoot } - public static var serverCertificateNotYetValid: URLError.Code { .serverCertificateNotYetValid } - public static var clientCertificateRejected: URLError.Code { .clientCertificateRejected } - public static var clientCertificateRequired: URLError.Code { .clientCertificateRequired } - public static var cannotLoadFromNetwork: URLError.Code { .cannotLoadFromNetwork } - public static var cannotCreateFile: URLError.Code { .cannotCreateFile } - public static var cannotOpenFile: URLError.Code { .cannotOpenFile } - public static var cannotCloseFile: URLError.Code { .cannotCloseFile } - public static var cannotWriteToFile: URLError.Code { .cannotWriteToFile } - public static var cannotRemoveFile: URLError.Code { .cannotRemoveFile } - public static var cannotMoveFile: URLError.Code { .cannotMoveFile } - public static var downloadDecodingFailedMidStream: URLError.Code { .downloadDecodingFailedMidStream } - public static var downloadDecodingFailedToComplete: URLError.Code { .downloadDecodingFailedToComplete } - public static var backgroundSessionRequiresSharedContainer: URLError.Code { - .backgroundSessionRequiresSharedContainer - } - public static var backgroundSessionInUseByAnotherProcess: URLError.Code { .backgroundSessionInUseByAnotherProcess } - public static var backgroundSessionWasDisconnected: URLError.Code { .backgroundSessionWasDisconnected } -} - -// MARK: - localizedDescription - -extension Error { - /// The error described for a person, as Apple's Foundation describes - /// it: a `LocalizedError`'s `errorDescription`, the description of a - /// URLError's code, else "The operation couldn’t be completed." with - /// the error's domain and code. - public var localizedDescription: String { - if let error = _existingNSError(self) { - return error.localizedDescription - } - if let error = self as? any LocalizedError, let description = error.errorDescription { - return description - } - if let error = self as? URLError { - if let description = error.userInfo[_URLErrorKey.localizedDescription] as? String { - return description - } - if let description = error._description { - return description - } - return "The operation couldn’t be completed. (\(URLError.errorDomain) error \(error.code.rawValue).)" - } - if let error = self as? CocoaError { - return "The operation couldn’t be completed. (\(CocoaError.errorDomain) error \(error.code.rawValue).)" - } - if let error = self as? POSIXError { - return "The operation couldn’t be completed. (\(POSIXError.errorDomain) error \(error.code.rawValue).)" - } - return "The operation couldn’t be completed. (\(_domain) error \(_code).)" - } -} diff --git a/foundation/URLRequest.swift b/foundation/URLRequest.swift deleted file mode 100644 index 87b8ad11..00000000 --- a/foundation/URLRequest.swift +++ /dev/null @@ -1,206 +0,0 @@ -// URLRequest, as Apple's Foundation has it: what to load and how. A value -// type here as there; Apple's keeps an NSURLRequest inside, this one its -// fields. Header field names match without regard to case, and the fields -// keep the order they were set in, which is the order the transport sends -// them (docs/parity/Foundation.md: what of a request a transport honours). - -import FoundationEssentials - -public struct URLRequest: Hashable, Sendable { - // Apple's are NSURLRequest's (`URLRequest.CachePolicy` is a typealias - // of `NSURLRequest.CachePolicy`); Isomer has no NSURLRequest. - - /// Where a response may come from: the network, or a cache. Isomer's - /// Foundation keeps no cache, so every policy loads from the network - /// (and the two that never load fail as an empty cache would). - public enum CachePolicy: UInt, Sendable { - case useProtocolCachePolicy = 0 - case reloadIgnoringLocalCacheData = 1 - case reloadIgnoringLocalAndRemoteCacheData = 4 - case returnCacheDataElseLoad = 2 - case returnCacheDataDontLoad = 3 - case reloadRevalidatingCacheData = 5 - - public static var reloadIgnoringCacheData: URLRequest.CachePolicy { .reloadIgnoringLocalCacheData } - } - - /// The kind of traffic a request is, for the system's network - /// scheduling; kept, not acted on. - public enum NetworkServiceType: UInt, Sendable { - case `default` = 0 - case video = 2 - case background = 3 - case voice = 4 - case responsiveData = 6 - case avStreaming = 8 - case responsiveAV = 9 - case callSignaling = 11 - } - - /// Who asked for a request: the developer or the person using the app. - public enum Attribution: UInt, Sendable { - case developer = 0 - case user = 1 - } - - public var url: URL? - public var cachePolicy: CachePolicy - public var timeoutInterval: TimeInterval - public var mainDocumentURL: URL? - public var networkServiceType: NetworkServiceType = .default - public var allowsCellularAccess = true - public var allowsExpensiveNetworkAccess = true - public var allowsConstrainedNetworkAccess = true - public var allowsUltraConstrainedNetworkAccess = true - public var assumesHTTP3Capable = false - public var requiresDNSSECValidation = false - public var allowsPersistentDNS = false - public var attribution: Attribution = .developer - public var cookiePartitionIdentifier: String? - public var httpShouldHandleCookies = true - - private var method: String? - private var fields: [(name: String, value: String)] = [] - private var body: Body? - - /// A request has a body of bytes or a stream, not both. - private enum Body { - case data(Data) - case stream(InputStream) - } - - public init( - url: URL, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 60.0 - ) { - self.url = url - self.cachePolicy = cachePolicy - self.timeoutInterval = timeoutInterval - } - - /// The method; "GET" until another is set (setting nil sets "GET" - /// again). - public var httpMethod: String? { - get { method ?? "GET" } - set { method = newValue } - } - - /// The header fields by name; nil when there are none. Setting replaces - /// them all. - public var allHTTPHeaderFields: [String: String]? { - get { - if fields.isEmpty { return nil } - var all: [String: String] = [:] - for field in fields { all[field.name] = field.value } - return all - } - set { - fields = (newValue ?? [:]).sorted { $0.key < $1.key }.map { (name: $0.key, value: $0.value) } - } - } - - /// The value of the field named `field` (in any case); nil when there - /// is none. - public func value(forHTTPHeaderField field: String) -> String? { - fields.first { $0.name.caseInsensitiveCompare(field) == .orderedSame }?.value - } - - /// Sets the field named `field` (in any case) to `value`, or removes it - /// when `value` is nil. - public mutating func setValue(_ value: String?, forHTTPHeaderField field: String) { - if let index = fields.firstIndex(where: { $0.name.caseInsensitiveCompare(field) == .orderedSame }) { - if let value { - fields[index].value = value - } else { - fields.remove(at: index) - } - } else if let value { - fields.append((name: field, value: value)) - } - } - - /// Adds `value` to the field named `field`, after a comma when it has - /// one already. - public mutating func addValue(_ value: String, forHTTPHeaderField field: String) { - if let index = fields.firstIndex(where: { $0.name.caseInsensitiveCompare(field) == .orderedSame }) { - fields[index].value += "," + value - } else { - fields.append((name: field, value: value)) - } - } - - /// The body sent with the request. Setting it clears `httpBodyStream`. - public var httpBody: Data? { - get { - if case .data(let data) = body { return data } - return nil - } - set { body = newValue.map { .data($0) } } - } - - /// A stream the body is read from, read whole when the request is - /// sent. Setting it clears `httpBody`. - public var httpBodyStream: InputStream? { - get { - if case .stream(let stream) = body { return stream } - return nil - } - set { body = newValue.map { .stream($0) } } - } - - /// The header fields in the order they were set: what is sent. - var _headerFields: [(name: String, value: String)] { fields } - - public static func == (lhs: URLRequest, rhs: URLRequest) -> Bool { - let sameBody: Bool - switch (lhs.body, rhs.body) { - case (nil, nil): sameBody = true - case (.data(let a)?, .data(let b)?): sameBody = a == b - case (.stream(let a)?, .stream(let b)?): sameBody = a === b - default: sameBody = false - } - return sameBody && lhs.url == rhs.url && lhs.cachePolicy == rhs.cachePolicy - && lhs.timeoutInterval == rhs.timeoutInterval && lhs.mainDocumentURL == rhs.mainDocumentURL - && lhs.httpMethod == rhs.httpMethod && lhs.allHTTPHeaderFields == rhs.allHTTPHeaderFields - && lhs.networkServiceType == rhs.networkServiceType && lhs.allowsCellularAccess == rhs.allowsCellularAccess - && lhs.allowsExpensiveNetworkAccess == rhs.allowsExpensiveNetworkAccess - && lhs.allowsConstrainedNetworkAccess == rhs.allowsConstrainedNetworkAccess - && lhs.allowsUltraConstrainedNetworkAccess == rhs.allowsUltraConstrainedNetworkAccess - && lhs.assumesHTTP3Capable == rhs.assumesHTTP3Capable - && lhs.requiresDNSSECValidation == rhs.requiresDNSSECValidation - && lhs.allowsPersistentDNS == rhs.allowsPersistentDNS && lhs.attribution == rhs.attribution - && lhs.cookiePartitionIdentifier == rhs.cookiePartitionIdentifier - && lhs.httpShouldHandleCookies == rhs.httpShouldHandleCookies - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(url) - hasher.combine(httpMethod) - hasher.combine(httpBody) - } -} - -extension URLRequest: CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { - public var description: String { - url?.description ?? "url: nil" - } - - public var debugDescription: String { - description - } - - public var customMirror: Mirror { - var children: [(label: String?, value: Any)] = [] - children.append((label: "url", value: url as Any)) - children.append((label: "cachePolicy", value: cachePolicy.rawValue)) - children.append((label: "timeoutInterval", value: timeoutInterval)) - if let mainDocumentURL { children.append((label: "mainDocumentURL", value: mainDocumentURL)) } - children.append((label: "networkServiceType", value: networkServiceType)) - children.append((label: "allowsCellularAccess", value: allowsCellularAccess)) - children.append((label: "httpMethod", value: httpMethod as Any)) - if let allHTTPHeaderFields { children.append((label: "allHTTPHeaderFields", value: allHTTPHeaderFields)) } - if let httpBody { children.append((label: "httpBody", value: httpBody)) } - if let httpBodyStream { children.append((label: "httpBodyStream", value: httpBodyStream)) } - children.append((label: "httpShouldHandleCookies", value: httpShouldHandleCookies)) - return Mirror(self, children: children, displayStyle: .struct) - } -} diff --git a/foundation/URLResourceValues.swift b/foundation/URLResourceValues.swift deleted file mode 100644 index 52bcf148..00000000 --- a/foundation/URLResourceValues.swift +++ /dev/null @@ -1,39 +0,0 @@ -// URLResourceValues and URL.setResourceValues(_:), for what an app sets on -// its files: a new name, and the backup and hidden flags. A name renames the -// item in its directory and moves the URL with it, as Apple's does. The -// flags are accepted and not acted on: Android backs up an app's files by -// its manifest's rules, not per file, and the web (IndexedDB) and WASI -// keep no such flag. Reading values back (`resourceValues(forKeys:)`) needs -// URLResourceKey, which swift-foundation declares off Apple's platforms with -// no members: not here yet. - -import FoundationEssentials - -public struct URLResourceValues { - public init() {} - - /// The item's name in its directory: setting it renames the item. - public var name: String? - - /// Accepted, not acted on (see above). - public var isHidden: Bool? - - /// Accepted, not acted on (see above). - public var isExcludedFromBackup: Bool? -} - -extension URL { - /// Applies `values` to the file this URL names: a `name` renames it - /// (and this URL becomes the new one); the flags are accepted. - public mutating func setResourceValues(_ values: URLResourceValues) throws { - // "NSURL": NSURLErrorKey, internal to swift-foundation. - guard isFileURL else { throw CocoaError(.fileWriteUnsupportedScheme, userInfo: ["NSURL": self]) } - guard let name = values.name, name != lastPathComponent else { return } - guard !name.isEmpty, name != ".", name != "..", !name.contains("/") else { - throw CocoaError(.fileWriteInvalidFileName, userInfo: ["NSURL": self]) - } - let renamed = deletingLastPathComponent().appendingPathComponent(name, isDirectory: hasDirectoryPath) - try FileManager.default.moveItem(at: self, to: renamed) - self = renamed - } -} diff --git a/foundation/URLResponse.swift b/foundation/URLResponse.swift deleted file mode 100644 index 90cc89b9..00000000 --- a/foundation/URLResponse.swift +++ /dev/null @@ -1,156 +0,0 @@ -// URLResponse and HTTPURLResponse, as Apple's Foundation has them: what a -// load's response said about itself. Swift classes, not NSObject -// subclasses; immutable, as Apple's are. - -import FoundationEssentials - -open class URLResponse: @unchecked Sendable { - private let responseURL: URL? - private let responseMIMEType: String? - private let contentLength: Int64 - private let encodingName: String? - - public init( - url URL: URL, mimeType MIMEType: String?, expectedContentLength length: Int, textEncodingName name: String? - ) { - responseURL = URL - responseMIMEType = MIMEType - contentLength = Int64(length) - encodingName = name - } - - open var url: URL? { responseURL } - - /// The type of the body ("text/html"), lowercased; nil when unknown. - open var mimeType: String? { responseMIMEType } - - /// The length of the body; -1 when unknown. - open var expectedContentLength: Int64 { contentLength } - - /// The body's character set ("utf-8"); nil when not given. - open var textEncodingName: String? { encodingName } - - /// A name to save the body under: the URL's last path component, else - /// "Unknown". - open var suggestedFilename: String? { - let last = responseURL?.lastPathComponent ?? "" - return last.isEmpty || last == "/" ? "Unknown" : last - } -} - -open class HTTPURLResponse: URLResponse, @unchecked Sendable { - private let status: Int - private let fields: [String: String] - - /// A response to a request for `url`; nil when `statusCode` is not one - /// (outside 100 to 999). The MIME type, text encoding and expected - /// length are read from the header fields. - public init?(url: URL, statusCode: Int, httpVersion HTTPVersion: String?, headerFields: [String: String]?) { - guard (100...999).contains(statusCode) else { return nil } - let fields = headerFields ?? [:] - status = statusCode - self.fields = fields - func field(_ name: String) -> String? { - fields.first { $0.key.caseInsensitiveCompare(name) == .orderedSame }?.value - } - var mimeType: String? - var encoding: String? - if let contentType = field("Content-Type") { - let parts = contentType.split(separator: ";").map { $0.trimmingCharacters(in: .whitespaces) } - if let type = parts.first, !type.isEmpty { mimeType = type.lowercased() } - for parameter in parts.dropFirst() { - let pair = parameter.split(separator: "=", maxSplits: 1).map(String.init) - if pair.count == 2, pair[0].lowercased() == "charset" { - encoding = pair[1].trimmingCharacters(in: CharacterSet(charactersIn: "\"")).lowercased() - } - } - } - let length = field("Content-Length").flatMap { Int($0.trimmingCharacters(in: .whitespaces)) } ?? -1 - super.init(url: url, mimeType: mimeType, expectedContentLength: length, textEncodingName: encoding) - } - - /// The status code: 200, 404… - open var statusCode: Int { status } - - /// The header fields by name, as the server sent them. - open var allHeaderFields: [AnyHashable: Any] { - var all: [AnyHashable: Any] = [:] - for (name, value) in fields { all[name] = value } - return all - } - - /// The value of the field named `field` (in any case); nil when there - /// is none. - open func value(forHTTPHeaderField field: String) -> String? { - fields.first { $0.key.caseInsensitiveCompare(field) == .orderedSame }?.value - } - - /// The name given in a `Content-Disposition` field, else the URL's last - /// path component. - open override var suggestedFilename: String? { - if let disposition = value(forHTTPHeaderField: "Content-Disposition") { - for parameter in disposition.split(separator: ";") { - let pair = parameter.split(separator: "=", maxSplits: 1) - .map { $0.trimmingCharacters(in: .whitespaces) } - if pair.count == 2, pair[0].lowercased() == "filename" { - let name = pair[1].trimmingCharacters(in: CharacterSet(charactersIn: "\"")) - if !name.isEmpty { return name } - } - } - } - return super.suggestedFilename - } - - /// The status code described, as Apple's Foundation describes it (in - /// English, lowercased): "no error" for 200, "not found" for 404. - open class func localizedString(forStatusCode statusCode: Int) -> String { - switch statusCode { - case 100: "continue" - case 101: "switching protocols" - case 200: "no error" - case 201: "created" - case 202: "accepted" - case 203: "non-authoritative information" - case 204: "no content" - case 205: "reset content" - case 206: "partial content" - case 300: "multiple choices" - case 301: "moved permanently" - case 302: "found" - case 303: "see other" - case 304: "not modified" - case 305: "needs proxy" - case 307: "temporarily redirected" - case 308: "permanent redirect" - case 400: "bad request" - case 401: "unauthorized" - case 402: "payment required" - case 403: "forbidden" - case 404: "not found" - case 405: "method not allowed" - case 406: "unacceptable" - case 407: "proxy authentication required" - case 408: "request timed out" - case 409: "conflict" - case 410: "no longer exists" - case 411: "length required" - case 412: "precondition failed" - case 413: "request too large" - case 414: "requested URL too long" - case 415: "unsupported media type" - case 416: "requested range not satisfiable" - case 417: "expectation failed" - case 500: "internal server error" - case 501: "unimplemented" - case 502: "bad gateway" - case 503: "service unavailable" - case 504: "gateway timed out" - case 505: "unsupported version" - case 100..<200: "informational" - case 200..<300: "success" - case 300..<400: "redirected" - case 400..<500: "client error" - default: "server error" - } - } -} diff --git a/foundation/URLSession.swift b/foundation/URLSession.swift deleted file mode 100644 index 5d3f0e0f..00000000 --- a/foundation/URLSession.swift +++ /dev/null @@ -1,689 +0,0 @@ -// URLSession and URLSessionConfiguration, as Apple's Foundation has them, -// without delegates (docs/parity/Foundation.md). A session makes tasks; -// a task loads its request when resumed and hands what it got to its -// completion handler, or to the `async` call that made it. Where a request -// goes: -// -// - file: URLs are read from the file system, data: URLs decoded, as -// Apple's URLSession does, with no transport; -// - http and https go through the HTTP transport the host installed -// (IsomerFoundation's IsomerNetwork.http), ws and wss through its -// WebSocket transport (URLSessionWebSocketTask.swift). With none -// installed a task fails with URLError.notConnectedToInternet: to the -// app the program is offline, which it handles as it would on a device -// (an unsupported-URL error would read as its own mistake); -// - any other scheme fails with URLError.unsupportedURL. -// -// Completion handlers run on a task of their own (Apple's run on the -// session's delegate queue, an OperationQueue, which Isomer does not have), -// never inside the call that made the task. - -import FoundationEssentials -import Synchronization -internal import IsomerFoundation - -open class URLSessionConfiguration: @unchecked Sendable { - /// What a session uses when made with none: a new configuration each - /// time, the defaults below. - open class var `default`: URLSessionConfiguration { URLSessionConfiguration() } - - /// A configuration that keeps nothing on disk. Isomer's sessions keep - /// no caches, cookies or credentials of their own, so it is the default - /// one. - open class var ephemeral: URLSessionConfiguration { URLSessionConfiguration() } - - init() {} - - /// A background session's identifier; Isomer has no background - /// sessions, so there is none. - open var identifier: String? { nil } - - open var requestCachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy - - /// How long a request may wait on the server, to connect or for more of - /// its response, when the request does not say (its `timeoutInterval` - /// left at the default 60). - open var timeoutIntervalForRequest: TimeInterval = 60 - - /// How long a WebSocket's or a request's whole exchange may take; kept, - /// and the hosts' stacks apply their own. - open var timeoutIntervalForResource: TimeInterval = 604_800 - - /// Header fields every request of the session sends, after its own and - /// unless it set them itself. - open var httpAdditionalHeaders: [AnyHashable: Any]? - - // What steers Apple's network stack, kept and not acted on: the - // platform's stack decides how its connections are made. - open var networkServiceType: URLRequest.NetworkServiceType = .default - open var allowsCellularAccess = true - open var allowsExpensiveNetworkAccess = true - open var allowsConstrainedNetworkAccess = true - open var allowsUltraConstrainedNetworkAccess = true - open var waitsForConnectivity = false - open var isDiscretionary = false - open var sharedContainerIdentifier: String? - open var sessionSendsLaunchEvents = false - open var httpShouldSetCookies = true - open var httpMaximumConnectionsPerHost = 6 - open var requiresDNSSECValidation = false - open var usesClassicLoadingMode = true - open var enablesEarlyData = false - open var multipathServiceType: MultipathServiceType = .none - - /// Where the session's cookies and credentials are kept: kept, and not - /// acted on (the hosts' stacks keep their own; HTTPCookieStorage). - open var httpCookieStorage: HTTPCookieStorage? = .shared - open var urlCredentialStorage: URLCredentialStorage? = .shared - - /// How a connection may use more than one network at a time - /// (Multipath TCP); kept, not acted on. - public enum MultipathServiceType: Int, Sendable { - case none = 0 - case handover = 1 - case interactive = 2 - case aggregate = 3 - } - - /// A copy: what a session keeps (Apple's `@NSCopying`). - func _copy() -> URLSessionConfiguration { - let copy = URLSessionConfiguration() - copy.requestCachePolicy = requestCachePolicy - copy.timeoutIntervalForRequest = timeoutIntervalForRequest - copy.timeoutIntervalForResource = timeoutIntervalForResource - copy.httpAdditionalHeaders = httpAdditionalHeaders - copy.networkServiceType = networkServiceType - copy.allowsCellularAccess = allowsCellularAccess - copy.allowsExpensiveNetworkAccess = allowsExpensiveNetworkAccess - copy.allowsConstrainedNetworkAccess = allowsConstrainedNetworkAccess - copy.allowsUltraConstrainedNetworkAccess = allowsUltraConstrainedNetworkAccess - copy.waitsForConnectivity = waitsForConnectivity - copy.isDiscretionary = isDiscretionary - copy.sharedContainerIdentifier = sharedContainerIdentifier - copy.sessionSendsLaunchEvents = sessionSendsLaunchEvents - copy.httpShouldSetCookies = httpShouldSetCookies - copy.httpMaximumConnectionsPerHost = httpMaximumConnectionsPerHost - copy.requiresDNSSECValidation = requiresDNSSECValidation - copy.usesClassicLoadingMode = usesClassicLoadingMode - copy.enablesEarlyData = enablesEarlyData - copy.multipathServiceType = multipathServiceType - copy.httpCookieStorage = httpCookieStorage - copy.urlCredentialStorage = urlCredentialStorage - return copy - } - - /// The additional header fields as text, in a stable order. - var _additionalHeaderFields: [(name: String, value: String)] { - (httpAdditionalHeaders ?? [:]) - .map { (name: ($0.key as? String) ?? "\($0.key)", value: ($0.value as? String) ?? "\($0.value)") } - .sorted { $0.name < $1.name } - } -} - -open class URLSession: @unchecked Sendable { - private struct State { - var tasks: [Int: URLSessionTask] = [:] - var nextIdentifier = 1 - var invalidated = false - var sessionDescription: String? - } - - let sessionConfiguration: URLSessionConfiguration - private let isShared: Bool - private let state = Mutex(State()) - - private static let sharedSession = URLSession(configuration: .default, shared: true) - - /// The session for requests that need no configuration of their own. - /// It cannot be invalidated. - open class var shared: URLSession { sharedSession } - - public init(configuration: URLSessionConfiguration) { - sessionConfiguration = configuration._copy() - isShared = false - } - - private init(configuration: URLSessionConfiguration, shared: Bool) { - sessionConfiguration = configuration - isShared = shared - } - - /// A copy of the session's configuration: changing it changes nothing. - open var configuration: URLSessionConfiguration { sessionConfiguration._copy() } - - open var sessionDescription: String? { - get { state.withLock { $0.sessionDescription } } - set { state.withLock { $0.sessionDescription = newValue } } - } - - // MARK: Invalidating - - /// Lets the session's tasks finish and takes no more. - open func finishTasksAndInvalidate() { - guard !isShared else { return } - state.withLock { $0.invalidated = true } - } - - /// Cancels the session's tasks and takes no more. - open func invalidateAndCancel() { - guard !isShared else { return } - let tasks = state.withLock { state in - state.invalidated = true - return Array(state.tasks.values) - } - for task in tasks { task.cancel() } - } - - /// Isomer's sessions keep no caches, cookies or credentials to empty. - open func reset(completionHandler: @escaping @Sendable () -> Void) { - Task { completionHandler() } - } - - public func reset() async {} - - /// Isomer's sessions keep nothing to write out. - open func flush(completionHandler: @escaping @Sendable () -> Void) { - Task { completionHandler() } - } - - public func flush() async {} - - // MARK: The session's tasks - - open func getTasksWithCompletionHandler( - _ completionHandler: - @escaping @Sendable ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) -> Void - ) { - let (data, uploads, downloads) = Self.sorted(liveTasks()) - Task { completionHandler(data, uploads, downloads) } - } - - open func getAllTasks(completionHandler: @escaping @Sendable ([URLSessionTask]) -> Void) { - let all = liveTasks() - Task { completionHandler(all) } - } - - public var tasks: ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) { - get async { Self.sorted(liveTasks()) } - } - - public var allTasks: [URLSessionTask] { - get async { liveTasks() } - } - - /// The tasks made and not yet completed, oldest first. - private func liveTasks() -> [URLSessionTask] { - state.withLock { $0.tasks.sorted { $0.key < $1.key }.map(\.value) } - } - - private static func sorted( - _ tasks: [URLSessionTask] - ) -> ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) { - let uploads = tasks.compactMap { $0 as? URLSessionUploadTask } - let data = tasks.compactMap { $0 as? URLSessionDataTask }.filter { !($0 is URLSessionUploadTask) } - let downloads = tasks.compactMap { $0 as? URLSessionDownloadTask } - return (data, uploads, downloads) - } - - /// The next task's identifier, the task kept until it completes. - func _register(_ make: (Int) -> Kind) -> Kind { - state.withLock { state in - if state.invalidated { - // As Apple's Foundation does (it raises an exception). - fatalError("Task created in a session that has been invalidated") - } - let identifier = state.nextIdentifier - state.nextIdentifier += 1 - let task = make(identifier) - state.tasks[identifier] = task - return task - } - } - - func _taskCompleted(_ task: URLSessionTask) { - state.withLock { _ = $0.tasks.removeValue(forKey: task.taskIdentifier) } - } - - // MARK: Data tasks - - open func dataTask(with request: URLRequest) -> URLSessionDataTask { - makeDataTask(request, upload: nil, completionHandler: nil) - } - - open func dataTask(with url: URL) -> URLSessionDataTask { - makeDataTask(URLRequest(url: url), upload: nil, completionHandler: nil) - } - - open func dataTask( - with request: URLRequest, completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void - ) -> URLSessionDataTask { - makeDataTask(request, upload: nil, completionHandler: completionHandler) - } - - open func dataTask( - with url: URL, completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void - ) -> URLSessionDataTask { - makeDataTask(URLRequest(url: url), upload: nil, completionHandler: completionHandler) - } - - // MARK: Upload tasks - - open func uploadTask(with request: URLRequest, from bodyData: Data) -> URLSessionUploadTask { - makeUploadTask(request, upload: .data(bodyData), completionHandler: nil) - } - - open func uploadTask( - with request: URLRequest, from bodyData: Data?, - completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void - ) -> URLSessionUploadTask { - makeUploadTask(request, upload: bodyData.map { .data($0) }, completionHandler: completionHandler) - } - - open func uploadTask(with request: URLRequest, fromFile fileURL: URL) -> URLSessionUploadTask { - makeUploadTask(request, upload: .file(fileURL), completionHandler: nil) - } - - open func uploadTask( - with request: URLRequest, fromFile fileURL: URL, - completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void - ) -> URLSessionUploadTask { - makeUploadTask(request, upload: .file(fileURL), completionHandler: completionHandler) - } - - // MARK: Download tasks - - open func downloadTask(with request: URLRequest) -> URLSessionDownloadTask { - makeDownloadTask(request, keepsFile: false, completionHandler: nil) - } - - open func downloadTask(with url: URL) -> URLSessionDownloadTask { - makeDownloadTask(URLRequest(url: url), keepsFile: false, completionHandler: nil) - } - - /// The handler gets the file the body was written to, in the temporary - /// directory; it is removed when the handler returns, so move it first. - open func downloadTask( - with request: URLRequest, completionHandler: @escaping @Sendable (URL?, URLResponse?, (any Error)?) -> Void - ) -> URLSessionDownloadTask { - makeDownloadTask(request, keepsFile: false, completionHandler: completionHandler) - } - - open func downloadTask( - with url: URL, completionHandler: @escaping @Sendable (URL?, URLResponse?, (any Error)?) -> Void - ) -> URLSessionDownloadTask { - makeDownloadTask(URLRequest(url: url), keepsFile: false, completionHandler: completionHandler) - } - - // MARK: WebSocket tasks - - open func webSocketTask(with url: URL) -> URLSessionWebSocketTask { - makeWebSocketTask(URLRequest(url: url), protocols: []) - } - - /// Offers `protocols` as the connection's subprotocols. - open func webSocketTask(with url: URL, protocols: [String]) -> URLSessionWebSocketTask { - makeWebSocketTask(URLRequest(url: url), protocols: protocols) - } - - /// Offers the subprotocols the request's `Sec-WebSocket-Protocol` field - /// lists. - open func webSocketTask(with request: URLRequest) -> URLSessionWebSocketTask { - let offered = request.value(forHTTPHeaderField: "Sec-WebSocket-Protocol")? - .split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } ?? [] - return makeWebSocketTask(request, protocols: offered) - } - - // MARK: Making tasks - - private func makeDataTask( - _ request: URLRequest, upload: _UploadBody?, - completionHandler: (@Sendable (Data?, URLResponse?, (any Error)?) -> Void)? - ) -> URLSessionDataTask { - let request = withSessionDefaults(request) - return _register { identifier in - URLSessionDataTask( - session: self, identifier: identifier, request: request, upload: upload, - completionHandler: completionHandler) - } - } - - private func makeUploadTask( - _ request: URLRequest, upload: _UploadBody?, - completionHandler: (@Sendable (Data?, URLResponse?, (any Error)?) -> Void)? - ) -> URLSessionUploadTask { - let request = withSessionDefaults(request) - return _register { identifier in - URLSessionUploadTask( - session: self, identifier: identifier, request: request, upload: upload, - completionHandler: completionHandler) - } - } - - func makeDownloadTask( - _ request: URLRequest, keepsFile: Bool, - completionHandler: (@Sendable (URL?, URLResponse?, (any Error)?) -> Void)? - ) -> URLSessionDownloadTask { - let request = withSessionDefaults(request) - return _register { identifier in - URLSessionDownloadTask( - session: self, identifier: identifier, request: request, keepsFile: keepsFile, - completionHandler: completionHandler) - } - } - - private func makeWebSocketTask(_ request: URLRequest, protocols: [String]) -> URLSessionWebSocketTask { - let request = withSessionDefaults(request) - return _register { identifier in - URLSessionWebSocketTask(session: self, identifier: identifier, request: request, protocols: protocols) - } - } - - /// The request as the session sends it: its timeout the configuration's - /// when it kept the default, and a request made from a URL alone with - /// the configuration's cache policy. - private func withSessionDefaults(_ request: URLRequest) -> URLRequest { - var request = request - if request.timeoutInterval == 60 { - request.timeoutInterval = sessionConfiguration.timeoutIntervalForRequest - } - if request.cachePolicy == .useProtocolCachePolicy { - request.cachePolicy = sessionConfiguration.requestCachePolicy - } - return request - } - - // MARK: Loading - - /// Loads `request` (with `upload` as its body when there is one): - /// what the task's response is, its body read whole. Throws a URLError. - func _load(_ request: URLRequest, upload: _UploadBody?, task: URLSessionTask) async throws -> (Data, URLResponse) { - guard let url = request.url else { throw URLError(.unsupportedURL, url: nil) } - switch url.scheme?.lowercased() { - case "file": - return try Self.loadFile(url) - case "data": - return try Self.decodeDataURL(url) - case "http", "https": - return try await loadHTTP(request, url: url, upload: upload, task: task) - default: - throw URLError(.unsupportedURL, url: url) - } - } - - private func loadHTTP( - _ request: URLRequest, url: URL, upload: _UploadBody?, task: URLSessionTask - ) async throws -> (Data, URLResponse) { - let body = try Self.body(of: request, upload: upload, url: url) - var fields = request._headerFields - for field in sessionConfiguration._additionalHeaderFields - where request.value(forHTTPHeaderField: field.name) == nil { - fields.append(field) - } - // As Apple's Foundation does: a body sent without a type is a form's. - if !body.isEmpty && request.value(forHTTPHeaderField: "Content-Type") == nil - && !fields.contains(where: { $0.name.caseInsensitiveCompare("Content-Type") == .orderedSame }) - { - fields.append((name: "Content-Type", value: "application/x-www-form-urlencoded")) - } - task._sending(body.count) - guard let transport = IsomerNetwork.http else { - throw URLError( - .notConnectedToInternet, url: url, - debugDescription: "No HTTP transport is installed (IsomerFoundation's IsomerNetwork.http).") - } - let exchange = HTTPTransportRequest( - method: request.httpMethod ?? "GET", url: url, headerFields: fields, body: body, - timeoutInterval: request.timeoutInterval) - let answer: HTTPTransportResponse - do { - answer = try await transport.send(exchange) - } catch { - throw Self.urlError(error, url: url) - } - // Repeated fields are one, their values joined, as Apple's are. - var headerFields: [String: String] = [:] - var names: [String: String] = [:] - for field in answer.headerFields { - let key = field.name.lowercased() - if let name = names[key] { - headerFields[name] = headerFields[name]! + ", " + field.value - } else { - names[key] = field.name - headerFields[field.name] = field.value - } - } - guard - let response = HTTPURLResponse( - url: answer.url ?? url, statusCode: answer.statusCode, httpVersion: "HTTP/1.1", - headerFields: headerFields) - else { - throw URLError(.badServerResponse, url: url, debugDescription: "Status \(answer.statusCode)") - } - task._received(answer.body.count) - return (answer.body, response) - } - - /// The body a request sends: the upload's, else the request's own. - private static func body(of request: URLRequest, upload: _UploadBody?, url: URL) throws -> Data { - switch upload { - case .data(let data): - return data - case .file(let file): - do { - return try Data(contentsOf: file) - } catch { - throw URLError(.cannotOpenFile, url: url, underlying: error) - } - case nil: - if let data = request.httpBody { return data } - guard let stream = request.httpBodyStream else { return Data() } - stream.open() - defer { stream.close() } - var data = Data() - var buffer = [UInt8](repeating: 0, count: 16_384) - while true { - let count = buffer.withUnsafeMutableBufferPointer { stream.read($0.baseAddress!, maxLength: $0.count) } - if count < 0 { throw URLError(.requestBodyStreamExhausted, url: url) } - if count == 0 { return data } - data.append(contentsOf: buffer[0.. URLError { - if let error = error as? URLError { return error } - if error is CancellationError { return URLError(.cancelled, url: url) } - guard let failure = error as? NetworkTransportError else { - return URLError(.unknown, url: url, debugDescription: "\(error)", underlying: error) - } - let code: URLError.Code = - switch failure.reason { - case .timedOut: .timedOut - case .cannotFindHost: .cannotFindHost - case .cannotConnectToHost: .cannotConnectToHost - case .networkConnectionLost: .networkConnectionLost - case .notConnectedToInternet: .notConnectedToInternet - case .secureConnectionFailed: .secureConnectionFailed - case .cancelled: .cancelled - case .badServerResponse: .badServerResponse - case .unknown: .unknown - } - return URLError(code, url: url, debugDescription: failure.message) - } - - /// A file: URL's contents, its type told by its extension. - private static func loadFile(_ url: URL) throws -> (Data, URLResponse) { - guard let type = FileManager.default.itemType(atPath: url.path) else { - throw URLError(.fileDoesNotExist, url: url) - } - if type == .typeDirectory { throw URLError(.fileIsDirectory, url: url) } - let data: Data - do { - data = try Data(contentsOf: url) - } catch { - throw URLError(.noPermissionsToReadFile, url: url, underlying: error) - } - let response = URLResponse( - url: url, mimeType: mimeType(forPathExtension: url.pathExtension), expectedContentLength: data.count, - textEncodingName: nil) - return (data, response) - } - - private static func mimeType(forPathExtension pathExtension: String) -> String { - switch pathExtension.lowercased() { - case "html", "htm": "text/html" - case "txt", "text": "text/plain" - case "css": "text/css" - case "csv": "text/csv" - case "js", "mjs": "text/javascript" - case "json": "application/json" - case "xml": "application/xml" - case "pdf": "application/pdf" - case "wasm": "application/wasm" - case "png": "image/png" - case "jpg", "jpeg": "image/jpeg" - case "gif": "image/gif" - case "webp": "image/webp" - case "svg": "image/svg+xml" - case "mp3": "audio/mpeg" - case "mp4", "m4v": "video/mp4" - case "m4a": "audio/mp4" - default: "application/octet-stream" - } - } - - /// A data: URL's bytes (RFC 2397): `data:[][;charset=…][;base64],`. - private static func decodeDataURL(_ url: URL) throws -> (Data, URLResponse) { - let text = url.absoluteString - guard let comma = text.firstIndex(of: ","), text.lowercased().hasPrefix("data:") else { - throw URLError(.badURL, url: url) - } - let header = text[text.index(text.startIndex, offsetBy: 5)..] = [] - var closed = false - var closeCode: CloseCode = .invalid - var closeReason: Data? - var maximumMessageSize = 1_048_576 - } - - private let protocols: [String] - private let socket = Mutex(Socket()) - private let sends = _SerialWork() - private let receives = _SerialWork() - - init(session: URLSession, identifier: Int, request: URLRequest, protocols: [String]) { - self.protocols = protocols - super.init(session: session, identifier: identifier, request: request) - } - - /// The largest message a receive takes, in bytes (1 MiB unless set): a - /// larger one fails the receive (POSIX EMSGSIZE) and closes the - /// connection with `.messageTooBig`. - open var maximumMessageSize: Int { - get { socket.withLock { $0.maximumMessageSize } } - set { socket.withLock { $0.maximumMessageSize = newValue } } - } - - /// How the connection closed; `.invalid` until it has. - open var closeCode: CloseCode { socket.withLock { $0.closeCode } } - - /// The reason the closing handshake gave; nil until the connection - /// closed, and when it gave none. - open var closeReason: Data? { socket.withLock { $0.closeReason } } - - // MARK: Sending and receiving - - @preconcurrency - open func send( - _ message: URLSessionWebSocketTask.Message, completionHandler: @escaping @Sendable ((any Error)?) -> Void - ) { - sends.add { - do { - try await self.deliver(message) - completionHandler(nil) - } catch { - completionHandler(error) - } - } - } - - public func send(_ message: URLSessionWebSocketTask.Message) async throws { - let done = _Rendezvous() - send(message) { error in done.resolve(error.map { .failure($0) } ?? .success(())) } - try await done.value() - } - - @preconcurrency - open func receive( - completionHandler: @escaping @Sendable (Result) -> Void - ) { - receives.add { - do { - completionHandler(.success(try await self.take())) - } catch { - completionHandler(.failure(error)) - } - } - } - - public func receive() async throws -> URLSessionWebSocketTask.Message { - let next = _Rendezvous() - receive { next.resolve($0) } - return try await next.value() - } - - /// Answers once the connection is open, or with why it could not open. - open func sendPing(pongReceiveHandler: @escaping @Sendable ((any Error)?) -> Void) { - Task { - do { - _ = try await self.connection() - pongReceiveHandler(nil) - } catch { - pongReceiveHandler(error) - } - } - } - - /// Closes the connection with `closeCode` and `reason`, which become - /// the task's. - open func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { - let (open, waiting) = socket.withLock { socket in - if !socket.closed { - socket.closed = true - socket.closeCode = closeCode - socket.closeReason = reason - } - defer { socket.waiting = [] } - return (socket.connection, socket.waiting) - } - open?.close(code: closeCode.rawValue, reason: reason ?? Data()) - // What waited for a connection that will not open now. - for waiter in waiting { waiter.resume(throwing: Self.notConnected) } - super.cancel() - } - - /// Closes the connection going away (1001), as Apple's does. - open override func cancel() { - cancel(with: .goingAway, reason: nil) - } - - // MARK: The connection - - /// Opens the connection; the task runs until it closes. - override func _run() async { - guard let transport = IsomerNetwork.webSocket else { - fail( - URLError( - .notConnectedToInternet, url: originalRequest?.url, - debugDescription: - "No WebSocket transport is installed (IsomerFoundation's IsomerNetwork.webSocket).")) - return - } - guard let request = originalRequest, let url = Self.webSocketURL(request.url) else { - fail(URLError(.unsupportedURL, url: originalRequest?.url)) - return - } - var fields = request._headerFields.filter { - $0.name.caseInsensitiveCompare("Sec-WebSocket-Protocol") != .orderedSame - } - for field in session.sessionConfiguration._additionalHeaderFields - where request.value(forHTTPHeaderField: field.name) == nil { - fields.append(field) - } - let connection: any WebSocketTransportConnection - do { - connection = try await transport.connect( - WebSocketTransportRequest( - url: url, protocols: protocols, headerFields: fields, timeoutInterval: request.timeoutInterval)) - } catch { - fail(URLSession.urlError(error, url: request.url)) - return - } - // The handshake's answer, as Apple's task gives it. - var answer = ["Upgrade": "websocket", "Connection": "Upgrade"] - if let subprotocol = connection.subprotocol { answer["Sec-WebSocket-Protocol"] = subprotocol } - let response = HTTPURLResponse(url: url, statusCode: 101, httpVersion: "HTTP/1.1", headerFields: answer) - let waiting = socket.withLock { socket -> [CheckedContinuation]? in - guard socket.failure == nil && !socket.closed else { return nil } - socket.connection = connection - defer { socket.waiting = [] } - return socket.waiting - } - guard let waiting else { - // Cancelled while it opened: closed as asked. - let (code, reason) = socket.withLock { ($0.closeCode, $0.closeReason) } - let sent = code == .invalid ? CloseCode.goingAway : code - connection.close(code: sent.rawValue, reason: reason ?? Data()) - return - } - status.withLock { $0.response = response } - for waiter in waiting { waiter.resume(returning: connection) } - } - - /// The open connection, once it is; throws what kept it from opening or - /// closed it. - private func connection() async throws -> any WebSocketTransportConnection { - try await withCheckedThrowingContinuation { continuation in - let ready = socket.withLock { socket -> Result? in - if let failure = socket.failure { return .failure(failure) } - if socket.closed { return .failure(Self.notConnected) } - if let connection = socket.connection { return .success(connection) } - socket.waiting.append(continuation) - return nil - } - if let ready { continuation.resume(with: ready) } - } - } - - private func deliver(_ message: Message) async throws { - let connection = try await connection() - do { - switch message { - case .string(let text): try await connection.send(text: text) - case .data(let data): try await connection.send(data: data) - } - } catch { - throw URLSession.urlError(error, url: originalRequest?.url) - } - } - - private func take() async throws -> Message { - let connection = try await connection() - let event: WebSocketTransportEvent - do { - event = try await connection.receive() - } catch { - let failure = URLSession.urlError(error, url: originalRequest?.url) - closed(code: CloseCode.abnormalClosure.rawValue, reason: nil, failure: failure) - throw failure - } - let limit = maximumMessageSize - switch event { - case .text(let text): - guard text.utf8.count <= limit else { throw tooBig(connection) } - return .string(text) - case .data(let data): - guard data.count <= limit else { throw tooBig(connection) } - return .data(data) - case .closed(let code, let reason): - closed(code: code, reason: reason.isEmpty ? nil : reason, failure: nil) - throw Self.notConnected - } - } - - private func tooBig(_ connection: any WebSocketTransportConnection) -> any Error { - connection.close(code: CloseCode.messageTooBig.rawValue, reason: Data()) - closed(code: CloseCode.messageTooBig.rawValue, reason: nil, failure: nil) - return POSIXError(.EMSGSIZE) - } - - /// The connection closed: the task completes, its close code and reason - /// what the handshake said (unless the app closed it first). - private func closed(code: Int, reason: Data?, failure: (any Error)?) { - socket.withLock { socket in - if !socket.closed { - socket.closed = true - socket.closeCode = CloseCode(rawValue: code) ?? .invalid - socket.closeReason = reason - } - } - _finish(failure.map { .failed($0, response) } ?? .ended) - } - - /// The connection could not be opened: whatever waits on it fails. - private func fail(_ error: any Error) { - let waiting = socket.withLock { socket in - socket.failure = error - defer { socket.waiting = [] } - return socket.waiting - } - for waiter in waiting { waiter.resume(throwing: error) } - _finish(.failed(error, nil)) - } - - /// Apple's error for a socket used after it closed. - private static var notConnected: any Error { POSIXError(.ENOTCONN) } - - /// ws and wss as they are; http and https as the WebSocket schemes they - /// stand for (Apple's task takes those too). - private static func webSocketURL(_ url: URL?) -> URL? { - guard let url, var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } - switch components.scheme?.lowercased() { - case "ws", "wss": return url - case "http": components.scheme = "ws" - case "https": components.scheme = "wss" - default: return nil - } - return components.url - } -} - -/// Work run one item at a time in the order it was added; adding never -/// waits. -final class _SerialWork: Sendable { - private let state = Mutex<(pending: [@Sendable () async -> Void], running: Bool)>(([], false)) - - func add(_ work: @escaping @Sendable () async -> Void) { - let start = state.withLock { state -> Bool in - state.pending.append(work) - defer { state.running = true } - return !state.running - } - if start { Task { await self.drain() } } - } - - private func drain() async { - while true { - let next = state.withLock { state -> (@Sendable () async -> Void)? in - guard !state.pending.isEmpty else { - state.running = false - return nil - } - return state.pending.removeFirst() - } - guard let next else { return } - await next() - } - } -} diff --git a/foundation/UserDefaults.swift b/foundation/UserDefaults.swift deleted file mode 100644 index c283fbbb..00000000 --- a/foundation/UserDefaults.swift +++ /dev/null @@ -1,321 +0,0 @@ -// UserDefaults: a key-value store of property-list values (strings, -// numbers, booleans, data, dates, URLs, and arrays and dictionaries of -// them), as Apple's Foundation has it. Each suite is one dictionary, kept in -// memory and written whole on each change: to a file in the app's -// Library/Preferences, as Apple's (the app's home persists on every -// platform: IndexedDB under the web's, the app's files on Android), or to a -// store a host installs in IsomerFoundation's `IsomerUserDefaults` instead. -// Where neither can be written, values last as long as the program. -// `@AppStorage` reads and writes the standard suite. - -import FoundationEssentials -internal import IsomerFoundation - -open class UserDefaults: @unchecked Sendable { - private let suite: String - private var values: [String: Any]? - private var registered: [String: Any] = [:] - private let lock = NSLock() - - nonisolated(unsafe) private static var shared: UserDefaults? - - open class var standard: UserDefaults { - if let shared { return shared } - let defaults = UserDefaults(suite: "standard") - shared = defaults - return defaults - } - - public convenience init() { - self.init(suite: "standard") - } - - public init?(suiteName suitename: String?) { - suite = suitename ?? "standard" - } - - private init(suite: String) { - self.suite = suite - } - - open class func resetStandardUserDefaults() {} - - // MARK: Reading - - open func object(forKey defaultName: String) -> Any? { - if let argument = Self.arguments[defaultName] { return argument } - lock.lock() - defer { lock.unlock() } - return loaded()[defaultName] ?? registered[defaultName] - } - - /// The argument domain, as Apple's: each `-key value` among the - /// program's arguments, ahead of anything stored, never written. A host - /// that starts no program with arguments (an Android app) passes them - /// in ISO_ARGUMENTS, split at spaces (`am start -e ISO_ARGUMENTS - /// "-reviews.fixture YES"`: the generated activity sets each ISO_ extra). - private static let arguments: [String: Any] = { - var words = Array(ProcessInfo.processInfo.arguments.dropFirst()) - if let more = ProcessInfo.processInfo.environment["ISO_ARGUMENTS"] { - words += more.split(separator: " ").map(String.init) - } - var found: [String: Any] = [:] - var index = 0 - while index + 1 < words.count { - let word = words[index] - if word.count > 1, word.hasPrefix("-"), !word.hasPrefix("--") { - found[String(word.dropFirst())] = words[index + 1] - index += 2 - } else { - index += 1 - } - } - return found - }() - - open func string(forKey defaultName: String) -> String? { - switch object(forKey: defaultName) { - case let value as String: return value - case let value as Int: return String(value) - case let value as Double: return String(value) - case let value as Bool: return value ? "1" : "0" - default: return nil - } - } - - open func array(forKey defaultName: String) -> [Any]? { object(forKey: defaultName) as? [Any] } - open func dictionary(forKey defaultName: String) -> [String: Any]? { object(forKey: defaultName) as? [String: Any] } - open func data(forKey defaultName: String) -> Data? { object(forKey: defaultName) as? Data } - open func stringArray(forKey defaultName: String) -> [String]? { - (object(forKey: defaultName) as? [Any])?.compactMap { $0 as? String } - } - - open func integer(forKey defaultName: String) -> Int { - switch object(forKey: defaultName) { - case let value as Int: return value - case let value as Double: return Int(value) - case let value as Bool: return value ? 1 : 0 - case let value as String: return Int(value) ?? Double(value).map { Int($0) } ?? 0 - default: return 0 - } - } - - open func float(forKey defaultName: String) -> Float { Float(double(forKey: defaultName)) } - - open func double(forKey defaultName: String) -> Double { - switch object(forKey: defaultName) { - case let value as Double: return value - case let value as Int: return Double(value) - case let value as Bool: return value ? 1 : 0 - case let value as String: return Double(value) ?? 0 - default: return 0 - } - } - - open func bool(forKey defaultName: String) -> Bool { - switch object(forKey: defaultName) { - case let value as Bool: return value - case let value as Int: return value != 0 - case let value as Double: return value != 0 - case let value as String: return ["1", "true", "yes", "YES", "TRUE"].contains(value) - default: return false - } - } - - open func url(forKey defaultName: String) -> URL? { - switch object(forKey: defaultName) { - case let value as URL: return value - case let value as String: return URL(string: value) - default: return nil - } - } - - open func dictionaryRepresentation() -> [String: Any] { - lock.lock() - defer { lock.unlock() } - return registered.merging(loaded()) { $1 }.merging(Self.arguments) { $1 } - } - - // MARK: Writing - - open func set(_ value: Any?, forKey defaultName: String) { - lock.lock() - var current = loaded() - if let value, let plist = Self.propertyList(value) { - current[defaultName] = plist - } else { - current[defaultName] = nil - } - values = current - lock.unlock() - save(current) - } - - open func set(_ value: Int, forKey defaultName: String) { set(value as Any?, forKey: defaultName) } - open func set(_ value: Float, forKey defaultName: String) { set(Double(value) as Any?, forKey: defaultName) } - open func set(_ value: Double, forKey defaultName: String) { set(value as Any?, forKey: defaultName) } - open func set(_ value: Bool, forKey defaultName: String) { set(value as Any?, forKey: defaultName) } - open func set(_ url: URL?, forKey defaultName: String) { set(url as Any?, forKey: defaultName) } - - open func removeObject(forKey defaultName: String) { set(nil as Any?, forKey: defaultName) } - - open func register(defaults registrationDictionary: [String: Any]) { - lock.lock() - defer { lock.unlock() } - for (key, value) in registrationDictionary { - if let plist = Self.propertyList(value) { registered[key] = plist } - } - } - - /// Writes are immediate; there is nothing left to write. - @discardableResult - open func synchronize() -> Bool { true } - - // MARK: Storage - - private var storeKey: String { "UserDefaults." + suite } - - /// The suite's file: `Library/Preferences/.defaults` in the app's - /// home, the standard suite under the app's bundle identifier (Apple's - /// are property lists; these are this file's text form). - private var fileURL: URL { - let name = suite == "standard" ? (Bundle.main.bundleIdentifier ?? "standard") : suite - return URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true) - .appendingPathComponent("Library/Preferences", isDirectory: true) - .appendingPathComponent(name + ".defaults", isDirectory: false) - } - - /// The suite's values, read the first time (the lock is held). - private func loaded() -> [String: Any] { - if let values { return values } - var read: [String: Any] = [:] - let text = IsomerUserDefaults.store.map { $0.read(storeKey) } - ?? (try? Data(contentsOf: fileURL)).map { String(decoding: $0, as: UTF8.self) } - if let text { - var reader = _PlistReader(text) - read = (reader.value() as? [String: Any]) ?? [:] - } - values = read - return read - } - - private func save(_ current: [String: Any]) { - var text = "" - _PlistWriter.write(current, into: &text) - if let store = IsomerUserDefaults.store { - store.write(storeKey, text) - } else { - let file = fileURL - try? FileManager.default.createDirectory( - at: file.deletingLastPathComponent(), withIntermediateDirectories: true) - // Not `.atomic`: WASI has no temporary files to write through. - try? Data(text.utf8).write(to: file) - } - } - - /// A value as a property list (its arrays' and dictionaries' contents - /// too); nil when it is not one. - private static func propertyList(_ value: Any) -> Any? { - switch value { - case is String, is Int, is Double, is Bool, is Data, is Date, is URL: return value - case let value as Float: return Double(value) - case let value as Int64: return Int(value) - case let value as Int32: return Int(value) - case let value as Substring: return String(value) - case let value as [Any]: - let items = value.compactMap(propertyList) - return items.count == value.count ? items : nil - case let value as [String: Any]: - var out: [String: Any] = [:] - for (key, item) in value { - guard let plist = propertyList(item) else { return nil } - out[key] = plist - } - return out - default: return nil - } - } -} - -/// The store's text form of a property list: a tag, then the value -/// (`s:`, `i;`, `f;`, `b0;`/`b1;`, -/// `d;`, `t;`, `u:`, -/// `a;` and its items, `m;` and its key-value pairs). -enum _PlistWriter { - static func write(_ value: Any, into out: inout String) { - switch value { - case let value as String: out += "s\(value.utf8.count):" + value - case let value as Bool: out += value ? "b1;" : "b0;" - case let value as Int: out += "i\(value);" - case let value as Double: out += "f\(value);" - case let value as Data: out += "d" + value.base64EncodedString() + ";" - case let value as Date: out += "t\(value.timeIntervalSinceReferenceDate);" - case let value as URL: - let text = value.absoluteString - out += "u\(text.utf8.count):" + text - case let value as [Any]: - out += "a\(value.count);" - for item in value { write(item, into: &out) } - case let value as [String: Any]: - out += "m\(value.count);" - for (key, item) in value.sorted(by: { $0.key < $1.key }) { - write(key, into: &out) - write(item, into: &out) - } - default: out += "s0:" - } - } -} - -struct _PlistReader { - private let bytes: [UInt8] - private var at = 0 - - init(_ text: String) { bytes = Array(text.utf8) } - - private mutating func until(_ end: UInt8) -> String? { - guard let stop = bytes[at...].firstIndex(of: end) else { return nil } - let text = String(decoding: bytes[at.. String? { - guard let length = until(UInt8(ascii: ":")).flatMap({ Int($0) }), at + length <= bytes.count else { return nil } - let text = String(decoding: bytes[at.. Any? { - guard at < bytes.count else { return nil } - let tag = bytes[at] - at += 1 - switch tag { - case UInt8(ascii: "s"): return counted() - case UInt8(ascii: "u"): return counted().flatMap { URL(string: $0) } - case UInt8(ascii: "b"): return until(UInt8(ascii: ";")).map { $0 == "1" } - case UInt8(ascii: "i"): return until(UInt8(ascii: ";")).flatMap { Int($0) } - case UInt8(ascii: "f"): return until(UInt8(ascii: ";")).flatMap { Double($0) } - case UInt8(ascii: "d"): return until(UInt8(ascii: ";")).flatMap { Data(base64Encoded: $0) } - case UInt8(ascii: "t"): return until(UInt8(ascii: ";")).flatMap { Double($0) }.map { Date(timeIntervalSinceReferenceDate: $0) } - case UInt8(ascii: "a"): - guard let count = until(UInt8(ascii: ";")).flatMap({ Int($0) }) else { return nil } - var items: [Any] = [] - for _ in 0..-i18n.artifactbundle.tar.gz; isomer's README, \"Upgrading isomer\").") +#endif diff --git a/foundation/isomer_foundation/BUILD.bazel b/foundation/isomer_foundation/BUILD.bazel deleted file mode 100644 index f0eaa823..00000000 --- a/foundation/isomer_foundation/BUILD.bazel +++ /dev/null @@ -1,43 +0,0 @@ -# IsomerFoundation: what a platform's host gives Isomer's Foundation, the -# API Apple's Foundation has no place for (docs/isomer_031_plan.md, phase -# 10). The transports `URLSession` sends its requests through -# (IsomerNetwork) and the store `UserDefaults` keeps its suites in -# (IsomerUserDefaults). Foundation reads them through an `internal import`, -# so nothing of this module reaches an app through `import Foundation`; a -# host imports it by name. - -load("@rules_swift//swift:swift.bzl", "swift_library") -load("//foundation:defs.bzl", "one_configuration") - -package( - default_visibility = ["//visibility:public"], - features = [ - # Swift 6, strict and warning-free: hosts on many threads (Android) - # and on one (the web) install these from wherever they start. - "swift.enable_v6", - "treat_warnings_as_errors", - "swift.treat_warnings_as_errors", - "swift.upcoming.ExistentialAny", - ], -) - -one_configuration( - name = "isomer_foundation", - target_compatible_with = select({ - "@platforms//os:macos": ["@platforms//:incompatible"], - "@platforms//os:ios": ["@platforms//:incompatible"], - "@platforms//os:tvos": ["@platforms//:incompatible"], - "@platforms//os:watchos": ["@platforms//:incompatible"], - "@platforms//os:visionos": ["@platforms//:incompatible"], - "//conditions:default": [], - }), - actual = "@swiftpkg_isomer//:IsomerFoundation", -) - -# What a host outside //foundation depends on (through -# @isomer//:isomer_foundation): built in the one configuration Foundation's -# copy is (//foundation:defs.bzl), so the two are one library. -one_configuration( - name = "for_dependents", - actual = ":isomer_foundation", -) diff --git a/foundation/isomer_foundation/IsomerNetwork.swift b/foundation/isomer_foundation/IsomerNetwork.swift deleted file mode 100644 index 4b4dabea..00000000 --- a/foundation/isomer_foundation/IsomerNetwork.swift +++ /dev/null @@ -1,273 +0,0 @@ -// The network beneath Isomer's Foundation. `URLSession` there is Apple's -// API over transports a host installs in `IsomerNetwork`: HTTP exchanges -// through `http`, WebSocket connections through `webSocket`. Each platform -// fills them in from its own networking (the browser's `fetch` and -// `WebSocket`, Android's HTTP stack and a WebSocket client in its runtime, -// Apple's URLSession in a WasmKit host). Without one, a task fails as it would -// on a device offline (`URLError.notConnectedToInternet`). Apps call -// URLSession; only hosts use what is here. -// -// The types are plain values (String, Data, Int, [String], header fields -// as name-value pairs in order) so that a host written in another language -// can be reached through swift_ffi by a small adapter: swift_ffi's -// interfaces take no `async`, so the adapter keeps a continuation per -// exchange and resumes it from the export the host calls back. - -import FoundationEssentials -import Synchronization - -/// The transports Isomer's Foundation sends `URLSession`'s work through. -/// -/// A host installs them before the app makes its first request; a task -/// reads them when it starts. -public enum IsomerNetwork { - /// Performs `URLSession`'s HTTP and HTTPS requests: data, upload and - /// download tasks and their async forms. - public static var http: (any HTTPTransport)? { - get { installed.withLock { $0.http } } - set { installed.withLock { $0.http = newValue } } - } - - /// Opens `URLSession`'s WebSocket connections - /// (`URLSessionWebSocketTask`). - public static var webSocket: (any WebSocketTransport)? { - get { installed.withLock { $0.webSocket } } - set { installed.withLock { $0.webSocket = newValue } } - } -} - -private let installed = Mutex<(http: (any HTTPTransport)?, webSocket: (any WebSocketTransport)?)>((nil, nil)) - -// MARK: - HTTP - -/// Performs one HTTP exchange: a request sent, its whole response read. -public protocol HTTPTransport: Sendable { - /// Sends `request` and returns the server's response with its body read - /// to the end. - /// - /// A status the server answered with, 404 or 500 as much as 200, is a - /// response. Redirects are followed, as `URLSession` follows them, and - /// the response says where it came from. The body is what the app - /// should see: content codings the platform's stack undoes (gzip, - /// Brotli) are undone. - /// - /// Throws a `NetworkTransportError` when there is no response; its - /// reason becomes the `URLError` code the app sees (any other error is - /// `URLError.unknown`). The calling task is cancelled when the app - /// cancels the `URLSessionTask`: a transport that can stop the exchange - /// (an `AbortController`, OkHttp's `Call.cancel()`) stops it then. - /// Whatever it returns after that is not used. - func send(_ request: HTTPTransportRequest) async throws -> HTTPTransportResponse -} - -/// What an HTTP exchange sends. -public struct HTTPTransportRequest: Sendable { - /// The request's method: "GET", "POST", "PUT"… - public var method: String - - /// An http or https URL. - public var url: URL - - /// The request's header fields in the order they were set, the names as - /// the app wrote them; the session's additional headers come after the - /// request's own. A platform's stack may drop the fields it keeps for - /// itself (a browser's `fetch` sets `Host`, `Content-Length`, - /// `Cookie`…). - public var headerFields: [(name: String, value: String)] - - /// The body; empty for none. - public var body: Data - - /// How many seconds the exchange may wait on the server, to connect or - /// for more of its response, before it fails with - /// `NetworkTransportError.Reason.timedOut`. A stack that has only a - /// timeout for the whole exchange uses it for that. - public var timeoutInterval: TimeInterval - - public init( - method: String, - url: URL, - headerFields: [(name: String, value: String)], - body: Data, - timeoutInterval: TimeInterval - ) { - self.method = method - self.url = url - self.headerFields = headerFields - self.body = body - self.timeoutInterval = timeoutInterval - } -} - -/// What an HTTP exchange received. -public struct HTTPTransportResponse: Sendable { - /// The status code: 200, 404… - public var statusCode: Int - - /// The response's header fields in the order they came. A field that - /// came more than once is listed each time (Foundation joins their - /// values with commas, as Apple's does). - public var headerFields: [(name: String, value: String)] - - /// The whole body, its content codings undone; empty for none. - public var body: Data - - /// The URL the response came from when redirects led away from the - /// request's; nil when it is the request's own. - public var url: URL? - - public init( - statusCode: Int, - headerFields: [(name: String, value: String)], - body: Data, - url: URL? = nil - ) { - self.statusCode = statusCode - self.headerFields = headerFields - self.body = body - self.url = url - } -} - -// MARK: - WebSocket - -/// Opens WebSocket connections. -public protocol WebSocketTransport: Sendable { - /// Opens a connection and returns it once the opening handshake is - /// done. - /// - /// Throws a `NetworkTransportError` when the connection cannot be - /// opened. The calling task is cancelled when the app cancels the - /// `URLSessionWebSocketTask` before it opened. - func connect(_ request: WebSocketTransportRequest) async throws -> any WebSocketTransportConnection -} - -/// What a WebSocket connection is opened with. -public struct WebSocketTransportRequest: Sendable { - /// A ws or wss URL. - public var url: URL - - /// The subprotocols to offer (`Sec-WebSocket-Protocol`), most preferred - /// first; empty for none. - public var protocols: [String] - - /// Header fields for the opening handshake, in the order they were set. - /// A browser's `WebSocket` cannot send any: there they are left out. - public var headerFields: [(name: String, value: String)] - - /// How many seconds the opening handshake may take before it fails with - /// `NetworkTransportError.Reason.timedOut`. - public var timeoutInterval: TimeInterval - - public init( - url: URL, - protocols: [String], - headerFields: [(name: String, value: String)], - timeoutInterval: TimeInterval - ) { - self.url = url - self.protocols = protocols - self.headerFields = headerFields - self.timeoutInterval = timeoutInterval - } -} - -/// An open WebSocket connection. -/// -/// Foundation sends one message at a time and asks for one at a time, each -/// in the order the app did: a host's connection keeps what arrives in a -/// queue until `receive()` takes it. -public protocol WebSocketTransportConnection: AnyObject, Sendable { - /// The subprotocol the server chose; nil for none. - var subprotocol: String? { get } - - /// Sends a text message. Throws a `NetworkTransportError` when the - /// connection is gone. - func send(text: String) async throws - - /// Sends a binary message. Throws a `NetworkTransportError` when the - /// connection is gone. - func send(data: Data) async throws - - /// The next message, or that the connection closed: once it has, every - /// call returns `.closed` with the same code and reason. Throws a - /// `NetworkTransportError` when the connection failed without a closing - /// handshake (or returns `.closed` with code 1006). - func receive() async throws -> WebSocketTransportEvent - - /// Starts the closing handshake with `code` (1000 to 4999) and `reason` - /// (UTF-8, at most 123 bytes; empty for none). What already arrived can - /// still be received; then `receive()` returns `.closed`. - /// - /// A browser's `WebSocket` sends only 1000 or 3000 to 4999: a host - /// there sends 1000 for the other codes. - func close(code: Int, reason: Data) -} - -/// What a WebSocket connection received. -public enum WebSocketTransportEvent: Sendable, Hashable { - /// A text message. - case text(String) - - /// A binary message. - case data(Data) - - /// The connection closed, with the code and reason of its closing - /// handshake: 1005 and no reason when the handshake carried no code, - /// 1006 when the connection ended without one. - case closed(code: Int, reason: Data) -} - -// MARK: - Errors - -/// Why a transport has no response to give, in the terms of the `URLError` -/// the app then sees. -public struct NetworkTransportError: Error, Sendable, Hashable { - /// What went wrong. The raw value is the case's name, for hosts that - /// report it as text. - public enum Reason: String, Sendable, Hashable { - /// The server did not answer in time: `URLError.timedOut`. - case timedOut - - /// The host's name has no address: `URLError.cannotFindHost`. - case cannotFindHost - - /// The connection was refused or never made: - /// `URLError.cannotConnectToHost`. - case cannotConnectToHost - - /// The connection broke during the exchange: - /// `URLError.networkConnectionLost`. - case networkConnectionLost - - /// The device has no network: `URLError.notConnectedToInternet`. - case notConnectedToInternet - - /// The TLS handshake failed or the server's certificate was - /// refused: `URLError.secureConnectionFailed`. - case secureConnectionFailed - - /// The exchange was stopped: `URLError.cancelled`. - case cancelled - - /// The server answered with something that is not HTTP (or not a - /// WebSocket handshake): `URLError.badServerResponse`. - case badServerResponse - - /// Anything else, and what a platform cannot tell apart (a - /// browser's `fetch` says only that it failed): `URLError.unknown`. - case unknown - } - - public var reason: Reason - - /// What the platform said, for a developer reading the error: Foundation - /// keeps it in the `URLError`'s user info under `NSDebugDescription`, - /// not in its description. - public var message: String - - public init(_ reason: Reason, message: String = "") { - self.reason = reason - self.message = message - } -} diff --git a/foundation/isomer_foundation/IsomerUserDefaults.swift b/foundation/isomer_foundation/IsomerUserDefaults.swift deleted file mode 100644 index e2ee878b..00000000 --- a/foundation/isomer_foundation/IsomerUserDefaults.swift +++ /dev/null @@ -1,37 +0,0 @@ -// Where Isomer's `UserDefaults` keeps its suites: a store the host installs -// (the browser's localStorage, a file in the app's files directory on -// Android). Each suite is one text value under its own key, -// "UserDefaults.", written whole on every change. Without a -// store, values last as long as the program. - -import Synchronization - -/// The store `UserDefaults` reads its suites from and writes them to. -public enum IsomerUserDefaults { - /// Installed by the host; read by `UserDefaults` the first time it - /// needs each suite and on every write. - public static var store: UserDefaultsStore? { - get { installed.withLock { $0 } } - set { installed.withLock { $0 = newValue } } - } -} - -private let installed = Mutex(nil) - -/// A store of text values by key: what `UserDefaults` needs of the -/// platform's. -public struct UserDefaultsStore: Sendable { - /// The value under `key`; nil when there is none. - public var read: @Sendable (_ key: String) -> String? - - /// Keeps `value` under `key`, replacing what was there. - public var write: @Sendable (_ key: String, _ value: String) -> Void - - public init( - read: @escaping @Sendable (_ key: String) -> String?, - write: @escaping @Sendable (_ key: String, _ value: String) -> Void - ) { - self.read = read - self.write = write - } -} diff --git a/foundation/networking/BUILD.bazel b/foundation/networking/BUILD.bazel deleted file mode 100644 index 1f909cbc..00000000 --- a/foundation/networking/BUILD.bazel +++ /dev/null @@ -1,16 +0,0 @@ - -load("//foundation:defs.bzl", "one_configuration") - -package(default_visibility = ["//visibility:public"]) - -# `import FoundationNetworking` on the platforms whose Foundation is Isomer's -# (FoundationNetworking.swift): part of //foundation:for_dependents there. -one_configuration( - name = "networking", - target_compatible_with = select({ - "@platforms//os:android": [], - "@platforms//os:wasi": [], - "//conditions:default": ["@platforms//:incompatible"], - }), - actual = "@swiftpkg_isomer//:FoundationNetworking", -) diff --git a/foundation/networking/FoundationNetworking.swift b/foundation/networking/FoundationNetworking.swift deleted file mode 100644 index 88877cf1..00000000 --- a/foundation/networking/FoundationNetworking.swift +++ /dev/null @@ -1,8 +0,0 @@ -// FoundationNetworking, where Isomer's Foundation is the Foundation (Android, -// the web): Isomer's Foundation, whose URLSession, URLRequest and -// URLResponse are this module's on corelibs. Code written for Linux imports -// it (`#if canImport(FoundationNetworking)`); the Swift SDK's own module of -// this name is corelibs', and beside Isomer's Foundation its URLSession made -// the name ambiguous. This one is found first (a dependency's module before -// the SDK's), so the import gets these types. -@_exported import Foundation diff --git a/foundation/tests/BUILD.bazel b/foundation/tests/BUILD.bazel index fc1fbb74..6b7bdc2f 100644 --- a/foundation/tests/BUILD.bazel +++ b/foundation/tests/BUILD.bazel @@ -1,3 +1,8 @@ +# Foundation's checks, against the Swift SDK's Foundation (since 0.56, +# Isomer's Swift SDKs carry Isomer's Foundation: the sources are +# isomer_hermetic_toolchains'). Built for wasm and run in headless Chrome; the +# Android ones are link checks. + load("@rules_shell//shell:sh_test.bzl", "sh_test") load("@rules_swift//swift:swift.bzl", "swift_binary") load("//tools/platforms:transition.bzl", "transition_binary") @@ -19,9 +24,10 @@ swift_binary( "StringsCheck.swift", ], deps = [ - "//foundation", - # The transports and the store, installed as a host installs them. - "//foundation/isomer_foundation", + # The Swift SDK's Foundation (Isomer's SDKs): nothing to link, but + # with //foundation:internationalization the check that the SDK is + # the -i18n one. + "//:foundation", ], tags = ["manual"], ) @@ -53,8 +59,10 @@ sh_test( ], ) -# With FoundationInternationalization and ICU (the build setting -# //foundation:internationalization, set by the transition). +# With FoundationInternationalization and ICU: the -i18n SDK's Foundation, +# which isomer's own module registers (MODULE.bazel), so these checks and the +# ones above run against it. (The transition sets +# //foundation:internationalization, which checks for that SDK.) swift_binary( name = "internationalization_check", package_name = "isomer", @@ -65,7 +73,7 @@ swift_binary( "-Xlinker", "stack-size=16777216", ], - deps = ["//foundation"], + deps = ["//:foundation"], tags = ["manual"], ) @@ -107,7 +115,7 @@ swift_binary( "-Xlinker", "--no-gc-sections", ], - deps = ["//foundation"], + deps = ["//:foundation"], tags = ["manual"], ) @@ -141,7 +149,7 @@ swift_binary( ], deps = [ ":icu_en_fr_de", - "//foundation", + "//:foundation", ], tags = ["manual"], ) diff --git a/foundation/wasi_thread_identity/identity.c b/foundation/wasi_thread_identity/identity.c deleted file mode 100644 index 6881c66d..00000000 --- a/foundation/wasi_thread_identity/identity.c +++ /dev/null @@ -1,23 +0,0 @@ -#include "identity.h" - -#if defined(_REENTRANT) -// Declared here, not through : that reaches in the -// compiler's builtin headers, which the wasm cc toolchain does not -// allow-list (before rules_swift#1989; -// declared by hand since). wasi-libc's pthread_t is a -// pointer and pthread_equal compares it. -extern void *pthread_self(void); - -// Captured by a constructor, which the reactor's initializer runs on the -// guest's main thread before any other thread exists: a lazily initialized -// Swift global could first be touched by a worker. -static void *main_thread; - -__attribute__((constructor)) static void capture_main_thread(void) { - main_thread = pthread_self(); -} - -int iso_wasi_is_main_thread(void) { return pthread_self() == main_thread; } -#else -int iso_wasi_is_main_thread(void) { return 1; } -#endif diff --git a/foundation/wasi_thread_identity/identity.h b/foundation/wasi_thread_identity/identity.h deleted file mode 100644 index f08698a2..00000000 --- a/foundation/wasi_thread_identity/identity.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef ISO_WASI_THREAD_IDENTITY_H -#define ISO_WASI_THREAD_IDENTITY_H - -/// Whether the calling thread is the guest's main thread: the one that ran -/// the reactor's constructors (`_initialize`), which is the thread the host -/// drives it from. 1 on a single-threaded build. -int iso_wasi_is_main_thread(void); - -#endif diff --git a/frameworks/BUILD.bazel b/frameworks/BUILD.bazel index 5ac1317d..d7c3c3bb 100644 --- a/frameworks/BUILD.bazel +++ b/frameworks/BUILD.bazel @@ -21,16 +21,17 @@ swift_library_group( "@platforms//os:watchos": [], "@platforms//os:visionos": [], "//conditions:default": [ - # Through Isomer's Foundation on wasm and Android; on Linux and - # Windows beside the toolchain's (core_graphics/BUILD.bazel). + # The Swift SDK's on wasm and Android (nothing to link); on Linux + # and Windows Isomer's, beside the toolchain's Foundation + # (core_graphics/BUILD.bazel). "//:core_graphics", "//frameworks/core_transferable", "//frameworks/uniform_type_identifiers", ], }) + select({ - # Combine: on wasm and Android Isomer's Foundation brings it (one - # configuration of it: a second, linked beside, duplicates every - # symbol); on Linux and Windows the toolchain's Foundation doesn't. + # Combine: on wasm and Android the Swift SDK's (Isomer's Foundation + # re-exports it); on Linux and Windows the toolchain's Foundation has + # none, so Isomer's. "@platforms//os:linux": ["//frameworks/combine"], "@platforms//os:windows": ["//frameworks/combine"], "//conditions:default": [], diff --git a/frameworks/combine/BUILD.bazel b/frameworks/combine/BUILD.bazel index ea515af4..4d358007 100644 --- a/frameworks/combine/BUILD.bazel +++ b/frameworks/combine/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_swift//swift:swift.bzl", "swift_library") +load("@rules_swift//swift:swift.bzl", "swift_library", "swift_library_group") load("//foundation:defs.bzl", "one_configuration") @@ -18,8 +18,23 @@ filegroup( # what isn't here). It sits beneath Foundation, which imports it as Apple's # does, so it depends on nothing but the standard library and the C # library's mutexes (Lock.swift); no Dispatch, which wasm lacks. -one_configuration( +# Since 0.56 these sources build Linux's and Windows' Combine alone: on +# Android and the web it is the Swift SDK's (Isomer's SDKs carry it, built +# from isomer_hermetic_toolchains' copy, Isomer/Sources/Combine; a change +# here goes there too), so this label is nothing to link there. +alias( name = "combine", + actual = select({ + "@platforms//os:android": ":none", + "@platforms//os:wasi": ":none", + "//conditions:default": ":package", + }), +) + +swift_library_group(name = "none") + +one_configuration( + name = "package", target_compatible_with = select({ "@platforms//os:macos": ["@platforms//:incompatible"], "@platforms//os:ios": ["@platforms//:incompatible"], diff --git a/shared/BUILD.bazel b/shared/BUILD.bazel index 15839838..157f1ea5 100644 --- a/shared/BUILD.bazel +++ b/shared/BUILD.bazel @@ -31,3 +31,11 @@ package(default_visibility = ["//visibility:public"]) # The map-free default: an empty library, so the flag can sit unconditionally # in each platform module's deps. cc_library(name = "no_map_engine") + +# FileDocument's FileWrapper, compiled into the SwiftUI of Linux and Windows, +# whose Foundation (the toolchain's) has none (Package.swift's SwiftUI target +# lists the directory); and into the core's host tests on Linux. +exports_files( + ["swift_ui_corelibs/FileWrapper.swift"], + visibility = ["//tests/snapshot:__pkg__"], +) diff --git a/shared/swift_ui_corelibs/FileWrapper.swift b/shared/swift_ui_corelibs/FileWrapper.swift deleted file mode 120000 index a7b7cf8f..00000000 --- a/shared/swift_ui_corelibs/FileWrapper.swift +++ /dev/null @@ -1 +0,0 @@ -../../foundation/FileWrapper.swift \ No newline at end of file diff --git a/shared/swift_ui_corelibs/FileWrapper.swift b/shared/swift_ui_corelibs/FileWrapper.swift new file mode 100644 index 00000000..92245377 --- /dev/null +++ b/shared/swift_ui_corelibs/FileWrapper.swift @@ -0,0 +1,144 @@ +// FileWrapper (Apple's Foundation has it; swift-foundation and corelibs do +// not): a file, a directory of them, or a symbolic link, held in memory, +// read from and written to the file system. What SwiftUI's FileDocument +// hands over. A Swift class, as Isomer's other Foundation classes are +// (Apple's is an NSObject). Compiled into the SwiftUI of Linux and Windows, +// whose Foundation is the toolchain's corelibs: FileManager's own API only. +// In isomer's Swift package the SwiftUI target lists this file +// (shared/swift_ui_corelibs) on every platform, so it is compiled there only +// where SwiftUI's Foundation is the toolchain's. Isomer's Foundation, in +// Isomer's Swift SDKs for Android and the web, has the same file +// (isomer_hermetic_toolchains' Isomer/Sources/Foundation): a change here +// goes there too. + +#if !ISOMER_SWIFTUI || os(Linux) || os(Windows) +import FoundationEssentials + +open class FileWrapper: @unchecked Sendable { + public struct ReadingOptions: OptionSet, Sendable { + public let rawValue: UInt + public init(rawValue: UInt) { self.rawValue = rawValue } + public static var immediate: ReadingOptions { ReadingOptions(rawValue: 1 << 0) } + public static var withoutMapping: ReadingOptions { ReadingOptions(rawValue: 1 << 1) } + } + + public struct WritingOptions: OptionSet, Sendable { + public let rawValue: UInt + public init(rawValue: UInt) { self.rawValue = rawValue } + public static var atomic: WritingOptions { WritingOptions(rawValue: 1 << 0) } + public static var withNameUpdating: WritingOptions { WritingOptions(rawValue: 1 << 1) } + } + + private enum Kind { + case file(Data) + case directory([String: FileWrapper]) + case link(URL) + } + + private var kind: Kind + open var preferredFilename: String? + open var filename: String? + open var fileAttributes: [String: Any] = [:] + + public init(regularFileWithContents contents: Data) { + kind = .file(contents) + } + + public init(directoryWithFileWrappers childrenByPreferredName: [String: FileWrapper]) { + for (name, child) in childrenByPreferredName where child.preferredFilename == nil { child.preferredFilename = name } + kind = .directory(childrenByPreferredName) + } + + public init(symbolicLinkWithDestinationURL url: URL) { + kind = .link(url) + } + + /// What is at `url` now: a file's contents, or a directory's files read + /// the same way, all at once. + public init(url: URL, options: ReadingOptions = []) throws { + let manager = FileManager.default + let path = url.path + guard let type = (try? manager.attributesOfItem(atPath: path))?[.type] as? FileAttributeType else { + throw CocoaError(.fileReadNoSuchFile) + } + if type == .typeSymbolicLink, let destination = try? manager.destinationOfSymbolicLink(atPath: path) { + kind = .link(URL(fileURLWithPath: destination)) + } else if type == .typeDirectory { + var children: [String: FileWrapper] = [:] + for name in try manager.contentsOfDirectory(atPath: path) { + children[name] = try FileWrapper(url: url.appendingPathComponent(name), options: options) + } + kind = .directory(children) + } else { + kind = .file(try Data(contentsOf: url)) + } + filename = url.lastPathComponent + preferredFilename = url.lastPathComponent + } + + open var isRegularFile: Bool { if case .file = kind { true } else { false } } + open var isDirectory: Bool { if case .directory = kind { true } else { false } } + open var isSymbolicLink: Bool { if case .link = kind { true } else { false } } + + open var regularFileContents: Data? { if case .file(let data) = kind { data } else { nil } } + open var fileWrappers: [String: FileWrapper]? { if case .directory(let children) = kind { children } else { nil } } + open var symbolicLinkDestinationURL: URL? { if case .link(let url) = kind { url } else { nil } } + + /// Adds a child to a directory, under its preferred name (made unique + /// with a number if taken): the name it is under. + @discardableResult + open func addFileWrapper(_ child: FileWrapper) -> String { + guard case .directory(var children) = kind else { return "" } + let wanted = child.preferredFilename ?? "Untitled" + var name = wanted + var number = 2 + while children[name] != nil { + name = "\(number) " + wanted + number += 1 + } + children[name] = child + kind = .directory(children) + return name + } + + @discardableResult + open func addRegularFile(withContents data: Data, preferredFilename fileName: String) -> String { + let child = FileWrapper(regularFileWithContents: data) + child.preferredFilename = fileName + return addFileWrapper(child) + } + + open func removeFileWrapper(_ child: FileWrapper) { + guard case .directory(var children) = kind, let key = keyForChildFileWrapper(child) else { return } + children[key] = nil + kind = .directory(children) + } + + open func keyForChildFileWrapper(_ child: FileWrapper) -> String? { + fileWrappers?.first { $0.value === child }?.key + } + + /// Writes it at `url`: a file's contents, a directory and its files, or + /// a link. + open func write(to url: URL, options: WritingOptions = [], originalContentsURL: URL?) throws { + let manager = FileManager.default + switch kind { + case .file(let data): + #if os(WASI) + // WASI has no temporary files to write atomically through. + try data.write(to: url) + #else + try data.write(to: url, options: options.contains(.atomic) ? .atomic : []) + #endif + case .directory(let children): + try manager.createDirectory(at: url, withIntermediateDirectories: true) + for (name, child) in children { + try child.write(to: url.appendingPathComponent(name), options: options, originalContentsURL: nil) + } + case .link(let destination): + try manager.createSymbolicLink(atPath: url.path, withDestinationPath: destination.path) + } + if options.contains(.withNameUpdating) { filename = url.lastPathComponent } + } +} +#endif diff --git a/tests/snapshot/BUILD.bazel b/tests/snapshot/BUILD.bazel index c21018bc..2bb031ff 100644 --- a/tests/snapshot/BUILD.bazel +++ b/tests/snapshot/BUILD.bazel @@ -14,7 +14,7 @@ swift_library( "//shared/no_process_host:srcs", ] + select({ # FileDocument's FileWrapper, which the toolchain's Foundation lacks. - "@platforms//os:linux": ["//foundation:FileWrapper.swift"], + "@platforms//os:linux": ["//shared:swift_ui_corelibs/FileWrapper.swift"], "//conditions:default": [], }), # The shared core spells its own types `SwiftUI.X` where a generic diff --git a/third_party/swift_packages/Package.resolved b/third_party/swift_packages/Package.resolved index e47fbee1..769b7e1b 100644 --- a/third_party/swift_packages/Package.resolved +++ b/third_party/swift_packages/Package.resolved @@ -81,23 +81,6 @@ "version" : "5.1.1" } }, - { - "identity" : "swift-foundation", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swiftlang/swift-foundation.git", - "state" : { - "revision" : "e4049b2d77e2d5d70c4cfcc99fd5eca32e1bcb06" - } - }, - { - "identity" : "swift-foundation-icu", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-foundation-icu", - "state" : { - "branch" : "release/6.4.x", - "revision" : "f986d0728da0766cf81f371521b909d4a11681d2" - } - }, { "identity" : "swift-http-structured-headers", "kind" : "remoteSourceControl", diff --git a/third_party/swift_packages/Package.swift b/third_party/swift_packages/Package.swift index caf2f885..1fa46e4e 100644 --- a/third_party/swift_packages/Package.swift +++ b/third_party/swift_packages/Package.swift @@ -1,9 +1,9 @@ // swift-tools-version: 5.9 // isomer's own SwiftPM graph, which rules_swift_package_manager consumes: -// isomer's package itself (the root Package.swift: Foundation, CoreGraphics, -// Combine and the rest of Isomer's Swift), and through it swift-foundation, -// with the patches MODULE.bazel lists. An application's graph lists isomer -// by revision instead, and the same repositories come from it. +// isomer's package itself (the root Package.swift: SwiftUI, the frameworks +// and the rest of Isomer's Swift) and what it depends on. An application's +// graph lists isomer by revision instead, and the same repositories come +// from it. import PackageDescription let package = Package( diff --git a/tools/foundation/check_link.py b/tools/foundation/check_link.py deleted file mode 100755 index 567b7cb5..00000000 --- a/tools/foundation/check_link.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python3 -"""Checks that apps built for wasm or Android link Isomer's Foundation and not -the Swift SDK's (swift-corelibs-foundation and its CoreFoundation, ICU and -FoundationEssentials copies): a library that imports Foundation without -depending on @isomer//:foundation finds the SDK's, which then links beside -Isomer's. - - tools/foundation/check_link.py [] [ ...] - (run in the workspace, after building the targets with the same flags: - `-c opt`, `--config=...`) - -Reads each link action's command line and the autolink files it reads, in -the configuration the flags give. An autolink file that is not on disk -(the targets were built with other flags, or not at all) is an error, not -a pass: a check that reads nothing finds nothing. -Exit status 1 and a list of what came from the SDK, if anything did. -""" - -import json -import os -import re -import subprocess -import sys - -# ICU itself is the SDK's (lib_FoundationICU.a, which Isomer's -# FoundationInternationalization links by name): not a leak. -SDK_LIBRARIES = re.compile( - r"(^|/)(lib)?(Foundation|CoreFoundation|FoundationEssentials|" - r"FoundationInternationalization|FoundationNetworking|FoundationXML|_FoundationCollections|" - r"_FoundationCShims)\.a$" -) -AUTOLINK = re.compile( - r"^-l(Foundation|CoreFoundation|FoundationEssentials|FoundationInternationalization|" - r"FoundationNetworking|FoundationXML|_FoundationCollections|_FoundationCShims)$" -) - - -def link_actions(target, flags): - query = 'mnemonic("CppLink", deps({}))'.format(target) - out = subprocess.run( - ["bazel", "aquery", query, "--output=jsonproto"] + flags, capture_output=True, text=True, check=True - ).stdout - data = json.loads(out or "{}") - return data.get("actions", []) - - -def main(argv): - # Labels are the targets; everything else is a flag (`-c opt` included). - targets = [a for a in argv if a.startswith(("//", "@", ":"))] - flags = [a for a in argv if not a.startswith(("//", "@", ":"))] - execroot = subprocess.run( - ["bazel", "info", "execution_root"] + flags, capture_output=True, text=True, check=True - ).stdout.strip() - problems = [] - unbuilt = [] - for target in targets: - for action in link_actions(target, flags): - args = action.get("arguments", []) - output = next((a for a in args if a.endswith((".wasm", ".so"))), None) - if output is None: - continue - for arg in args: - path = arg.lstrip("@") - if "swift_toolchain" in path and SDK_LIBRARIES.search(path): - problems.append("{}: links {}".format(output, path)) - if arg.startswith("@") and path.endswith(".autolink"): - full = os.path.join(execroot, path) - if not os.path.exists(full): - unbuilt.append(path) - continue - for flag in open(full).read().split(): - if AUTOLINK.match(flag): - problems.append("{}: {} asks for {}".format(output, path, flag)) - if unbuilt: - print("not built with these flags ({}): {} autolink files, e.g. {}".format( - " ".join(flags) or "no flags", len(set(unbuilt)), sorted(set(unbuilt))[0])) - print("build the targets with the same flags first") - return 2 - if problems: - print("\n".join(sorted(set(problems)))) - return 1 - print("ok: no Foundation from the Swift SDK in", ", ".join(targets)) - return 0 - - -if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) diff --git a/tools/library_evolution/defs.bzl b/tools/library_evolution/defs.bzl index 50d3aa26..e249c9db 100644 --- a/tools/library_evolution/defs.bzl +++ b/tools/library_evolution/defs.bzl @@ -18,15 +18,15 @@ Not the `swift.enable_library_evolution` feature: isomer's REPO.bazel turns that off for its packages, and one_configuration drops it from the package's modules' configuration (foundation/defs.bzl), so that a consumer's `--features` never changes how Isomer is built; and it would -reach swift-foundation, its collections and SwiftProtobuf beneath Isomer's -package too, which an app doesn't import. Copts, for Isomer's modules only: +reach SwiftProtobuf and the other packages beneath Isomer's package too, +which an app doesn't import. Copts, for Isomer's modules only: - isomer's own swift_library targets (the Isomer module, the hosts, os and OSLog, IsomerFFI, SwiftGPU, SwiftMap, Metal, ...) add `LIBRARY_EVOLUTION_COPTS` to their copts: a select on the flag, so the module is resilient in whatever configuration it is built; -- the modules of isomer's Swift package (Foundation, SwiftUI, Combine, - CoreGraphics, PhotosUI, ...) are generated targets of +- the modules of isomer's Swift package (SwiftUI, PhotosUI, and on Linux + and Windows CoreGraphics and Combine, ...) are generated targets of rules_swift_package_manager's, whose copts nothing here writes. Every dependent reaches them through `one_configuration` (`@isomer//:foundation`, `@isomer//:swift_ui`, each platform's `libraries/swift_ui:core`), whose @@ -36,6 +36,10 @@ package too, which an app doesn't import. Copts, for Isomer's modules only: each target's canonical label) name the package's targets with `-enable-library-evolution`. +Foundation, FoundationNetworking, IsomerFoundation, and on Android and the +web CoreGraphics and Combine, are the Swift SDK's (since 0.56), which Isomer's +SDKs build with library evolution whatever the flag, as an Apple SDK's are. + The module stays resilient through the copt alone: rules_swift doesn't know of it, so no .swiftinterface is emitted (an app links Isomer from source; nothing reads one). @@ -62,13 +66,9 @@ _PACKAGE_TARGETS = [ "Combine", "CoreGraphics", "CoreTransferable", - "Foundation", - "FoundationNetworking", "ImageIO", "Isomer", - "IsomerDispatchTime", "IsomerDriver", - "IsomerFoundation", "IsomerGRPCTransport", "IsomerProcessTransport", "IsomerRemote", diff --git a/tools/parity/parity.py b/tools/parity/parity.py index 5051ca13..91ea091f 100644 --- a/tools/parity/parity.py +++ b/tools/parity/parity.py @@ -56,7 +56,7 @@ "sources": ["foundation"], "apple": [("Foundation", None)], "isomer": ["Foundation", "FoundationEssentials", "FoundationInternationalization"], - "isomer_where": "`foundation/` (module `Foundation`) over swift-foundation's FoundationEssentials (swift-6.4.2-RELEASE, patched), and its FoundationInternationalization with ICU when an app builds with `--@isomer//foundation:internationalization`", + "isomer_where": "Isomer's Swift SDKs (module `Foundation`, from isomer_hermetic_toolchains' `Isomer/Sources/Foundation`) over swift-foundation's FoundationEssentials (swift-6.4.2-RELEASE, patched), and its FoundationInternationalization with ICU in the -i18n SDKs", }, { "name": "SwiftUI", @@ -190,12 +190,12 @@ def isomer_graphs(): "-include-spi-symbols", "-DISOMER_PARITY_%d" % int(datetime.datetime.now().timestamp())] subprocess.run( - # Foundation as an app that opts into FoundationInternationalization - # has it (what the report counts says so). + # isomer's own module registers the -i18n SDKs: Foundation as an app + # that opts into FoundationInternationalization has it (what the + # report counts says so). ["bazel", "build", "--platforms=//tools/platforms:wasm32", "--//foundation:internationalization"] + ["--@rules_swift//swift:copt=%s" % c for c in copts] - + ["//wasm/libraries/swift_ui:swift_ui", "//foundation:foundation", "//metal/metal:metal", - "//frameworks/combine", + + ["//wasm/libraries/swift_ui:swift_ui", "//metal/metal:metal", "//frameworks/core_transferable", "//frameworks/uniform_type_identifiers", "//wasm/libraries/swift_ui:photos_ui", # The Isomer umbrella and the Isomer* modules beneath it: what @@ -206,8 +206,7 @@ def isomer_graphs(): # directory of its own (the modules have the same names). for directory, flags, targets in ( (ISOMER_ANDROID_DIR, ["--platforms=//tools/platforms:android_arm64", "--//foundation:internationalization"], - ["//android/libraries/swift_ui:swift_ui", "//android/libraries/swift_ui:photos_ui", - "//foundation:foundation", "//frameworks/combine"]), + ["//android/libraries/swift_ui:swift_ui", "//android/libraries/swift_ui:photos_ui"]), (ISOMER_CLI_DIR, [], ["//cli/libraries/swift_ui:swift_ui"])): if os.path.isdir(directory): shutil.rmtree(directory) @@ -216,14 +215,21 @@ def isomer_graphs(): ["bazel", "build"] + flags + ["--@rules_swift//swift:copt=%s" % c.replace(ISOMER_DIR, directory) for c in copts] + targets, cwd=ROOT, check=True) - # Observation and Synchronization: the wasm SDK's own modules. + # Observation and Synchronization: the wasm SDK's own modules. And since + # 0.56 Foundation (with swift-foundation's FoundationEssentials and + # FoundationInternationalization beneath it), FoundationNetworking, + # IsomerFoundation, CoreGraphics and Combine: Isomer's Swift SDK carries + # them (docs/hermetic_toolchains.md), built from + # isomer_hermetic_toolchains' sources. base = bazel_output_base() bundle = glob.glob(os.path.join( base, "external", "rules_swift++swift+swift_toolchain_wasm_sdk_*", "*.artifactbundle", "*", "wasm32-unknown-wasip1"))[0] extractor = glob.glob(os.path.join( base, "external", "rules_swift++swift+swift_toolchain_*", "usr", "bin", "swift-symbolgraph-extract"))[0] - for module in ("Observation", "Synchronization"): + for module in ("Observation", "Synchronization", "Foundation", "FoundationEssentials", + "FoundationInternationalization", "FoundationNetworking", "IsomerFoundation", + "CoreGraphics", "Combine"): subprocess.run( [extractor, "-module-name", module, "-target", "wasm32-unknown-wasip1", "-sdk", os.path.join(bundle, "WASI.sdk"), @@ -831,14 +837,22 @@ def compare(apple, isomer, apple_elsewhere=()): return implemented, missing, set_aside, additions, partial, retyped -# Where an addition comes from: swift-foundation as upstream has it (its -# package's repository, rules_swift_package_manager's), or Isomer. +# Where an addition comes from: swift-foundation as upstream has it, or +# Isomer. Built from source, its package's repository +# (rules_swift_package_manager's) says; read from the Swift SDK's modules +# (since 0.56), which carry no source locations, the module declaring it. +UPSTREAM_MODULES = {"FoundationEssentials", "FoundationInternationalization"} + + def from_upstream(symbol, isomer_by_path): location = (symbol.get("location") or {}).get("uri", "") if not location: parent = isomer_by_path.get(tuple(symbol["pathComponents"][:-1])) location = (parent.get("location") or {}).get("uri", "") if parent else "" - return "swiftpkg_swift_foundation/" in location + if location: + return "swiftpkg_swift_foundation/" in location + precise = symbol.get("identifier", {}).get("precise", "") + return owners([precise]).get(precise) in UPSTREAM_MODULES _MODIFIERS = r"(?:(?:final|static|class|override|mutating|nonisolated(?:\(unsafe\))?|indirect|required|convenience)\s+)*" @@ -1202,10 +1216,13 @@ def by_type(members, level): # What the other builds' modules are compared as: Android's, as the wasm # build's (the same sources, their own hosts and #if branches), and the -# CLI's SwiftUI (the core with the terminal host, on macOS). +# CLI's SwiftUI (the core with the terminal host, on macOS). Foundation, +# CoreGraphics and Combine are the Swift SDKs' since 0.56, built for Android +# and wasm from the same sources by the same script (isomer_hermetic_toolchains' +# sdk/build.sh): only the wasm SDK's are read. OTHER_BUILDS = [ - ("Android", ISOMER_ANDROID_DIR, ["SwiftUI", "PhotosUI", "Foundation", "CoreGraphics", "ImageIO", - "CoreTransferable", "UniformTypeIdentifiers", "Combine"]), + ("Android", ISOMER_ANDROID_DIR, ["SwiftUI", "PhotosUI", "ImageIO", + "CoreTransferable", "UniformTypeIdentifiers"]), ("The CLI (macOS)", ISOMER_CLI_DIR, ["SwiftUI"]), ] diff --git a/tools/parity/reasons/Foundation.json b/tools/parity/reasons/Foundation.json index b06f9c45..625a2d43 100644 --- a/tools/parity/reasons/Foundation.json +++ b/tools/parity/reasons/Foundation.json @@ -2,10 +2,10 @@ "summary": "Isomer's Foundation, on the platforms that have no Foundation of Apple's, is swift-foundation's FoundationEssentials, built from its swift-6.4.2-RELEASE tag, with the Swift value types and API Swift code uses most: `Data`, `Date`, `URL`, `UUID`, `Decimal`, `AttributedString`, JSON and property-list coding, `Calendar` basics, `FileManager`, `ProcessInfo`, `Predicate`. Isomer's own module adds what Apple's framework and swift-corelibs-foundation give Swift code through Objective-C: `CharacterSet`, the `String` methods that come from `NSString` (searching, replacing, trimming, comparing, percent encoding) and `String(format:)`, as well as `Bundle`, `Stream`, English calendar symbols, and `URLSession` with its requests, responses, errors and WebSocket tasks, over transports the platform's host installs. There is no swift-corelibs-foundation layer: no `NS` classes, CoreFoundation, FoundationNetworking or FoundationXML. On Apple platforms an app uses Apple's Foundation.", "deviations": [ "`Bundle`, `InputStream` and `OutputStream` are Swift classes, not `NSObject` subclasses. A bundle is a directory found on the file system (`ISOMER_BUNDLE_PATH`, else the executable's directory); it reads no Info.plist; its strings tables are `.lproj/
.strings` (Xcode's text format or a property list), in the preferred language the host gives (`ISOMER_PREFERRED_LANGUAGES`), and `Bundle(for:)` is the main bundle. Streams read and write memory and files synchronously, with no run loop or delegate events.", - "Without `--@isomer//foundation:internationalization`, `Calendar`'s symbol lists (`shortWeekdaySymbols`, `monthSymbols`, `amSymbol`…) are English whatever the calendar's locale; with it they are ICU's.", + "With the plain Swift SDK, `Calendar`'s symbol lists (`shortWeekdaySymbols`, `monthSymbols`, `amSymbol`…) are English whatever the calendar's locale; with the -i18n SDK they are ICU's.", "The \"localized\" string comparisons (`localizedCompare`, `localizedStandardCompare`, `localizedCaseInsensitiveContains`…) compare without locale data. `String(format:)` does not apply a locale.", "`CharacterSet` equality between sets that are not explicit ranges compares every code point (slow, rare), and its hash reads only the ASCII and Latin-1 range.", - "Formatting and parsing, locales, calendars beyond the Gregorian and time zones beyond GMT (FoundationInternationalization, over ICU) are an app's choice: counted here as present, they are there when the app builds with `--@isomer//foundation:internationalization`. ICU's data then comes with the app; `isomer_web_app(icu_locales = [\"en\", …])` keeps only the languages it names (34 MB of data becomes 6 to 7 MB for one to five languages).", + "Formatting and parsing, locales, calendars beyond the Gregorian and time zones beyond GMT (FoundationInternationalization, over ICU) are an app's choice: counted here as present, they are there when the app registers the -i18n Swift SDK. ICU's data then comes with the app; `isomer_web_app(icu_locales = [\"en\", …])` keeps only the languages it names (34 MB of data becomes 6 to 7 MB for one to five languages).", "What corelibs adds to swift-foundation and apps reach for, written in Swift over swift-foundation and the C library: `NSRange` and its functions, `NSLock`, `NSRecursiveLock`, `NSCondition`, `Thread` (pthreads; in WebAssembly without threads there is one thread and starting another stops the program), `FileHandle` (reading, writing, seeking; not the run-loop background reads), `NSNumber` (not bridged: `intValue`, not `as? Int`), `NSRegularExpression` and `NSTextCheckingResult` (over Swift's `Regex`, matching by Unicode scalar with UTF-16 ranges; patterns in the syntax both read), `NSTemporaryDirectory()` and `NSHomeDirectory()`. They are Swift classes, not NSObject subclasses; `Thread.threadDictionary` is a Swift dictionary.", "`URLSession` sends http and https requests through the HTTP transport the platform's host installs in IsomerFoundation (`IsomerNetwork.http`: the browser's `fetch`, Android's HTTP stack, Apple's URLSession under WasmKit) and opens WebSockets through its WebSocket transport; without one a task fails with `URLError.notConnectedToInternet`. `file:` and `data:` URLs are read without a transport. A body is sent and received whole; the host's stack keeps its own cookies and cache and follows redirects. Completion handlers run on a task of their own, not on a delegate queue. `suspend()` keeps a task that has not started from starting; one already loading goes on. Configuration and request properties that steer Apple's network stack (cellular, expensive and constrained access, service types, connections per host, waiting for connectivity) are kept and not acted on. `URLSessionWebSocketTask.sendPing` answers once the connection is open (the transports carry no pings), and a close code `CloseCode` has no case for (an application's 4000s) reads as `.invalid`, where Apple's enum, imported from C, holds the number. `URLRequest.CachePolicy`, `NetworkServiceType` and `Attribution` are enums of `URLRequest`'s own (Apple's are typealiases of `NSURLRequest`'s); `URLResponse`, `URLSession` and its tasks and configuration are Swift classes. `Error.localizedDescription`, URLError's descriptions and `HTTPURLResponse.localizedString(forStatusCode:)` are English." ], diff --git a/tools/patches/swift_foundation_apple_interface.patch b/tools/patches/swift_foundation_apple_interface.patch deleted file mode 100644 index e866974b..00000000 --- a/tools/patches/swift_foundation_apple_interface.patch +++ /dev/null @@ -1,195 +0,0 @@ -diff --git a/Sources/FoundationEssentials/Data/Data.swift b/Sources/FoundationEssentials/Data/Data.swift ---- a/Sources/FoundationEssentials/Data/Data.swift -+++ b/Sources/FoundationEssentials/Data/Data.swift -@@ -278,9 +278,8 @@ - /// - span: An `OutputRawSpan` covering uninitialized memory with - /// space for the specified number of bytes. - @available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) -- @_alwaysEmitIntoClient -- @_spi(_) // TODO: Remove pending API surface amendment -- public init( -+ @usableFromInline -+ internal init( - rawCapacity capacity: Int, - initializingWith initializer: (_ span: inout OutputRawSpan) throws(E) -> Void - ) throws(E) { -@@ -726,8 +725,8 @@ - - /// Appends the bytes in the specified sequence to the end of the data. - @inline(__always) -- @_alwaysEmitIntoClient -- public mutating func append(contentsOf elements: some Sequence & ContiguousBytes) { -+ @usableFromInline -+ internal mutating func append(contentsOf elements: some Sequence & ContiguousBytes) { - // Since the sequence is already contiguous, access the underlying raw memory directly. - elements.withUnsafeBytes { - guard !$0.isEmpty else { return } -@@ -870,8 +869,8 @@ - /// - subrange: The range in the data to replace. - /// - newElements: The replacement bytes. - @inline(__always) -- @_alwaysEmitIntoClient -- public mutating func replaceSubrange(_ subrange: Range, with newElements: some Collection & ContiguousBytes) { -+ @usableFromInline -+ internal mutating func replaceSubrange(_ subrange: Range, with newElements: some Collection & ContiguousBytes) { - newElements.withUnsafeBytes { buffer in - _representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count) - } -diff --git a/Sources/FoundationEssentials/Decimal/Decimal.swift b/Sources/FoundationEssentials/Decimal/Decimal.swift -index 82a5dfa5..a1b76a50 100644 ---- a/Sources/FoundationEssentials/Decimal/Decimal.swift -+++ b/Sources/FoundationEssentials/Decimal/Decimal.swift -@@ -23,8 +23,9 @@ import ucrt - /// A structure representing a base-10 number. - @available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *) - public struct Decimal: Sendable { -- @_spi(SwiftCorelibsFoundation) -- public typealias Mantissa = (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) -+ // Isomer: internal (Apple's Decimal has no Mantissa; its initializer -+ // below spells the tuple out, as Apple's does). -+ internal typealias Mantissa = (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) - - internal struct Storage: Sendable { - var exponent: Int8 -@@ -122,14 +123,14 @@ public struct Decimal: Sendable { - } - } - -- @_spi(SwiftCorelibsFoundation) -+ // Isomer: public, as Apple's is. - public init( - _exponent: Int32 = 0, - _length: UInt32, - _isNegative: UInt32 = 0, - _isCompact: UInt32, - _reserved: UInt32 = 0, -- _mantissa: Mantissa -+ _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) - ) { - let length: UInt8 = (UInt8(truncatingIfNeeded: _length) & 0xF) << 4 - let isNegative: UInt8 = UInt8(truncatingIfNeeded: _isNegative & 0x1) == 0 ? 0 : 0b00001000 -@@ -143,8 +144,8 @@ public struct Decimal: Sendable { - ) - } - -- @_spi(SwiftCorelibsFoundation) -- public init(mantissa: UInt64, exponent: Int16, isNegative: Bool) { -+ // Isomer: internal, as the other declarations Apple's Decimal lacks. -+ internal init(mantissa: UInt64, exponent: Int16, isNegative: Bool) { - var d = Decimal(mantissa) - d._exponent += Int32(exponent) - d._isNegative = isNegative ? 1 : 0 -@@ -189,8 +190,8 @@ extension Decimal { - extension Decimal { - #if FOUNDATION_FRAMEWORK - #else -- @_spi(SwiftCorelibsFoundation) -- public func toString(with locale: Locale? = nil) -> String { -+ // Isomer: internal (not in Apple's Decimal). -+ internal func toString(with locale: Locale? = nil) -> String { - let separator: String - if let locale = locale, - let localizedSeparator = locale.decimalSeparator { -@@ -201,8 +202,8 @@ extension Decimal { - return _toString(withDecimalSeparator: separator) - } - -- @_spi(SwiftCorelibsFoundation) -- public static func decimal( -+ // Isomer: internal (not in Apple's Decimal). -+ internal static func decimal( - from stringView: String.UTF8View, - decimalSeparator: String.UTF8View, - matchEntireString: Bool -diff --git a/Sources/FoundationEssentials/Error/CocoaError.swift b/Sources/FoundationEssentials/Error/CocoaError.swift -index 71eae6b5..ae5d2f56 100644 ---- a/Sources/FoundationEssentials/Error/CocoaError.swift -+++ b/Sources/FoundationEssentials/Error/CocoaError.swift -@@ -174,8 +174,12 @@ extension CocoaError { - return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info) - } - #else -- public static func error(_ code: CocoaError.Code, userInfo: [String : AnyHashable]? = nil, url: URL? = nil) -> Error { -- var info: [String : AnyHashable] = userInfo ?? [:] -+ // Isomer: Apple's signature; what is kept are the string keys' hashable values. -+ public static func error(_ code: CocoaError.Code, userInfo: [AnyHashable : Any]? = nil, url: URL? = nil) -> Error { -+ var info: [String : AnyHashable] = [:] -+ for (key, value) in userInfo ?? [:] { -+ if let key = key.base as? String, let value = value as? AnyHashable { info[key] = value } -+ } - if let url = url { - info[NSURLErrorKey] = url - } -diff --git a/Sources/FoundationEssentials/FileManager/SwiftFileManager.swift b/Sources/FoundationEssentials/FileManager/SwiftFileManager.swift -index 0bac0fe9..8d4d24fc 100644 ---- a/Sources/FoundationEssentials/FileManager/SwiftFileManager.swift -+++ b/Sources/FoundationEssentials/FileManager/SwiftFileManager.swift -@@ -26,7 +26,8 @@ public struct FileAttributeType : Hashable, RawRepresentable, Sendable { - self.rawValue = rawValue - } - -- public init(_ rawValue: String) { -+ // Isomer: internal (Apple's FileAttributeType has init(rawValue:) only). -+ internal init(_ rawValue: String) { - self.rawValue = rawValue - } - -@@ -136,7 +137,8 @@ public struct FileProtectionType : RawRepresentable, Sendable { - /// The file is stored in an encrypted format on disk and cannot be - /// accessed until after the device has booted. - public static let completeUntilFirstUserAuthentication = Self(rawValue: "NSFileProtectionCompleteUntilFirstUserAuthentication") -- public static let inactive = Self(rawValue: "NSFileProtectionCompleteWhenUserInactive") -+ // Isomer: internal (not one of Apple's FileProtectionType values). -+ internal static let inactive = Self(rawValue: "NSFileProtectionCompleteWhenUserInactive") - } - - extension FileManager { -@@ -361,7 +363,9 @@ open class FileManager : @unchecked Sendable { - _impl.fileExists(atPath: path) - } - -- open func fileExists(atPath path: String, isDirectory: inout Bool) -> Bool { -+ // Isomer: not public. Apple's takes an Objective-C `ObjCBool`; ask -+ // attributesOfItem(atPath:)[.type] instead. -+ internal func fileExists(atPath path: String, isDirectory: inout Bool) -> Bool { - _impl.fileExists(atPath: path, isDirectory: &isDirectory) - } - -@@ -397,7 +401,8 @@ open class FileManager : @unchecked Sendable { - _impl.string(withFileSystemRepresentation: str, length: len) - } - -- open func withFileSystemRepresentation(for path: String, _ body: (UnsafePointer?) throws -> R) rethrows -> R { -+ // Isomer: internal (Apple's FileManager has fileSystemRepresentation(withPath:) instead). -+ internal func withFileSystemRepresentation(for path: String, _ body: (UnsafePointer?) throws -> R) rethrows -> R { - try path.withFileSystemRepresentation(body) - } - -diff --git a/Sources/FoundationEssentials/ProcessInfo/ProcessInfo+API.swift b/Sources/FoundationEssentials/ProcessInfo/ProcessInfo+API.swift -index 4adf89bc..0d9c4982 100644 ---- a/Sources/FoundationEssentials/ProcessInfo/ProcessInfo+API.swift -+++ b/Sources/FoundationEssentials/ProcessInfo/ProcessInfo+API.swift -@@ -115,7 +115,8 @@ extension ProcessInfo { - /// A structure that contains version information about the currently executing operating system, including major, minor, and patch version numbers. - /// - /// Use the ``ProcessInfo`` property ``ProcessInfo/operatingSystemVersion`` to fetch an instance of this type. You can also pass this type to ``ProcessInfo/isOperatingSystemAtLeast(_:)`` to determine whether the current operating system version is the same or later than the given value. --public struct OperatingSystemVersion: Hashable, Codable, Sendable { -+// Isomer: Apple's is a C struct, neither Hashable nor Codable. -+public struct OperatingSystemVersion: Sendable { - /// The major release number, such as 10 in version 10.9.3. - public let majorVersion: Int - /// The minor release number, such as 9 in version 10.9.3. -diff --git a/Sources/FoundationEssentials/String/StringProtocol+Stub.swift b/Sources/FoundationEssentials/String/StringProtocol+Stub.swift -index 87816f03..04f2ed18 100644 ---- a/Sources/FoundationEssentials/String/StringProtocol+Stub.swift -+++ b/Sources/FoundationEssentials/String/StringProtocol+Stub.swift -@@ -15,7 +15,8 @@ - extension StringProtocol { - /// Compares the string using the specified options and - /// returns the lexical ordering for the range. -- package func compare(_ aString: T, options mask: String.CompareOptions = [], range: Range? = nil) -> ComparisonResult { -+ // Isomer: public, with Apple's signature (the locale is not used). -+ public func compare(_ aString: T, options mask: String.CompareOptions = [], range: Range? = nil, locale: Locale? = nil) -> ComparisonResult { - var substr = Substring(self) - if let range { - substr = substr[range] diff --git a/tools/patches/swift_foundation_create_directory_root.patch b/tools/patches/swift_foundation_create_directory_root.patch deleted file mode 100644 index a824735c..00000000 --- a/tools/patches/swift_foundation_create_directory_root.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/Sources/FoundationEssentials/FileManager/FileManager+Directories.swift b/Sources/FoundationEssentials/FileManager/FileManager+Directories.swift -index b03a6b0a..d9379e32 100644 ---- a/Sources/FoundationEssentials/FileManager/FileManager+Directories.swift -+++ b/Sources/FoundationEssentials/FileManager/FileManager+Directories.swift -@@ -457,7 +457,7 @@ extension _FileManagerImpl { - return - } - let parent = path.deletingLastPathComponent() -- if !parent.isEmpty { -+ if !parent.isEmpty && parent != path { - try _create(path: parent, leafFile: false) - } - try fileManager.withFileSystemRepresentation(for: path) { pathFsRep in diff --git a/tools/patches/swift_foundation_package_helpers.patch b/tools/patches/swift_foundation_package_helpers.patch deleted file mode 100644 index 8e696b9a..00000000 --- a/tools/patches/swift_foundation_package_helpers.patch +++ /dev/null @@ -1,89 +0,0 @@ -diff --git a/Sources/FoundationEssentials/String/BuiltInUnicodeScalarSet.swift b/Sources/FoundationEssentials/String/BuiltInUnicodeScalarSet.swift -index 18b3bb60..72813e57 100644 ---- a/Sources/FoundationEssentials/String/BuiltInUnicodeScalarSet.swift -+++ b/Sources/FoundationEssentials/String/BuiltInUnicodeScalarSet.swift -@@ -25,7 +25,7 @@ internal import _FoundationCollections - // Represents sets of unicode scalars of those whose bitmap data we own. - // whitespace, whitespaceAndNewline, and newline are not included since they're not stored with bitmaps - // This only contains a subset of predefined CFCharacterSet that are in use for now. --internal struct BuiltInUnicodeScalarSet { -+package struct BuiltInUnicodeScalarSet { - enum SetType { - case control - case whitespace -@@ -216,7 +216,7 @@ internal struct BuiltInUnicodeScalarSet { - } - - // CFUniCharIsMemberOf -- internal func contains(_ scalar: Unicode.Scalar) -> Bool { -+ package func contains(_ scalar: Unicode.Scalar) -> Bool { - switch charset { - case .whitespace: - return isWhitespace(scalar) -@@ -445,12 +445,12 @@ internal struct BuiltInUnicodeScalarSet { - return ((scalar.value >= 0x000A && scalar.value <= 0x000D) || (scalar.value == 0x0085) || (scalar.value == 0x2028) || (scalar.value == 0x2029)) - } - -- static let uppercaseLetters = Self.init(type: .uppercaseLetter) -- static let lowercaseLetters = Self.init(type: .lowercaseLetter) -+ package static let uppercaseLetters = Self.init(type: .uppercaseLetter) -+ package static let lowercaseLetters = Self.init(type: .lowercaseLetter) - static let caseIgnorables = Self.init(type: .caseIgnorable) - static let hfsPlusDecomposables = Self.init(type: .hfsPlusDecomposable) - static let graphemeExtends = Self.init(type: .graphemeExtend) -- static let canonicalDecomposables = Self.init(type: .canonicalDecomposable) -+ package static let canonicalDecomposables = Self.init(type: .canonicalDecomposable) - } - - #if !FOUNDATION_FRAMEWORK -diff --git a/Sources/FoundationEssentials/String/RegexPatternCache.swift b/Sources/FoundationEssentials/String/RegexPatternCache.swift -index 9c8be6e8..e8e63da0 100644 ---- a/Sources/FoundationEssentials/String/RegexPatternCache.swift -+++ b/Sources/FoundationEssentials/String/RegexPatternCache.swift -@@ -12,7 +12,7 @@ - - internal import Synchronization - --struct RegexPatternCache: Sendable, ~Copyable { -+package struct RegexPatternCache: Sendable, ~Copyable { - private struct Key : Sendable, Hashable { - var pattern: String - var caseInsensitive: Bool -@@ -20,13 +20,13 @@ struct RegexPatternCache: Sendable, ~Copyable { - - private let _lock: Mutex<[Key: Regex]> - -- static let cache = RegexPatternCache() -+ package static let cache = RegexPatternCache() - - fileprivate init() { - _lock = Mutex(.init()) - } - -- func regex(for pattern: String, caseInsensitive: Bool) throws -> Regex? { -+ package func regex(for pattern: String, caseInsensitive: Bool) throws -> Regex? { - - let key = Key(pattern: pattern, caseInsensitive: caseInsensitive) - -diff --git a/Sources/FoundationEssentials/String/String+Comparison.swift b/Sources/FoundationEssentials/String/String+Comparison.swift -index 2520f2c8..30109bc8 100644 ---- a/Sources/FoundationEssentials/String/String+Comparison.swift -+++ b/Sources/FoundationEssentials/String/String+Comparison.swift -@@ -599,7 +599,7 @@ extension Substring { - return unicodeScalars._rangeOfCharacter(anchored: options.contains(.anchored), backwards: options.contains(.backwards), matchingPredicate: set.contains) - } - -- func _range(of strToFind: Substring, options: String.CompareOptions) throws -> Range? { -+ package func _range(of strToFind: Substring, options: String.CompareOptions) throws -> Range? { - #if !NO_REGEX - if options.contains(.regularExpression) { - guard let regex = try RegexPatternCache.cache.regex(for: String(strToFind), caseInsensitive: options.contains(.caseInsensitive)) else { -@@ -684,7 +684,7 @@ extension Substring.UnicodeScalarView { - return ComparisonResult(stringIndex: idx1, idx2: idx2, endIndex1: endIndex, endIndex2: other.endIndex) - } - -- func _rangeOfCharacter(anchored: Bool, backwards: Bool, matchingPredicate predicate: (Unicode.Scalar) -> Bool) -> Range? { -+ package func _rangeOfCharacter(anchored: Bool, backwards: Bool, matchingPredicate predicate: (Unicode.Scalar) -> Bool) -> Range? { - guard !isEmpty else { return nil } - - let fromLoc: String.Index diff --git a/tools/patches/swift_foundation_sdk_icu.patch b/tools/patches/swift_foundation_sdk_icu.patch deleted file mode 100644 index 4a08da3e..00000000 --- a/tools/patches/swift_foundation_sdk_icu.patch +++ /dev/null @@ -1,22 +0,0 @@ ---- a/Package.swift -+++ b/Package.swift -@@ -179,7 +179,6 @@ - dependencies: [ - .target(name: "FoundationEssentials"), - .target(name: "_FoundationCShims"), -- .product(name: "_FoundationICU", package: "swift-foundation-icu") - ], - exclude: [ - "String/CMakeLists.txt", -@@ -195,7 +194,10 @@ - swiftSettings: [ - .enableExperimentalFeature("AccessLevelOnImport"), - .enableExperimentalFeature("Lifetimes"), -- ] + availabilityMacros + featureSettings -+ ] + availabilityMacros + featureSettings, -+ linkerSettings: [ -+ .linkedLibrary("_FoundationICU"), -+ ] - ), - - .testTarget( diff --git a/tools/platforms/transition.bzl b/tools/platforms/transition.bzl index 36b5d444..3671749c 100644 --- a/tools/platforms/transition.bzl +++ b/tools/platforms/transition.bzl @@ -8,8 +8,10 @@ _INTERNATIONALIZATION = str(Label("//foundation:internationalization")) def _platform_transition_impl(settings, attr): return { "//command_line_option:platforms": str(attr.platform), - # Isomer's Foundation with FoundationInternationalization and ICU - # (//foundation), when the binary asks for it or the build does. + # Isomer's Foundation with FoundationInternationalization and ICU, + # when the binary asks for it or the build does: the Swift SDK's + # Foundation is, the -i18n one, and the setting checks it is + # (foundation/BUILD.bazel). _INTERNATIONALIZATION: attr.internationalization or settings[_INTERNATIONALIZATION], } @@ -30,7 +32,7 @@ transition_binary = rule( "platform": attr.label(mandatory = True, doc = "Platform to build `binary` for."), "internationalization": attr.bool( default = False, - doc = "Build Isomer's Foundation with FoundationInternationalization (ICU).", + doc = "Ask for Isomer's Foundation with FoundationInternationalization (ICU): the -i18n Swift SDK's.", ), "_allowlist_function_transition": attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist", diff --git a/tools/wasm/defs.bzl b/tools/wasm/defs.bzl index 943cdbbc..7f26720c 100644 --- a/tools/wasm/defs.bzl +++ b/tools/wasm/defs.bzl @@ -404,8 +404,8 @@ def isomer_web_app( # which 10 MB of export names), where the page calls some sixty. exports = "host", export_entries = ISOMER_HOST_ENTRIES, - # ICU's data, less what ICU_DROP leaves out (an app with the full - # Foundation; nothing for one without). + # ICU's data, less what ICU_DROP leaves out (an app on the -i18n + # Swift SDK; nothing for one on the plain SDK, which links no ICU). reactor_deps = [":app_bridge_icu"], linkopts = [ # wasm-ld defaults the linear stack to ~1 MiB, which Swift's deeply @@ -427,9 +427,8 @@ def isomer_web_app( icu_data_library( name = "app_bridge_icu", wasm = ":app_bridge_all.wasm", - # With ICU (the full Foundation, or Isomer's with - # //foundation:internationalization): only these languages' locale - # data, when given. + # With ICU (the -i18n Swift SDK's Foundation, which links the SDK's + # ICU): only these languages' locale data, when given. locales = icu_locales, ) From 4661c7d69dc661126aea2e6b2afbc42be79902a9 Mon Sep 17 00:00:00 2001 From: Agent <344224964+logan-shire-agent[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:05:46 -0500 Subject: [PATCH 2/3] rules_swift 4.3.0.isomer.1 (upstream 4.3.0, with #2012, and #1860, #1990, #1995 and #2000); the SDKs' checksums at isomer_hermetic_toolchains 42fd9591; the single-object lesson in docs/hermetic_toolchains.md --- AGENTS.md | 26 ++++++++++++++++---------- MODULE.bazel | 35 +++++++++++++++++------------------ README.md | 22 ++++++++++++---------- TODO.md | 18 +++++++----------- docs/hermetic_toolchains.md | 19 +++++++++++++++---- examples/MODULE.bazel | 8 ++++---- 6 files changed, 71 insertions(+), 57 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2dc09d82..b87d40a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,7 +52,7 @@ nothing under `swift_ffi/` may depend on anything outside it but Foundation, and so on up. A consumer pins ONE version of isomer (by version from the project's registry, AttilaTheFun/bazel_registry, from 0.36.0; a commit between releases) and lists that registry before the BCR in its .bazelrc: -no override of isomer's dependencies since 0.40 (rules_swift 4.2.2.isomer.3 +no override of isomer's dependencies since 0.40 (rules_swift 4.3.0.isomer.1 sorts above the 4.2.2 rules_applecross asks for). **Versions (from 0.38).** A version is MAJOR.MINOR.BUILD; there are no @@ -86,10 +86,10 @@ minor (MAJOR.MINOR.0) before the release's commit. by version at a release (a commit is fine on a branch, or on main between releases). Bazel modules come from bazel_registry, before the BCR: isomer's releases, visor's, and the forks isomer carries until upstream takes their -changes, as patched versions (rules_swift 4.2.2.isomer.3: upstream 4.2.2 -with rules_swift#1989, #1860, #1990, #1995, #1985 and #2000, each a patch -taken from the PR's head). A change to a fork or to those -patches is a new entry (.isomer.4), made with the registry's +changes, as patched versions (rules_swift 4.3.0.isomer.1: upstream 4.3.0 +with rules_swift#1860, #1990, #1995 and #2000, each a patch taken from the +PR's head). A change to a fork or to those +patches is a new entry (.isomer.2), made with the registry's tools/add_version.py --fork and approved there like any version. Swift packages are SwiftPM's, through rules_swift_package_manager, never Bazel modules. tools/released_pins.sh says whether every pin is a released @@ -214,7 +214,7 @@ a repository of its own): toolchain by an absolute path that Bazel's inclusion check rejects; C compiled for wasm had to avoid them (-nobuiltininc and shims, a hand-declared pthread_self). rules_swift#1989 (a patch of isomer's from - 0.34, merged upstream after 4.2.2; in the registry's rules_swift) gives + 0.34, in upstream's 4.3.0) gives compiles the Swift SDK's clang resource directory, as links already had: the headers come from the SDK, among the action's inputs. A package's C (swift_sql's amalgamation, through rules_swift_package_manager) then @@ -552,10 +552,16 @@ SwiftUI libraries → swift_map/ → swift_gpu/ → metal/ → swift_ffi registered through `--extra_toolchains`, the build-time Swift tools' CppArchive fails in the sandbox (no apple-support-ar-wrapper); `--strategy=CppArchive=local` works around it. -- **rules_swift 4.2.2.isomer.3** from the registry: upstream 4.2.2 and six - pull requests (MODULE.bazel). It sorts above the 4.2.2 rules_applecross - asks for, so MVS keeps it with no override in any root (until 0.40 the - fork was 4.1.0.isomer.N, held by an override every consumer repeated). +- **rules_swift 4.3.0.isomer.1** from the registry (since 0.56): + upstream 4.3.0 and four pull requests, each a patch from its head: + #1860 and #1990 (the wasip1-threads SDK beside the single-threaded one), + #1995 (Swift/C++ interop on Android) and #2000 (Android below API 28, + merged after 4.3.0). 4.3.0 has the rest of what 4.2.2.isomer.3 carried + (#1989, #1985), #2012 (`swift.android_sdk(url = …)`, Isomer's Swift + SDKs) and #1999 (no explicit modules for Android and wasm). It sorts + above the 4.2.2 rules_applecross asks for, so MVS keeps it with no + override in any root (until 0.40 the fork was 4.1.0.isomer.N, held by an + override every consumer repeated). - **The Apple targets build on Linux too** (rules_applecross, 2026-10-26; the project registry's 0.0.3.382f8c3, its main at 382f8c3, until it has a release in the BCR): Xcode 27.0's SDKs from an SDK archive, the Swift diff --git a/MODULE.bazel b/MODULE.bazel index edcff331..e69aeb50 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -40,31 +40,30 @@ bazel_dep(name = "platforms", version = "1.1.0") # Apple platform (uses the locally installed Xcode, as all Bazel apple builds do). # rules_swift from this project's registry (AttilaTheFun/bazel_registry, -# listed before the BCR in .bazelrc): 4.2.2.isomer.4 is upstream's 4.2.2 with -# seven rules_swift pull requests until a release has them, each a patch in -# the registry entry, taken from the PR's head: -# * #1989 (merged after 4.2.2): C compiled for wasm gets the Swift SDK's -# clang resource directory, so and come from the -# SDK, among the action's inputs; C such as SQLite's amalgamation builds -# as is; +# listed before the BCR in .bazelrc): 4.3.0.isomer.1 is upstream's 4.3.0 +# with four rules_swift pull requests until a release has them, each a patch +# in the registry entry, taken from the PR's head: # * #1860: a metadata-driven wasm SDK and its wasip1-threads variant; # * #1990: a single-threaded and a threads wasm SDK side by side (two # `swift.wasm_sdk` tags), chosen by a platform's # `@rules_swift//swift/toolchains/wasm:threaded` constraint; # * #1995: Swift/C++ interop on Android (the SDK's clang headers copied # from the paired toolchain, swiftCxx and swiftCxxStdlib linked from -# beside the shared runtime, -lc++ the static libc++). -# * #1985 (merged after 4.2.2): swift.org's release metadata through 6.4.2; -# * #2000: Android targets down to the Swift SDK's own minimum (6.4's: API -# 23), without RELR relocations below 28; -# * #2012: `swift.android_sdk(url = …, sha256 = …)`, an Android Swift SDK -# from any URL, as #1860 gives `swift.wasm_sdk`: how a consumer registers -# Isomer's Swift SDKs (README, "Upgrading isomer"). +# beside the shared runtime, -lc++ the static libc++); +# * #2000 (merged after 4.3.0): Android targets down to the Swift SDK's +# own minimum (6.4's: API 23), without RELR relocations below 28; 4.3.0 +# alone fails any target below 28 (#1998). +# 4.3.0 itself has what 4.2.2.isomer.3 carried besides: #1989 (C compiled +# for wasm gets the Swift SDK's clang resource directory, so SQLite's +# amalgamation builds as is), #1985 (swift.org's release metadata through +# 6.4.2) and #2012 (`swift.android_sdk(url = …, sha256 = …)`, how a consumer +# registers Isomer's Swift SDKs: README, "Isomer's Swift SDKs"); and #1999, +# which turns explicit modules off for Android and wasm. # It sorts above the 4.2.2 rules_applecross asks for, so no override holds -# it, here or in a consumer. A change is a new entry (4.2.2.isomer.5) made +# it, here or in a consumer. A change is a new entry (4.3.0.isomer.2) made # with the registry's tools/add_version.py --fork; back to a plain BCR # version at the release that has them all. -bazel_dep(name = "rules_swift", version = "4.2.2.isomer.4") +bazel_dep(name = "rules_swift", version = "4.3.0.isomer.1") # rules_apple and apple_support at rules_applecross's versions, from this # project's registry: rules_apple 5.3.1.applecross.6 is rules_apple 5.3.1 # with rules_applecross's patches (bundling and signing on Linux), asking @@ -423,7 +422,7 @@ swift.toolchain( # most applications do (README, "Upgrading isomer"). swift.wasm_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm-i18n.artifactbundle.tar.gz", - sha256 = "d787225d4cb19003b6674272bb4643153aab751016d9f14c064ba58981e68f38", + sha256 = "cc3423d1dfa969e1fb255ed324af6a9e3c7dedc06b75d90a3ff74adcce10877c", ) # No wasi-threads SDK beside it since 0.41: Isomer's was a build of # Swift 6.3.2 with swiftlang/swift#92018, which reaches a release in 6.5; @@ -431,7 +430,7 @@ swift.wasm_sdk( # for it (TODO.md). swift.android_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android-i18n.artifactbundle.tar.gz", - sha256 = "4a726a303e53529ba2d8f6c97f735ce6b880313740efc53065028a460aee0296", + sha256 = "9ed7cd5051cc276acd14a5210d72311f2b4b7984c4bdaa77dd25bafad2170d93", ) use_repo( swift, diff --git a/README.md b/README.md index d9c390f3..ab5bab1f 100644 --- a/README.md +++ b/README.md @@ -785,7 +785,7 @@ The isomer the root depends on and the one its Package.swift lists are the module's release: one isomer in the build. Nothing of isomer's needs an override in your MODULE.bazel since 0.40 (its -rules_swift, 4.2.2.isomer.4, sorts above the version rules_applecross asks +rules_swift, 4.3.0.isomer.1, sorts above the version rules_applecross asks for); you still register the toolchains, and only those of the platforms you build: an app for iOS, the Mac and Android declares the host toolchain and Isomer's Android SDK (below) and registers the Android Swift toolchains, with @@ -797,7 +797,7 @@ renderer are all part of this one module (`@isomer//swift_ffi/...`, them. SQLite (swift_sql, a Swift package: list it in the Package.swift your rules_swift_package_manager graph reads) left this module at 0.34; the examples use it. C compiled for wasm, swift_sql's included, needs -rules_swift#1989, which the registry's rules_swift carries. +rules_swift#1989, which rules_swift has since 4.3.0. **Isomer's Swift SDKs.** On Android and the web Foundation is the Swift SDK's, so an app registers Isomer's SDKs (since 0.56) in the `swift` block @@ -810,7 +810,7 @@ If you build for Android: ```starlark swift.android_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android.artifactbundle.tar.gz", - sha256 = "1fce2fe24ec9b7c54f97fe2aff41ceab01b5acbc5a09492c50cc918e1dbcdbac", + sha256 = "557ed5ffc5c9d2a2061ea3ea24a2ec0e44dcabd6f42b37ef319e2f08198034fc", ) ``` @@ -819,7 +819,7 @@ If you build for the web: ```starlark swift.wasm_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm.artifactbundle.tar.gz", - sha256 = "d63e3f15297575b634dcc07b36e19111fb3a24b7dbac0e9b217d3c3532b3bb11", + sha256 = "3dbfc93e5c91e92d197e3660a488fd580133200df75bcaca90f3b50c5782ae93", ) ``` @@ -832,12 +832,12 @@ and ICU (tens of megabytes of data, which `icu_locales` trims on the web): # Android, formatting: swift.android_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android-i18n.artifactbundle.tar.gz", - sha256 = "4a726a303e53529ba2d8f6c97f735ce6b880313740efc53065028a460aee0296", + sha256 = "9ed7cd5051cc276acd14a5210d72311f2b4b7984c4bdaa77dd25bafad2170d93", ) # The web, formatting: swift.wasm_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm-i18n.artifactbundle.tar.gz", - sha256 = "d787225d4cb19003b6674272bb4643153aab751016d9f14c064ba58981e68f38", + sha256 = "cc3423d1dfa969e1fb255ed324af6a9e3c7dedc06b75d90a3ff74adcce10877c", ) ``` @@ -913,9 +913,11 @@ Each release's notes have an Upgrading section; these things are easy to miss: the SDK registered is the -i18n one (a build that sets it with the plain SDK fails, saying which to register); keep it if your app sets it, or drop it with the -i18n SDK in place. - - rules_swift is the registry's 4.2.2.isomer.4 (its - `swift.android_sdk(url = …)`); your own override of rules_swift, if you - kept one, has to be that version. + - rules_swift is the registry's 4.3.0.isomer.1 (upstream 4.3.0, which + takes `swift.android_sdk(url = …)`, and four pull requests); your own + override of rules_swift, if you kept one, has to be that version. + 4.3.0 builds Android and wasm targets without explicit modules + (rules_swift#1999). - `tools/foundation/check_link.py` is gone: there is one Foundation to link. @@ -995,7 +997,7 @@ Each release's notes have an Upgrading section; these things are easy to miss: whatever version isomer asks for: bumping isomer alone silently keeps the old fork. Since 0.40 isomer's rules_swift needs no override (it sorts above rules_applecross's); delete yours, or move it to the version isomer's - release names (4.2.2.isomer.3 at 0.41). + release names (4.3.0.isomer.1 at 0.56). ### Swift features, Java and library evolution diff --git a/TODO.md b/TODO.md index 767de6c0..84be6e70 100644 --- a/TODO.md +++ b/TODO.md @@ -430,7 +430,7 @@ with NDK r30, so its own fallbacks are compiled in (the runtime's `posix_spawn`) and no shim of Isomer's is needed. An app sets `android.ndk(api_level = 23)` and `isomer_android_app(min_sdk_version = 23)` (README, "Android below API 28"); rules_swift#2000 (in the registry's -4.2.2.isomer.3) reads the SDK's minimum and leaves out RELR below 28. +4.3.0.isomer.1) reads the SDK's minimum and leaves out RELR below 28. Isomer's Kotlin calls above 23 are behind version checks (#96). - Open: Shireworks' api23 emulator config doesn't boot yet (Shireworks), @@ -469,21 +469,17 @@ project's own modules. Every change we carry has an upstream PR now (2026-11-04, drafts unless noted); each patch or fork goes when a release has it. -- **rules_swift** (the registry's 4.2.2.isomer.3: upstream 4.2.2 and a - patch per PR, from its head): +- **rules_swift** (the registry's 4.3.0.isomer.1 since 0.56: upstream 4.3.0, + which has #1985, #1989, #1998, #1999 and #2012, and a patch per PR, from + its head): - bazelbuild/rules_swift#1860 (open): the metadata-driven wasm SDK and its wasip1-threads variant; - #1990 (open, on #1860): a single-threaded and a threads wasm SDK side by side; - - #1989 (merged after 4.2.2): the wasm SDK's clang resource directory for - C compiles; - #1995 (open): Swift/C++ interop on Android; - - #1985 (merged after 4.2.2): swift.org's release metadata through 6.4.2; - - #2000 (open, rebased over #1998 at ab75b825): Android down to the - Swift SDK's own minimum (6.4's: 23), no RELR below 28. Upstream main - has #1998 (merged 2026-11-06, b7e99a5b), which fails below API 28: a - rules_swift release with #1998 and not #2000 needs the registry's patch - to remove `_check_android_api` and its call too (#2000's head does); + - #2000 (merged after 4.3.0, e901d23b): Android down to the Swift SDK's + own minimum (6.4's: 23), no RELR below 28; 4.3.0 alone (#1998) fails + any target below 28; - #1988 (draft): `swift.windows_sdk`, Windows built on Linux with the builder's own SDKs (Isomer's tools/windows, upstream's tools/windows_sdk), which tools/windows then gives way to. diff --git a/docs/hermetic_toolchains.md b/docs/hermetic_toolchains.md index 6d832a56..3eeb7385 100644 --- a/docs/hermetic_toolchains.md +++ b/docs/hermetic_toolchains.md @@ -41,6 +41,16 @@ What it taught: FoundationInternationalization imports ICU (`_FoundationICU`) internally, so it asks its clients for it by `-public-autolink-library`, as swift-foundation's CMake build does. +- **One object a module.** A static archive's member is linked only when a + symbol in it is wanted, and a file of conformances alone defines nothing a + client names: Foundation's NSNumberBridging.swift (Swift's numbers + bridging to NSNumber, which `json["n"] as? Int` needs) was dropped, and + the cast failed. So each Swift module is compiled whole into one object + (`-num-threads 0`): a module linked at all is linked whole, as Bazel links + a library built from source, and `--gc-sections` still drops what + nothing reaches. (Not objects merged by `ld -r` afterwards: wasm-ld's + loses the retain flag on Swift's metadata, which the final link then + collects.) - **rules_swift took an Android SDK by checksum only**, its URL download.swift.org's. rules_swift#2012 adds `url` (below). @@ -134,10 +144,11 @@ swift.wasm_sdk( and the `-i18n` URL (with its own sha256) if the app formats dates or numbers. An app that builds for Android alone registers no wasm SDK. -`swift.wasm_sdk` takes `url` through rules_swift#1860 and `swift.android_sdk` -through rules_swift#2012 (generic: any Swift SDK artifact bundle at any URL), -both in the registry's rules_swift 4.2.2.isomer.4, which isomer asks for and -MVS gives every consumer. +`swift.wasm_sdk` takes `url` through rules_swift#1860 (a patch of the +registry's rules_swift 4.3.0.isomer.1) and `swift.android_sdk` through +rules_swift#2012 (in rules_swift 4.3.0; generic: any Swift SDK artifact bundle +at any URL); isomer asks for 4.3.0.isomer.1, and MVS gives it every +consumer. ## isomer after the move diff --git a/examples/MODULE.bazel b/examples/MODULE.bazel index ffd368b8..c60813da 100644 --- a/examples/MODULE.bazel +++ b/examples/MODULE.bazel @@ -52,10 +52,10 @@ local_path_override( # --- What isomer needs from its consumer ------------------------------- # rules_swift: isomer's patched version comes from the project's registry -# (.bazelrc lists it before the BCR), patches and all: 4.2.2.isomer.4, which +# (.bazelrc lists it before the BCR), patches and all: 4.3.0.isomer.1, which # sorts above the 4.2.2 rules_applecross asks for, so it needs no override # (and takes `swift.android_sdk(url = …)`, below). -bazel_dep(name = "rules_swift", version = "4.2.2.isomer.4") +bazel_dep(name = "rules_swift", version = "4.3.0.isomer.1") # swift_ffi, swift_gpu and swift_map are part of the isomer module # (`@isomer//swift_ffi/...`, `@isomer//swift_gpu/...`, `@isomer//swift_map/...`): @@ -85,7 +85,7 @@ swift.toolchain( # sha256 from the release's notes). swift.wasm_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_wasm.artifactbundle.tar.gz", - sha256 = "d63e3f15297575b634dcc07b36e19111fb3a24b7dbac0e9b217d3c3532b3bb11", + sha256 = "3dbfc93e5c91e92d197e3660a488fd580133200df75bcaca90f3b50c5782ae93", ) # No wasi-threads SDK beside it since 0.41: Isomer's was a build of # Swift 6.3.2 with swiftlang/swift#92018, which reaches a release in 6.5; @@ -93,7 +93,7 @@ swift.wasm_sdk( # for it (TODO.md). swift.android_sdk( url = "https://github.com/AttilaTheFun/isomer_hermetic_toolchains/releases/download/isomer-6.4.2.1/swift-6.4.2-RELEASE_android.artifactbundle.tar.gz", - sha256 = "1fce2fe24ec9b7c54f97fe2aff41ceab01b5acbc5a09492c50cc918e1dbcdbac", + sha256 = "557ed5ffc5c9d2a2061ea3ea24a2ec0e44dcabd6f42b37ef319e2f08198034fc", ) use_repo( swift, From 196420ea47e1ff6c19facde741256d2c40538cd9 Mon Sep 17 00:00:00 2001 From: Agent <344224964+logan-shire-agent[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:29:37 -0500 Subject: [PATCH 3/3] A Swift compile's own Clang module cache (rules_swift 4.3.0 builds Android and wasm without explicit modules, and the shared cache then holds two _Builtin_stddef) --- .bazelrc | 7 +++++++ README.md | 6 +++++- examples/.bazelrc | 7 +++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/.bazelrc b/.bazelrc index 9aba675e..4f23651b 100644 --- a/.bazelrc +++ b/.bazelrc @@ -86,6 +86,13 @@ test --test_output=errors # malformed response". (The Apple build requires a local Xcode anyway.) build --strategy=SwiftCompile=local +# A Clang module cache of each Swift compile's own (until rules_swift says so +# for Android and wasm): rules_swift 4.3.0 builds those without explicit +# modules (rules_swift#1999), so their Clang modules are built implicitly, +# and in the shared cache two builds of one of the Swift SDK's modules +# conflict ("module '_Builtin_stddef' is defined in both …"). +build --features=-swift.use_global_module_cache + # swift_ffi's `analyzer` / `generator` are swift.org-toolchain swift_binaries # invoked as build actions (the analyzer aspect + ffi_generate). They need the # Swift runtime, which the action sandbox doesn't stage — so each host resolves diff --git a/README.md b/README.md index ab5bab1f..b422dd55 100644 --- a/README.md +++ b/README.md @@ -917,7 +917,11 @@ Each release's notes have an Upgrading section; these things are easy to miss: takes `swift.android_sdk(url = …)`, and four pull requests); your own override of rules_swift, if you kept one, has to be that version. 4.3.0 builds Android and wasm targets without explicit modules - (rules_swift#1999). + (rules_swift#1999), and their Clang modules then conflict in Bazel's + shared module cache ("module '_Builtin_stddef' is defined in both …"): + add `build --features=-swift.use_global_module_cache` to your + `.bazelrc`, as examples/.bazelrc has it, until rules_swift turns that + off for them. - `tools/foundation/check_link.py` is gone: there is one Foundation to link. diff --git a/examples/.bazelrc b/examples/.bazelrc index 3eb2d5ff..d3c97161 100644 --- a/examples/.bazelrc +++ b/examples/.bazelrc @@ -123,6 +123,13 @@ test --test_output=errors # malformed response". (The Apple build requires a local Xcode anyway.) build --strategy=SwiftCompile=local +# A Clang module cache of each Swift compile's own (until rules_swift says so +# for Android and wasm): rules_swift 4.3.0 builds those without explicit +# modules (rules_swift#1999), so their Clang modules are built implicitly, +# and in the shared cache two builds of one of the Swift SDK's modules +# conflict ("module '_Builtin_stddef' is defined in both …"). +build --features=-swift.use_global_module_cache + # swift_ffi's `analyzer` / `generator` are swift.org-toolchain swift_binaries # invoked as build actions (the analyzer aspect + ffi_generate). They need the # Swift runtime, which the action sandbox doesn't stage — so each host resolves