Commit Graph

217 Commits

Author SHA1 Message Date
David Smith
753a9408c2 ASCII fast paths for grapheme stride (#72064) 2024-03-04 22:03:58 -08:00
Alex Martini
7e58b81092 Call out time complexity of String.count.
This discussion borrows wording from the docs for the default
implementation of Collection.count[1], which are inherited by many other
symbols, but with a rewrite here because String doesn't guarantee
random-access performance (doesn't conform to RandomAccessCollection),
so accessing the count is never an O(1) operation.

1: https://developer.apple.com/documentation/swift/collection/count-4l4qk
2022-12-01 16:06:55 -08:00
Karoy Lorentey
50c2399a94 [stdlib] Work around binary compatibility issues with String index validation fixes in 5.7
Swift 5.7 added stronger index validation for `String`, so some illegal cases that previously triggered inconsistently diagnosed out of bounds accesses now result in reliable runtime errors. Similarly, attempts at applying an index originally vended by a UTF-8 string on a UTF-16 string now result in a reliable runtime error.

As is usually the case, new traps to the stdlib exposes code that contains previously undiagnosed / unreliably diagnosed coding issues.

Allow invalid code in binaries built with earlier versions of the stdlib to continue running with the 5.7 library by disabling some of the new traps based on the version of Swift the binary was built with.

In the case of an index encoding mismatch, allow transcoding of string storage regardless of the direction of the mismatch. (Previously we only allowed transcoding a UTF-8 string to UTF-16.)

rdar://93379333
2022-05-17 19:25:10 -07:00
Karoy Lorentey
c67f08b2af [stdlib][NFC] Remove obsolete note 2022-04-13 19:15:42 -07:00
Karoy Lorentey
67adcabefc Apply notes from code review 2022-04-10 00:14:43 -07:00
Karoy Lorentey
58ab3fea34 Apply suggestions from code review
Co-authored-by: Alejandro Alonso <alejandro_alonso@apple.com>
2022-04-10 00:14:43 -07:00
Karoy Lorentey
3c9968945e [stdlib] String: Implement happy paths for index validation 2022-04-10 00:14:43 -07:00
Karoy Lorentey
83df814c63 [stdlib] _StringObject.isKnownUTF16 → isForeignUTF8
This fixes a compatibility issue with potential future UTF-8 encoded
foreign String forms, as well as simplifying the code a bit — we no
longer need to do an availability check on inlinable fast paths.

The isForeignUTF8 bit is never set by any past or current stdlib
version, but it allows us to introduce UTF-8 encoded foreign forms
without breaking inlinable index encoding validation introduced in
Swift 5.7.
2022-04-09 21:33:53 -07:00
Karoy Lorentey
67f01a1159 [stdlib] Stop inlining String.subscript
`index(after:)`/`index(before:)` aren’t inlinable, so I don’t expect
force-inlining the subscript has much benefit.
2022-03-24 21:00:00 -07:00
Karoy Lorentey
1326c43b0f [stdlib][NFC] Update some outdated comments 2022-03-24 21:00:00 -07:00
Karoy Lorentey
0523b67e1f [stdlib] String.index(_:offsetBy:limitedBy:): compare limit against original index
Whether the limit actually applies depends on how it’s ordered
relative to the original index `i`, not the one we round down to the
nearest Character.
2022-03-24 21:00:00 -07:00
Karoy Lorentey
321284e9a9 [stdlib] Review & fix index validation during String index conversions
- Validate that the index has the same encoding as the string
- Validate that the index is within bounds
2022-03-24 21:00:00 -07:00
Karoy Lorentey
8ab2379946 [stdlib] Round indices down to nearest Character in String’s index algorithms
To prevent unaligned indices from breaking well-defined index distance
and index offset calculations, round every index down to the nearest
whole Character.

For the horrific details, see the forum discussion below.

https://forums.swift.org/t/string-index-unification-vs-bidirectionalcollection-requirements/55946

To avoid rounding from regressing String performance in the regular
case (when indices aren’t being passed across string views), introduce
a new String.Index flag bit that indicates that the index is already
Character aligned.
2022-03-24 21:00:00 -07:00
Karoy Lorentey
a44997eeea [stdlib] Factor scalar-aligned String index validation out into a set of common routines
There are three flavors, corresponding to i < endIndex, i <= endIndex, and range containment checks.
Additionally, we have separate variants for index validation in substrings.
2022-03-24 21:00:00 -07:00
Karoy Lorentey
15c7721caf [stdlib] Use the new index encoding flags when marking the encoding of indices
This removes an unnecessary opaque call from the inlinable path, but it preserves a runtime version check.
2022-03-24 20:59:59 -07:00
Karoy Lorentey
6e18955f90 [stdlib] Add bookkeeping to keep track of the encoding of strings and indices
Assign some previously reserved bits in String.Index and _StringObject to keep track of their associated storage encoding (either UTF-8 or UTF-16).

None of these bits will be reliably set in processes that load binaries compiled with older stdlib releases, but when they do end up getting set, we can use them opportunistically to more reliably detect cases where an index is applied on a string with a mismatching encoding.

As more and more code gets recompiled with 5.7+, the stdlib will gradually become able to detect such issues with complete accuracy.

Code that misuses indices this way was always considered broken; however, String wasn’t able to reliably detect these runtime errors before. Therefore, I expect there is a large amount of broken code out there that keeps using bridged Cocoa String indices (UTF-16) after a mutation turns them into native UTF-8 strings. Therefore, instead of trapping, this commit silently corrects the issue, transcoding the offsets into the correct encoding.

It would probably be a good idea to also emit a runtime warning in addition to recovering from the error. This would generate some noise that would gently nudge folks to fix their code.

rdar://89369680
2022-03-24 20:59:59 -07:00
Karoy Lorentey
683b9fa021 [stdlib] Adjust/fix String’s indexing operations to deal with the consequences of SE-0180 2022-03-24 20:59:59 -07:00
Karoy Lorentey
5b364c4e2b [stdlib] String.index(before:): Fix index validation issues
`String.index(before:)` (and methods that rely on it, such as `Substring.index(before:)`, `.distance(from:to:)` etc.) does not currently verify that the given index falls before the `endIndex` before aligning it to a scalar boundary. This allows an out-of-bounds memory access when the provided index points to a position beyond the end of `self`’s storage.

Additionally, the `i > startIndex` check needs to be done after scalar alignment, not before, as alignment can round the index down to `startIndex`.

rdar://89497074&89495373
2022-02-28 17:26:52 -08:00
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
Doug Gregor
9579390024 [SE-0304] Rename ConcurrentValue to Sendable 2021-03-18 22:48:20 -07:00
Doug Gregor
1a1f79c0de Introduce safety checkin for ConcurrentValue conformance.
Introduce checking of ConcurrentValue conformances:
- For structs, check that each stored property conforms to ConcurrentValue
- For enums, check that each associated value conforms to ConcurrentValue
- For classes, check that each stored property is immutable and conforms
  to ConcurrentValue

Because all of the stored properties / associated values need to be
visible for this check to work, limit ConcurrentValue conformances to
be in the same source file as the type definition.

This checking can be disabled by conforming to a new marker protocol,
UnsafeConcurrentValue, that refines ConcurrentValue.
UnsafeConcurrentValue otherwise his no specific meaning. This allows
both "I know what I'm doing" for types that manage concurrent access
themselves as well as enabling retroactive conformance, both of which
are fundamentally unsafe but also quite necessary.

The bulk of this change ended up being to the standard library, because
all conformances of standard library types to the ConcurrentValue
protocol needed to be sunk down into the standard library so they
would benefit from the checking above. There were numerous little
mistakes in the initial pass through the stsandard library types that
have now been corrected.
2021-02-04 03:45:09 -08:00
Michael Ilseman
e01a294da6 [stdlib] Introduce _invariantCheck_5_1 for 5.1 and later assertions.
Inlinable and non-inlinable code can cause 5.1 code to intermix with
5.0 code on older OSes. Some (weak) invariants for 5.1 should only be
checked when the OS's code is 5.1 or later, which is the purpose of
_invariantCheck_5_1.

Applied to String.Index._isScalarAligned, which is a new bit
introduced in 5.1 from one of the reserved bits from 5.0. The bit is
set when the index is proven to be scalar aligned, and we want to
assert on this liberally in contexts where we expect it to be
so. However, older OSes might not set this bit when doing scalar
aligning, depending on exactly what got inlined where/when.
2019-07-12 15:58:27 -07:00
Michael Ilseman
63a6794cf9 [String] Switch scalar-aligned bit to a reserved bit.
Since scalar-alignment is set in inlinable code, switch the alignment
bit to one of the previously-reserved bits rather than a grapheme
cache bit. Setting a grapheme cache bit in inlinable would break
backward deployment, as older versions would interpret it as a cached
value.

Also adjust the name to "scalar-aligned", which is clearer, and
removed assertion (which should be a real precondition).
2019-07-02 16:25:04 -07:00
Michael Ilseman
bd5a40ff1b [gardening] Add underscore to internal member 2019-06-27 11:11:44 -07:00
Michael Ilseman
4cd1e812b7 [String] Scalar-alignment bug fixes.
Fixes a general category (pun intended) of scalar-alignment bugs
surrounding exchanging non-scalar-aligned indices between views and
for slicing.

SE-0180 unifies the Index type of String and all its views and allows
non-scalar-aligned indices to be used across views. In order to
guarantee behavior, we often have to check and perform scalar
alignment. To speed up these checks, we allocate a bit denoting
known-to-be-aligned, so that the alignment check can skip the
load. The below shows what views need to check for alignment before
they can operate, and whether the indices they produce are aligned.

┌───────────────╥────────────────────┬──────────────────────────┐
│ View          ║ Requires Alignment │ Produces Aligned Indices │
╞═══════════════╬════════════════════╪══════════════════════════╡
│ Native UTF8   ║ no                 │ no                       │
├───────────────╫────────────────────┼──────────────────────────┤
│ Native UTF16  ║ yes                │ no                       │
╞═══════════════╬════════════════════╪══════════════════════════╡
│ Foreign UTF8  ║ yes                │ no                       │
├───────────────╫────────────────────┼──────────────────────────┤
│ Foreign UTF16 ║ no                 │ no                       │
╞═══════════════╬════════════════════╪══════════════════════════╡
│ UnicodeScalar ║ yes                │ yes                      │
├───────────────╫────────────────────┼──────────────────────────┤
│ Character     ║ yes                │ yes                      │
└───────────────╨────────────────────┴──────────────────────────┘

The "requires alignment" applies to any operation taking a
String.Index that's not defined entirely in terms of other operations
taking a String.Index. These include:

* index(after:)
* index(before:)
* subscript
* distance(from:to:) (since `to` is compared against directly)
* UTF16View._nativeGetOffset(for:)
2019-06-26 16:42:58 -07:00
Ben Cohen
e9d4687e31 De-underscore @frozen, apply it to structs (#24185)
* De-underscore @frozen for enums

* Add @frozen for structs, deprecate @_fixed_layout for them

* Switch usage from _fixed_layout to frozen
2019-05-30 17:55:37 -07:00
Michael Ilseman
f7cdda2720 [gardening] Clean up many String computed vars 2019-04-08 15:16:48 -07:00
Michael Ilseman
415cc8fb0c [String.Index] Deprecate encodedOffset var/init
String.Index has an encodedOffset-based initializer and computed
property that exists for serialization purposes. It was documented as
UTF-16 in the SE proposal introducing it, which was String's
underlying encoding at the time, but the dream of String even then was
to abstract away whatever encoding happend to be used.

Serialization needs an explicit encoding for serialized indices to
make sense: the offsets need to align with the view. With String
utilizing UTF-8 encoding for native contents in Swift 5, serialization
isn't necessarily the most efficient in UTF-16.

Furthermore, the majority of usage of encodedOffset in the wild is
buggy and operates under the assumption that a UTF-16 code unit was a
Swift Character, which isn't even valid if the String is known to be
all-ASCII (because CR-LF).

This change introduces a pair of semantics-preserving alternatives to
encodedOffset that explicitly call out the UTF-16 assumption. These
serve as a gentle off-ramp for current mis-uses of encodedOffset.
2019-02-13 18:42:40 -08:00
Michael Ilseman
b01ee7267a [String] Custom iterator for UTF16View (#20929)
Defining a custom iterator for the UTF16View avoid some redundant
computation over the indexing model. This speeds up iteration by
around 40% on non-ASCII strings.
2018-12-01 09:35:27 -08:00
Michael Ilseman
034f76d10b [String] Remove some unneeded inlinable annotations 2018-11-15 09:43:34 -08:00
Maxim Moiseev
cbf83ac04f [NFC][stdlib] Add FIXME markers to simplify audit 2018-11-14 11:58:42 -08:00
Slava Pestov
f6c2caf64b stdlib: Add @inlinable to @inline(__always) declarations
These should be audited since some might not actually need to be
@inlinable, but for now:

- Anything public and @inline(__always) is now also @inlinable
- Anything @usableFromInline and @inline(__always) is now @inlinable
2018-11-13 15:15:07 -05:00
Michael Ilseman
75943350d2 [String] Give String a custom iterator
Gives us modest wins on complex grapheme strings, but up to 40% on
heavy-ASCII strings.
2018-11-08 18:25:01 -08:00
Michael Ilseman
948655e850 [String] Cleanups, comments, documentation
After rebasing on master and incorporating more 32-bit support,
perform a bunch of cleanup, documentation updates, comments, move code
back to String declaration, etc.
2018-11-04 10:42:42 -08:00
Michael Ilseman
7aea40680d [String] NFC iterator fast-paths
Refactor and rename _StringGutsSlice, apply NFC-aware fast paths to a
new buffered iterator.

Also, fix bug in _typeName which used to assume ASCIIness and better
SIL optimizations on StringObject.
2018-11-04 10:42:41 -08:00
Michael Ilseman
a0e639eaf5 [String] Grapheme breaking fast-paths
Add in our scalar-based fast-paths for UTF-8 and foreign strings, and
update the grapheme cache.
2018-11-04 10:42:40 -08:00
Michael Ilseman
fe7c3ce2e4 [String] Refactorings and cleanup
* Refactor out RRC implementation into dedicated file.

* Change our `_invariantCheck` pattern to generate efficient code in
  asserts builds and make the optimizer job's easier.

* Drop a few Bidi shims we no longer need.

* Restore View decls to String, workaround no longer needed

* Cleaner unicode helper facilities
2018-11-04 10:42:40 -08:00
Michael Ilseman
f23a3c19b8 [String] Bounds checking and Index cleanup 2018-11-04 10:42:40 -08:00
Michael Ilseman
89d18e1a3a [String] Refactor helper code into UnicodeHelpers.swift.
Clean up some of the index assumptions, stick index-aware methods on
_StringGuts, and otherwise migrate code over to UnicodeHelpers.swift.
2018-11-04 10:42:40 -08:00
Michael Ilseman
4ab45dfe20 [String] Drop in initial UTF-8 String prototype
This is a giant squashing of a lot of individual changes prototyping a
switch of String in Swift 5 to be natively encoded as UTF-8. It
includes what's necessary for a functional prototype, dropping some
history, but still leaves plenty of history available for future
commits.

My apologies to anyone trying to do code archeology between this
commit and the one prior. This was the lesser of evils.
2018-11-04 10:42:40 -08:00
Michael Ilseman
463e3747a8 [gardening] Factor out String bidi conformance
Add StringCharacterView.swift for String's bidi conformance. NFC.
2018-07-25 14:14:37 -07:00
Ben Cohen
a4230ab2ad [stdlib] Update stdlib to 4.0 and reorganize compatibility shims (#17580)
* Update stdlib to 4.0 and move all compatibility shims into a dedicated source file
2018-06-29 06:26:52 -07:00
Ben Cohen
a51cc89b11 Replace _CharacterView with a typealias (#17472) 2018-06-25 13:22:09 -07:00
Karoy Lorentey
23c630ac92 [stdlib] Add @usableFromInline to internal typealiases that need it
This fixes 3659 warnings in the standard library.
2018-06-18 16:34:19 +01:00
Michael Ilseman
3ee17102ed [String.Index] Restore compound offsets.
Move the shifts to index creation time rather than index comparison
time. This seems to benefit micro benchmarks and cover up
inefficiencies in our generic index distance calculations.
2018-05-25 09:54:35 -07:00
Michael Ilseman
614016fecd [String.Index] Simplify and prepare for more resilience.
Simplify String.Index by sinking transcoded offsets into the .utf8
variant. This is in preparation for a more resilient index type
capable of supporting existential string indices.
2018-05-24 14:47:04 -07:00
Michael Ilseman
4a368ab46c [string] Drop many @inlinable from big API.
Drop append-related @inlinable annotations for String, StringGuts,
StringStorage, and the Views. Drop several for larger operations, such
as case conversion. Drop as many as we can from StringGuts for now.
2018-05-13 07:38:55 -07:00
Nate Cook
58933d88c5 [stdlib] Rename index(...) methods to firstIndex(...)
A la SE-204.
2018-04-21 18:07:25 -05:00
Slava Pestov
2e5aef9c8d stdlib: Remove redundant @usableFromInline attributes 2018-04-06 00:02:30 -07:00
Slava Pestov
e1f50b2d36 SE-0193: Rename @_inlineable to @inlinable, @_versioned to @usableFromInline 2018-03-30 21:55:30 -07:00