Skip to content

Refactoring some import conditions #298

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions Sources/FoundationEssentials/Calendar/Calendar_Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@
//
//===----------------------------------------------------------------------===//


#if FOUNDATION_FRAMEWORK
@_implementationOnly import _ForSwiftFoundation
import CoreFoundation
#else
#endif

/// Singleton which listens for notifications about preference changes for Calendar and holds cached singletons for the current locale, calendar, and time zone.
Expand All @@ -24,7 +22,7 @@ struct CalendarCache : Sendable {

// _CalendarICU, if present
static var calendarICUClass: _CalendarProtocol.Type = {
#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && canImport(FoundationICU)
_CalendarICU.self
#else
if let name = _typeByName("FoundationInternationalization._CalendarICU"), let t = name as? _CalendarProtocol.Type {
Expand Down
8 changes: 8 additions & 0 deletions Sources/FoundationEssentials/Data/Data.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ private func malloc_good_size(_ size: Int) -> Int {
return size
}

#elseif canImport(C)

private func malloc_good_size(_ size: Int) -> Int {
return size
}

#endif

#if os(Windows)
Expand All @@ -46,6 +52,8 @@ import func WinSDK.UnmapViewOfFile
internal func __DataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) {
#if os(Windows)
_ = UnmapViewOfFile(mem)
#elseif canImport(C)
free(mem)
#else
munmap(mem, length)
#endif
Expand Down
2 changes: 1 addition & 1 deletion Sources/FoundationEssentials/Data/DataProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ extension DataProtocol {
extension DataProtocol where Self : ContiguousBytes {
public func copyBytes<DestinationType, R: RangeExpression>(to ptr: UnsafeMutableBufferPointer<DestinationType>, from range: R) where R.Bound == Index {
precondition(ptr.baseAddress != nil)

let concreteRange = range.relative(to: self)
withUnsafeBytes { fullBuffer in
let adv = distance(from: startIndex, to: concreteRange.lowerBound)
Expand Down
2 changes: 1 addition & 1 deletion Sources/FoundationEssentials/Date.swift
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ extension NSDate : _HasCustomAnyHashableRepresentation {
#endif // FOUNDATION_FRAMEWORK

// MARK: - Playground Support
#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension Date : _CustomPlaygroundQuickLookable {
var summary: String {
Expand Down
44 changes: 23 additions & 21 deletions Sources/FoundationEssentials/ErrorCodes+POSIX.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,7 @@
//
//===----------------------------------------------------------------------===//


#if FOUNDATION_FRAMEWORK
/// Describes an error in the POSIX error domain.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public struct POSIXError : _BridgedStoredNSError {
public let _nsError: NSError

public init(_nsError error: NSError) {
precondition(error.domain == NSPOSIXErrorDomain)
self._nsError = error
}

public static var errorDomain: String { return NSPOSIXErrorDomain }

public var hashValue: Int {
return _nsError.hashValue
}

public typealias Code = POSIXErrorCode
}
#else
#if !FOUNDATION_FRAMEWORK || canImport(C)
// Define the POSIXErrorCode for all platforms here.
public enum POSIXErrorCode : Int32 {
/// Operation not permitted.
Expand Down Expand Up @@ -366,6 +346,28 @@ public enum POSIXErrorCode : Int32 {

extension POSIXErrorCode : Equatable, Hashable, RawRepresentable {
}
#endif

#if FOUNDATION_FRAMEWORK
/// Describes an error in the POSIX error domain.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public struct POSIXError : _BridgedStoredNSError {
public let _nsError: NSError

public init(_nsError error: NSError) {
precondition(error.domain == NSPOSIXErrorDomain)
self._nsError = error
}

public static var errorDomain: String { return NSPOSIXErrorDomain }

public var hashValue: Int {
return _nsError.hashValue
}

public typealias Code = POSIXErrorCode
}
#else

/// Describes an error in the POSIX error domain.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
Expand Down
5 changes: 3 additions & 2 deletions Sources/FoundationEssentials/JSON/JSONDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ open class JSONDecoder {
/// Decode the `Date` as UNIX millisecond timestamp from a JSON number.
case millisecondsSince1970

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
// TODO: Reenable once DateFormatStyle has been moved: https://github.com/apple/swift-foundation/issues/46
/// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
Expand Down Expand Up @@ -647,7 +647,8 @@ extension JSONDecoderImpl: Decoder {
case .millisecondsSince1970:
let double = try self.unwrapFloatingPoint(from: mapValue, as: Double.self, for: codingPathNode, additionalKey)
return Date(timeIntervalSince1970: double / 1000.0)
#if FOUNDATION_FRAMEWORK // TODO: Reenable once DateFormatStyle has been moved
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
// TODO: Reenable once DateFormatStyle has been moved
case .iso8601:
let string = try self.unwrapString(from: mapValue, for: codingPathNode, additionalKey)
guard let date = try? Date.ISO8601FormatStyle().parse(string) else {
Expand Down
4 changes: 2 additions & 2 deletions Sources/FoundationEssentials/JSON/JSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ open class JSONEncoder {
/// Encode the `Date` as UNIX millisecond timestamp (as a JSON number).
case millisecondsSince1970

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
// TODO: Reenable once DateFormatStyle has been ported: https://github.com/apple/swift-foundation/issues/46
/// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
Expand Down Expand Up @@ -998,7 +998,7 @@ private extension __JSONEncoder {
case .millisecondsSince1970:
return try .number(from: 1000.0 * date.timeIntervalSince1970, with: .throw, for: codingPathNode, additionalKey)

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
case .iso8601:
return self.wrap(date.formatted(.iso8601))

Expand Down
2 changes: 1 addition & 1 deletion Sources/FoundationEssentials/JSON/JSONWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ internal struct JSONWriter {
pretty ? writer(" : ") : writer(":")
try serializeJSON(value, depth: depth)
}
#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_LOCALIZATION
if sortedKeys {
// TODO: Until we have a solution for sorting like Locale.system in FoundationEssentials or with the help of FoundationLocalization, this comparison requires bridging back to NSString. To avoid the extreme overhead of bridging the strings on every comparison, we'll do it up front instead.
let nsKeysAndValues = dict.map {
Expand Down
2 changes: 1 addition & 1 deletion Sources/FoundationEssentials/Locale/Locale+Language.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ extension Locale {

/// Returns a list of system languages, includes the languages of all product localization for the current platform
public static var systemLanguages: [Language] {
#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && canImport(FoundationICU)
NSLocale.systemLanguages().map {
let comp = Components(identifier: $0 as! String)
return Language(components: comp)
Expand Down
4 changes: 2 additions & 2 deletions Sources/FoundationEssentials/Locale/Locale.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public struct Locale : Hashable, Equatable, Sendable {
Locale(inner: LocaleCache.cache.system)
}

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && canImport(FoundationICU)
/// This returns an instance of `Locale` that's set up exactly like it would be if the user changed the current locale to that identifier, set the preferences keys in the overrides dictionary, then called `current`.
internal static func localeAsIfCurrent(name: String?, cfOverrides: CFDictionary? = nil, disableBundleMatching: Bool = false) -> Locale {
return LocaleCache.cache.localeAsIfCurrent(name: name, cfOverrides: cfOverrides, disableBundleMatching: disableBundleMatching)
Expand Down Expand Up @@ -483,7 +483,7 @@ public struct Locale : Hashable, Equatable, Sendable {
_locale.forceMinDaysInFirstWeek(calendar)
}

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
// This is framework-only because Date.FormatStyle.DateStyle is Internationalization-only.
package func customDateFormat(_ style: Date.FormatStyle.DateStyle) -> String? {
_locale.customDateFormat(style)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ internal final class _LocaleAutoupdating : _LocaleProtocol, @unchecked Sendable
LocaleCache.cache.current.forceTemperatureUnit
}

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
func customDateFormat(_ style: Date.FormatStyle.DateStyle) -> String? {
LocaleCache.cache.current.customDateFormat(style)
}
Expand Down
17 changes: 13 additions & 4 deletions Sources/FoundationEssentials/Locale/Locale_Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ struct LocaleCache : Sendable {

// _LocaleICU, if present. Otherwise we use _LocaleUnlocalized. The `Locale` initializers are not failable, so we just fall back to the unlocalized type when needed without failure.
static var localeICUClass: _LocaleProtocol.Type = {
#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && canImport(FoundationICU)
return _LocaleICU.self
#else
if let name = _typeByName("FoundationInternationalization._LocaleICU"), let t = name as? _LocaleProtocol.Type {
Expand Down Expand Up @@ -140,6 +140,7 @@ struct LocaleCache : Sendable {
}
}

#if canImport(FoundationICU)
mutating func fixedNSLocale(_ locale: _LocaleICU) -> _NSSwiftLocale {
let id = IdentifierAndPrefs(identifier: locale.identifier, prefs: locale.prefs)
if let locale = cachedFixedLocaleToNSLocales[id] {
Expand All @@ -152,6 +153,7 @@ struct LocaleCache : Sendable {
return nsLocale
}
}
#endif

mutating func currentNSLocale(preferences: LocalePreferences?, cache: Bool) -> _NSSwiftLocale? {
resetCurrentIfNeeded()
Expand All @@ -172,9 +174,14 @@ struct LocaleCache : Sendable {
return nil
}

#if canImport(FoundationICU)
// We have neither a Swift Locale nor an NSLocale. Recalculate and set both.
let locale = _LocaleICU(name: nil, prefs: preferences, disableBundleMatching: false)
#else
let locale = _LocaleUnlocalized(name: nil, prefs: preferences, disableBundleMatching: false)
#endif
let nsLocale = _NSSwiftLocale(Locale(inner: locale))

if cache {
// It's possible this was an 'incomplete locale', in which case we will want to calculate it again later.
self.cachedCurrentLocale = locale
Expand Down Expand Up @@ -281,9 +288,11 @@ struct LocaleCache : Sendable {
lock.withLock { $0.fixedNSLocale(identifier: id) }
}

#if canImport(FoundationICU)
func fixedNSLocale(_ locale: _LocaleICU) -> _NSSwiftLocale {
lock.withLock { $0.fixedNSLocale(locale) }
}
#endif

func autoupdatingCurrentNSLocale() -> _NSSwiftLocale {
lock.withLock { $0.autoupdatingNSLocale() }
Expand Down Expand Up @@ -319,7 +328,7 @@ struct LocaleCache : Sendable {
lock.withLock { $0.fixedComponents(comps) }
}

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_CFPREFERENCES
func preferences() -> (LocalePreferences, Bool) {
// On Darwin, we check the current user preferences for Locale values
var wouldDeadlock: DarwinBoolean = false
Expand Down Expand Up @@ -372,7 +381,7 @@ struct LocaleCache : Sendable {
}
#endif

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_CFPREFERENCES
/// This returns an instance of `Locale` that's set up exactly like it would be if the user changed the current locale to that identifier, set the preferences keys in the overrides dictionary, then called `current`.
func localeAsIfCurrent(name: String?, cfOverrides: CFDictionary? = nil, disableBundleMatching: Bool = false) -> Locale {

Expand All @@ -399,7 +408,7 @@ struct LocaleCache : Sendable {
}

func localeAsIfCurrentWithBundleLocalizations(_ availableLocalizations: [String], allowsMixedLocalizations: Bool) -> Locale? {
#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && canImport(FoundationICU)
guard !allowsMixedLocalizations else {
let (prefs, _) = preferences()
let inner = _LocaleICU(name: nil, prefs: prefs, disableBundleMatching: true)
Expand Down
12 changes: 8 additions & 4 deletions Sources/FoundationEssentials/Locale/Locale_Preferences.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ package struct LocalePreferences: Hashable {
// The OS no longer writes out this preference, but we keep it here for compatibility with CFDateFormatter behavior.
package var icuNumberFormatStrings: CFDictionary?
package var icuNumberSymbols: CFDictionary?
#if !NO_FORMATTERS
package var dateFormats: [Date.FormatStyle.DateStyle: String]? // Bridged version of `icuDateFormatStrings`
#endif
#endif
package var numberSymbols: [UInt32 : String]? // Bridged version of `icuNumberSymbols`

Expand All @@ -87,7 +89,7 @@ package struct LocalePreferences: Hashable {

package init() { }

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && canImport(FoundationICU)
// The framework init supports customized dateFormats
package init(metricUnits: Bool? = nil,
languages: [String]? = nil,
Expand Down Expand Up @@ -153,7 +155,7 @@ package struct LocalePreferences: Hashable {
}
#endif

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_CFPREFERENCES
/// Interpret a dictionary (from user defaults) according to a predefined set of strings and convert it into the more strongly-typed `LocalePreferences` values.
/// Several dictionaries may need to be applied to the same instance, which is why this is structured as a mutating setter rather than an initializer.
/// Why use a `CFDictionary` instead of a Swift dictionary here? The input prefs may be a complete copy of the user's prefs, and we don't want to bridge a ton of unrelated data into Swift just to extract a few keys. Keeping it as a `CFDictionary` avoids that overhead, and we call into small CF helper functions to get the data we need, if it is there.
Expand Down Expand Up @@ -284,15 +286,17 @@ package struct LocalePreferences: Hashable {
if let other = prefs.collationOrder { self.collationOrder = other }
if let other = prefs.firstWeekday { self.firstWeekday = other }
if let other = prefs.minDaysInFirstWeek { self.minDaysInFirstWeek = other }
if let other = prefs.numberSymbols { self.numberSymbols = other }
#if FOUNDATION_FRAMEWORK
if let other = prefs.icuDateTimeSymbols { self.icuDateTimeSymbols = other }
if let other = prefs.icuDateFormatStrings { self.icuDateFormatStrings = other }
if let other = prefs.icuTimeFormatStrings { self.icuTimeFormatStrings = other }
if let other = prefs.icuNumberFormatStrings { self.icuNumberFormatStrings = other }
if let other = prefs.icuNumberSymbols { self.icuNumberSymbols = other }
#if !NO_FORMATTERS
if let other = prefs.dateFormats { self.dateFormats = other }
#endif
if let other = prefs.numberSymbols { self.numberSymbols = other }
#endif // !NO_FORMATTERS
#endif // FOUNDATION_FRAMEWORK
if let other = prefs.country { self.country = other }
if let other = prefs.measurementUnits { self.measurementUnits = other }
if let other = prefs.temperatureUnit { self.temperatureUnit = other }
Expand Down
2 changes: 2 additions & 0 deletions Sources/FoundationEssentials/Locale/Locale_Protocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,11 @@ package protocol _LocaleProtocol : AnyObject, Sendable, CustomDebugStringConvert

func bridgeToNSLocale() -> NSLocale

#if !NO_FORMATTERS
// This is framework-only because Date.FormatStyle.DateStlye is Internationalization-only
func customDateFormat(_ style: Date.FormatStyle.DateStyle) -> String?
#endif
#endif
}

extension _LocaleProtocol {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ internal final class _LocaleUnlocalized : _LocaleProtocol, @unchecked Sendable {
nil
}

#if FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK && !NO_FORMATTERS
func customDateFormat(_ style: Date.FormatStyle.DateStyle) -> String? {
nil
}
Expand Down
12 changes: 9 additions & 3 deletions Sources/FoundationEssentials/Platform.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
#if canImport(Darwin)
import Darwin

fileprivate let _pageSize = Int(vm_page_size)
fileprivate var _pageSize: Int {
Int(vm_page_size)
}
#elseif canImport(WinSDK)
import WinSDK
fileprivate var _pageSize: Int {
Expand All @@ -23,13 +25,17 @@ fileprivate var _pageSize: Int {
#elseif os(WASI)
// WebAssembly defines a fixed page size
fileprivate let _pageSize: Int = 65_536
#else
#elseif canImport(Glibc)
import Glibc
fileprivate let _pageSize: Int = Int(getpagesize())
#elseif canImport(C)
fileprivate let _pageSize: Int = Int(getpagesize())
#endif // canImport(Darwin)

internal struct Platform {
static var pageSize: Int = _pageSize
static var pageSize: Int {
_pageSize
}

static func roundDownToMultipleOfPageSize(_ size: Int) -> Int {
return size & ~(self.pageSize - 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#if FOUNDATION_FRAMEWORK

#if canImport(ReflectionInternal)
@_implementationOnly
import ReflectionInternal

Expand Down Expand Up @@ -499,4 +500,5 @@ extension PredicateCodableConfiguration {
}()
}

#endif // canImport(ReflectionInternal)
#endif // FOUNDATION_FRAMEWORK
Loading