Commit Graph

6693 Commits

Author SHA1 Message Date
Karoy Lorentey
626582ce5f [stdlib] Mark String.IndexDistance as deprecated and stop mentioning it in method signatures
`IndexDistance` is an artifact of ancient history — it used to be an associated type of Collection in the Swift 3 era. The Collection requirement got replaced with a deprecated typealias of Int in Swift 4, the same release that re-introduced the Collection conformance for String.

However, the typealias declaration for String.IndexDistance has fallen through the cracks. It was accidentally left un-deprecated and it’s still actively mentioned in String API declarations to this day. (These usages leak into the API docs, which can be a source of unnecessary confusion.)

Let’s put an end to this and add the missing deprecation attribute, replacing `IndexDistance` usages with `Int`.

While we’re here, also bring `String.index(_:offsetBy:)` and `String.index(_:offsetBy:limitedBy:)` in sync with their declarations in Collection by renaming the second argument from `n` to `distance`.

(These method declaration changes do get emitted into .swiftinterface files, but they aren’t breaking any client code — the argument names are only relevant to the docs (and the method implementation). They do not affect callers of these functions.)
2022-02-25 17:32:04 -08:00
Karoy Lorentey
5293bde558 [stdlib] Collection: simplify default _failEarlyRangeCheck implementations
Currently, the default implementations of the various `_failEarlyRangeCheck` forms contain several _precondition invocations, like this:

```
@inlinable
  public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
    _precondition(
      bounds.lowerBound <= index,
      "Out of bounds: index < startIndex")
    _precondition(
      index < bounds.upperBound,
      "Out of bounds: index >= endIndex")
  }
```

Each such precondition call generates a separate trap instruction, which seems like a waste — theoretically it would be helpful to know which condition was violated, but in practice, that information tends not to be surfaced anyway. Combining these will lead to a minuscule code size improvement.

(The separate messages do surface these in debug builds, but only if these generic defaults actually execute, which isn’t often. These are not public entry points, so concrete collection types tend ignore these and roll their own custom index validation instead. From what I’ve seen, custom code tends to combine the upper/lower checks into a single precondition check. These underscored requirements tend to be only called by the standard `Slice`; and it seems reasonable for that to follow suit.)

More interestingly, the range-in-range version of `_failEarlyRangeCheck` performs two times as many checks than are necessary:

```
  @inlinable
  public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
    _precondition(
      bounds.lowerBound <= range.lowerBound,
      "Out of bounds: range begins before startIndex")
    _precondition(
      range.lowerBound <= bounds.upperBound,
      "Out of bounds: range ends after endIndex")
    _precondition(
      bounds.lowerBound <= range.upperBound,
      "Out of bounds: range ends before bounds.lowerBound")
    _precondition(
      range.upperBound <= bounds.upperBound,
      "Out of bounds: range begins after bounds.upperBound")
  }
```

It is safe to assume that `range.lowerBound <= range.upperBound`, so it’s enough to test that `bounds.lowerBound <= range.lowerBound && range.upperBound <= bounds.upperBound` — we don’t need to check each combination separately.
2022-02-25 17:06:08 -08:00
Guillaume Lessard
758cdaebb0 Merge branch 'main' into se-pointer-convenience 2022-02-25 13:52:45 -07:00
Guillaume Lessard
bb05e851af [stdlib] restrict pointer arithmetic to UInt 2022-02-25 13:35:20 -07:00
Guillaume Lessard
d80a50bda0 [stdlib] comparisons for heterogeneous pointer types 2022-02-25 13:34:23 -07:00
Guillaume Lessard
5c10c67a01 [stdlib] pointer(to property:) for UP and UMP 2022-02-25 13:34:23 -07:00
Guillaume Lessard
b3f96e8cea [stdlib] alignedUp(for:) and siblings for URP and UMRP 2022-02-25 13:34:23 -07:00
swift_jenkins
9013f5dd6e Merge remote-tracking branch 'origin/main' into next 2022-02-25 07:00:37 -08:00
Guillaume Lessard
9ead7d039d [stdlib] relax stride check in UnsafePointer.withMemoryRebound (#41553)
* [stdlib] relax stride check

- The stride check in `UnsafePointer.withMemoryRebound` makes less sense when rebinding memory for a single element.
- This skips the stride-matching portion of the `_debugPrecondition` in `withMemoryRebound` when `count == 1`.

* [test] UnsafePointer.withMemoryRebound with capacity 1
2022-02-25 09:54:32 -05:00
Guillaume Lessard
82fa4b0ea8 [stdlib] relax stride check
- The stride check in `UnsafePointer.withMemoryRebound` makes less sense when rebinding memory for a single element.
- This skips the stride-matching portion of the `_debugPrecondition` in `withMemoryRebound` when `count == 1`.
2022-02-24 18:57:51 -07:00
swift_jenkins
945cea69fc Merge remote-tracking branch 'origin/main' into next 2022-02-23 05:20:33 -08:00
Luciano Almeida
1218d7fee8 Merge pull request #41489 from LucianoPAlmeida/minor-nfc-warnings
[NFC] Fixing some stdlib unused warnings
2022-02-23 10:17:43 -03:00
swift_jenkins
c3aa3da6b1 Merge remote-tracking branch 'origin/main' into next 2022-02-22 18:20:41 -08:00
Karoy Lorentey
d384a796eb Merge pull request #41512 from lorentey/clock-fixes
[stdlib] Some more clock adjustments
2022-02-22 18:13:35 -08:00
Karoy Lorentey
ea10e15829 [stdlib] Duration: use optimized methods for multiplication/division by constants 2022-02-22 02:32:02 -08:00
Karoy Lorentey
524f499a0e [stdlib] Duration: match parameter order in direct initializer with _Int128 2022-02-22 02:32:01 -08:00
Karoy Lorentey
c00322d513 [stdlib] Int128: Add direct multiplication by a single UInt64 value 2022-02-22 02:26:57 -08:00
Karoy Lorentey
2cc1e2aecc [stdlib] Int128: Add direct division by some constant powers of ten 2022-02-22 02:25:31 -08:00
Karoy Lorentey
b963f7ce1d [stdlib] Int128: Fix thinko in _wideDivide22 2022-02-22 02:22:43 -08:00
swift_jenkins
dedc417e68 Merge remote-tracking branch 'origin/main' into next 2022-02-21 21:00:42 -08:00
Karoy Lorentey
0704746bfa Merge pull request #41445 from lorentey/unconditional-debugPrecondition
[stdlib] Add build option to enable _debugPrecondition in Release mode
2022-02-21 20:59:22 -08:00
Karoy Lorentey
b3016c9615 Merge pull request #41485 from lorentey/clock-fixes
[stdlib] Fix some Clock issues
2022-02-21 20:59:03 -08:00
swift_jenkins
3a2b931e5f Merge remote-tracking branch 'origin/main' into next 2022-02-21 17:00:42 -08:00
Karoy Lorentey
b7cae85482 [stdlib] Leave [U]Int128.~ disabled for now 2022-02-21 12:26:21 -08:00
LucianoAlmeida
09bf4cb6d1 [NFC] Fixing some stdlib unused warnings 2022-02-20 18:18:35 -03:00
Karoy Lorentey
1da0bb8f2e [stdlib] Int128: Fix Words; simplify/tweak some operations
`Words.Iterator.next()` used to call `Int128(truncatingIfNeeded:)`, which in turn iterates over words, leading to an infinite recursion.

Implement half-width multiplication from scratch instead of masking off the full width results.
2022-02-19 18:43:32 -08:00
Karoy Lorentey
890a7f25e8 [stdlib] Duration: add an initializer that takes low/high components
Having a direct initializer in the ABI is critically important — otherwise we wouldn’t be able to add back deployable conversion initializers in the future (without going through unnecessary overhead).
2022-02-19 18:43:32 -08:00
Saagar Jha
bb499b2dcf [stdlib] Fix comment on _forEachFieldWithKeyPath
The description for the body block appears to have been copied from
_forEachField without modification, even though the type signature
differs.
2022-02-19 00:59:47 -08:00
Karoy Lorentey
2643e8dcf3 [stdlib] Add build option to enable _debugPrecondition in Release mode
It is sometimes desirable to always perform (relatively cheap) runtime checks in the stdlib, even in configurations where we’d otherwise elide them.

Add a build-time option to the standard library (`SWIFT_STDLIB_ENABLE_DEBUG_PRECONDITIONS_IN_RELEASE`) to make `_debugPrecondition` work like `_precondition`, i.e., to enable it even in ReleaseAssert configurations.

This option will keep additional checks in the following places, even in release mode:

- Range checking in the subscript operations of all unsafe buffer pointer types.
- Nil checking in `Optional.unsafelyUnwrapped`
- Additional argument validation in `Unsafe[Mutable][Raw]Pointer`’s initialization/assignment/move/deinitialization/binding methods
- Protection against initializing `Unsafe[Mutable][Raw]Pointer` with invalid data. (Negative count, nil pointer for non-empty buffer, etc)
- Checks against index overflow in `Unsafe[Mutable]BufferPointer`’s index manipulation methods
- Checks against backward ranges in `Range(uncheckedBounds:)`, `ClosedRange(uncheckedBounds:)`
- Dynamic isa check in `unsafeDowncast(_:to:)`
- Additional [cheap] checks to catch invalid Sequence/Collection implementations in `Array.init<S:Sequence>(_:)` and elsewhere
- Checks against `Character` containing multiple grapheme clusters
- More index validation in `EmptyCollection`

(Additional cases will get added as the stdlib evolves.)

The option is disabled by default — so `_debugPrecondition`s continue to be disabled in optimized builds, even after this change lands, unless someone specifically builds a stdlib that enables them.

rdar://89118585
2022-02-18 21:53:23 -08:00
swift_jenkins
4759690b43 Merge remote-tracking branch 'origin/main' into next 2022-02-17 21:40:49 -08:00
Slava Pestov
c0adf40758 stdlib: Move Generator and _Element typealiases to Sequence and Collection protocols
The requirement machine does not allow 'where' clauses to reference
typealiases defined in protocol extensions.

These should probably be removed entirely since they're not useful
anymore, but I'd rather that decision was made by the stdlib folks.
2022-02-17 19:40:58 -05:00
swift_jenkins
6887dfcca4 Merge remote-tracking branch 'origin/main' into next 2022-02-17 10:01:03 -08:00
Arnold Schwaighofer
62ec31a462 Merge pull request #41338 from aschwaighofer/reuse_contiguous_array_storage_metadata
Reuse `_ContiguousArrayStorage<AnyObject>` metadata for any class or objc generic type
2022-02-17 12:47:23 -05:00
swift_jenkins
f649deeafd Merge remote-tracking branch 'origin/main' into next 2022-02-17 09:41:05 -08:00
Philippe Hausler
e675b310f8 [SE-0329] Clock/Instant/Duration (#40609)
* [WIP] Initial draft at v2 Clock/Instant/Duration

* Ensure the literal types for _DoubleWide are able to be at least 64 bits on 32 bit platforms

* static cast timespec members to long

* Remove runtime exports from clock functions

* Export clock functions in implementations as they are in headers

* Clean up internal properties by adding leading underscores, refine availability to a TBD marker macro, and break at 80 lines to match style

* Shift operators to concrete Instant types to avoid complexity in solver resolution

* Adjust diagnostic note and error expectation of ambiguities to reflect new potential solver (perhaps incorrect) solutions

* Update stdlib/public/Concurrency/TaskSleep.swift

Co-authored-by: Karoy Lorentey <klorentey@apple.com>

* [stdlib][NFC] Remove trailing whitespace

* [stdlib] Remove _DoubleWidth from stdlib's ABI

* [stdlib] Strip downd _DoubleWidth to _[U]Int128

* Additional adjustments to diagnostic notes and errors expectation of ambiguities to reflect new potential solver (perhaps incorrect) solutions

* Disable type checker performance validation for operator overload inferences (rdar://33958047)

* Decorate Duration, DurationProtocol, Instant and clocks with @available(SwiftStdlib 9999, *)

* Restore diagnostic ambiguity test assertion (due to availability)

* Add a rough attempt at implementing time accessors on win32

* Remove unused clock id, rename SPI for swift clock ids and correct a few more missing availabilities

* remove obsolete case of realtime clock for dispatch after callout

* Use the default implementation of ~ for Int128 and UInt128

* Ensure diagnostic ambiguitiy applies evenly to all platforms and their resolved types

* Restore the simd vector build modifications (merge damage)

* Update to latest naming results for Instant.Duration

* Updates to latest proposal initializers and accessors and adjust encoding/decoding to string based serialization

* Update availability for Clock/Instant/Duration methods and types to be 5.7

* Correct *Clock.now to report via the correct runtime API

* Ensure the hashing of Duration is based upon the attoseconds hashing

* Avoid string based encoding and resort back to high and low bit encoding/decoding but as unkeyed

* Adjust naming of component initializer to use suffixes on parameters

* Duration decoding should use a mutable container for decoding

* fix up components initializer and decode access

* Add platform base initializers for timespec and tiemval to and from Duration

* Add some first draft documentation for standard library types Duration, DurationProtocol and InstantProtocol

* Another round of documentation prose and some drive-by availability fixes

* InstantProtocol availability should be 5.7

* Correct linux timeval creation to be Int and not Int32

Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2022-02-17 09:32:46 -08:00
Arnold Schwaighofer
9f2b6a4ebb Reuse _ContiguousArrayStorage<AnyObject> metadata for any class or objc generic type
Reduces the number of _ContiguousArrayStorage metadata.

In order to support constant time bridging we do need to set the correct
metadata when we bridge to Objective-C. This is so that the type check
succeeds when bridging back from Objective-C to reuse the storage
instance rather than bridging the elements.

To support dynamically setting the `_ContiguousArrayStorage` element
type i needed to add support for optimizing `alloc_ref_dynamic`
throughout the optimizer.

Possible future improvements:
* Use different metadata such that we can disambiguate native Swift
  classes during destruction -- allowing native release rather then unknown
  release usage.
* Optimize the newly added semantic function
  getContiguousArrayStorageType

rdar://86171143
2022-02-16 07:55:34 -08:00
Alejandro Alonso
657c17fa39 Setup grapheme breaking tests 2022-02-15 17:16:36 -08:00
Alex Martini
fa04ef570d Add missing parameter in doc comment.
This text matches what's in the doc comment for
UnsafeMutableRawPointer.storeBytes(of:toByteOffset:as:)

Fixes rdar://88982081
2022-02-15 16:49:07 -08:00
Alejandro Alonso
c0e1ef01f9 Fix backwards count of Indic graphemes 2022-02-15 15:28:37 -08:00
swift_jenkins
b773d1408b Merge remote-tracking branch 'origin/main' into next 2022-02-14 14:41:02 -08:00
Guillaume Lessard
d870a9f164 Merge pull request #41288 from glessard/sr15433
[stdlib] Implement `withContiguousStorageIfAvailable` for raw buffer types
2022-02-14 15:37:27 -07:00
Alex Martini
9bc7b8ea99 Add missing comma & slightly clarify. 2022-02-11 11:48:07 -08:00
swift_jenkins
ea7813436f Merge remote-tracking branch 'origin/main' into next 2022-02-09 17:41:37 -08:00
Alex Martini
6dcd9b27b9 Merge pull request #40529 from amartini51/array_slice_end_76254761
Fix mentions of nonexistent 'end' parameter.
2022-02-09 17:32:03 -08:00
swift_jenkins
ed58ee8712 Merge remote-tracking branch 'origin/main' into next 2022-02-09 05:41:20 -08:00
Kuba (Brecka) Mracek
2fa79689fa Turn build-swift-stdlib-static-print on for freestanding preset (#41260) 2022-02-09 05:41:04 -08:00
Guillaume Lessard
441e3ce4e3 [stdlib] add withContiguousStorageIfAvailable for raw buffers 2022-02-08 18:05:02 -07:00
swift_jenkins
a18da6ac61 Merge remote-tracking branch 'origin/main' into next 2022-02-08 17:03:22 -08:00
Guillaume Lessard
8552044dc5 Merge pull request #40828 from glessard/sort-optimization
[nfc] document legacy ABI in the implementation of sort
2022-02-08 16:17:05 -07:00
swift_jenkins
265e609bbe Merge remote-tracking branch 'origin/main' into next 2022-02-08 10:21:25 -08:00