mirror of
https://github.com/apple/swift.git
synced 2025-12-21 12:14:44 +01:00
* [CodeCompletion] Restrict ancestor search to brace
This change allows ExprParentFinder to restrict certain searches for parents to just AST nodes within the nearest surrounding BraceStmt. In the string interpolation rework, BraceStmts can appear in new places in the AST; this keeps code completion from looking at irrelevant context.
NFC in this commit, but keeps code completion from crashing once TapExpr is introduced.
* Remove test relying on ExpressibleByStringInterpolation being deprecated
Since soon enough, it won’t be anymore.
* [AST] Introduce TapExpr
TapExpr allows a block of code to to be inserted between two expressions, accessing and potentially mutating the result of its subexpression before giving it to its parent expression. It’s roughly equivalent to this function:
func _tap<T>(_ value: T, do body: (inout T) throws -> Void) rethrows -> T {
var copy = value
try body(©)
return copy
}
Except that it doesn’t use a closure, so no variables are captured and no call frame is (even notionally) added.
This commit does not include tests because nothing in it actually uses TapExpr yet. It will be used by string interpolation.
* SE-0228: Fix ExpressibleByStringInterpolation
This is the bulk of the implementation of the string interpolation rework. It includes a redesigned AST node, new parsing logic, new constraints and post-typechecking code generation, and new standard library types and members.
* [Sema] Rip out typeCheckExpressionShallow()
With new string interpolation in place, it is no longer used by anything in the compiler.
* [Sema] Diagnose invalid StringInterpolationProtocols
StringInterpolationProtocol informally requires conforming types to provide at least one method with the base name “appendInterpolation” with no (or a discardable) return value and visibility at least as broad as the conforming type’s. This change diagnoses an error when a conforming type does not have a method that meets those criteria.
* [Stdlib] Fix map(String.init) source break
Some users, including some in the source compatibility suite, accidentally used init(stringInterpolationSegment:) by writing code like `map(String.init)`. Now that these intializers have been removed, the remaining initializers often end up tying during overload resolution. This change adds several overloads of `String.init(describing:)` which will break these ties in cases where the compiler previously selected `String.init(stringInterpolationSegment:)`.
* [Sema] Make callWitness() take non-mutable arrays
It doesn’t actually need to mutate them.
* [Stdlib] Improve floating-point interpolation performance
This change avoids constructing a String when interpolating a Float, Double, or Float80. Instead, we write the characters to a fixed-size buffer and then append them directly to the string’s storage.
This seems to improve performance for all three types, but especially for Double and Float80, which cannot always fit into a small string when stringified.
* [NameLookup] Improve MemberLookupTable invalidation
In rare cases usually involving generated code, an overload added by an extension in the middle of a file would not be visible below it if the type had lazy members and the same base name had already been referenced above the extension. This change essentially dirties a type’s member lookup table whenever an extension is added to it, ensuring the entries in it will be updated.
This change also includes some debugging improvements for NameLookup.
* [SILOptimizer] XFAIL dead object removal failure
The DeadObjectRemoval pass in SILOptimizer does not currently remove reworked string interpolations as well as the old design because their effects cannot be described by @_effects(readonly). That causes a test failure on Linux. This change temporarily silences that test. The SILOptimizer issue has been filed as SR-9008.
* Confess string interpolation’s source stability sins
* [Parser] Parse empty interpolations
Previously, the parser had an odd asymmetry which caused the same function to accept foo(), but reject “\()”. This change fixes the issue.
Already tested by test/Parse/try.swift, which uses this construct in one of its throwing interpolation tests.
* [Sema] Fix batch-mode-only lazy var bug
The temporary variable used by string interpolation needs to be recontextualized when it’s inserted into a synthesized getter. Fixes a compilation failure in Alamofire.
I’ll probably follow up on this bug a bit more after merging.
260 lines
9.8 KiB
Swift
260 lines
9.8 KiB
Swift
//===--- StringInterpolation.swift - String Interpolation -----------------===//
|
|
//
|
|
// This source file is part of the Swift.org open source project
|
|
//
|
|
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
//
|
|
// See https://swift.org/LICENSE.txt for license information
|
|
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
/// Represents a string literal with interpolations while it is being built up.
|
|
///
|
|
/// Do not create an instance of this type directly. It is used by the compiler
|
|
/// when you create a string using string interpolation. Instead, use string
|
|
/// interpolation to create a new string by including values, literals,
|
|
/// variables, or expressions enclosed in parentheses, prefixed by a
|
|
/// backslash (`\(`...`)`).
|
|
///
|
|
/// let price = 2
|
|
/// let number = 3
|
|
/// let message = """
|
|
/// If one cookie costs \(price) dollars, \
|
|
/// \(number) cookies cost \(price * number) dollars.
|
|
/// """
|
|
/// print(message)
|
|
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
|
|
///
|
|
/// When implementing an `ExpressibleByStringInterpolation` conformance,
|
|
/// set the `StringInterpolation` associated type to
|
|
/// `DefaultStringInterpolation` to get the same interpolation behavior as
|
|
/// Swift's built-in `String` type and construct a `String` with the results.
|
|
/// If you don't want the default behavior or don't want to construct a
|
|
/// `String`, use a custom type conforming to `StringInterpolationProtocol`
|
|
/// instead.
|
|
///
|
|
/// Extending default string interpolation behavior
|
|
/// ===============================================
|
|
///
|
|
/// Code outside the standard library can extend string interpolation on
|
|
/// `String` and many other common types by extending
|
|
/// `DefaultStringInterpolation` and adding an `appendInterpolation(...)`
|
|
/// method. For example:
|
|
///
|
|
/// extension DefaultStringInterpolation {
|
|
/// fileprivate mutating func appendInterpolation(
|
|
/// escaped value: String, asASCII forceASCII: Bool = false) {
|
|
/// for char in value.unicodeScalars {
|
|
/// appendInterpolation(char.escaped(asASCII: forceASCII)
|
|
/// }
|
|
/// }
|
|
/// }
|
|
///
|
|
/// print("Escaped string: \(escaped: string)")
|
|
///
|
|
/// See `StringInterpolationProtocol` for details on `appendInterpolation`
|
|
/// methods.
|
|
///
|
|
/// `DefaultStringInterpolation` extensions should add only `mutating` members
|
|
/// and should not copy `self` or capture it in an escaping closure.
|
|
@_fixed_layout
|
|
public struct DefaultStringInterpolation: StringInterpolationProtocol {
|
|
/// The string contents accumulated by this instance.
|
|
@usableFromInline
|
|
internal var _storage: String
|
|
|
|
/// Creates a string interpolation with storage pre-sized for a literal
|
|
/// with the indicated attributes.
|
|
///
|
|
/// Do not call this initializer directly. It is used by the compiler when
|
|
/// interpreting string interpolations.
|
|
@inlinable
|
|
public init(literalCapacity: Int, interpolationCount: Int) {
|
|
let capacityPerInterpolation = 2
|
|
let initialCapacity = literalCapacity +
|
|
interpolationCount * capacityPerInterpolation
|
|
_storage = String(_StringGuts(_initialCapacity: initialCapacity))
|
|
}
|
|
|
|
/// Appends a literal segment of a string interpolation.
|
|
///
|
|
/// Do not call this method directly. It is used by the compiler when
|
|
/// interpreting string interpolations.
|
|
@inlinable
|
|
public mutating func appendLiteral(_ literal: String) {
|
|
literal.write(to: &self)
|
|
}
|
|
|
|
/// Interpolates the given value's textual representation into the
|
|
/// string literal being created.
|
|
///
|
|
/// Do not call this method directly. It is used by the compiler when
|
|
/// interpreting string interpolations. Instead, use string
|
|
/// interpolation to create a new string by including values, literals,
|
|
/// variables, or expressions enclosed in parentheses, prefixed by a
|
|
/// backslash (`\(`...`)`).
|
|
///
|
|
/// let price = 2
|
|
/// let number = 3
|
|
/// let message = """
|
|
/// If one cookie costs \(price) dollars, \
|
|
/// \(number) cookies cost \(price * number) dollars.
|
|
/// """
|
|
/// print(message)
|
|
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
|
|
@inlinable
|
|
public mutating func appendInterpolation<T>(_ value: T)
|
|
where T: TextOutputStreamable, T: CustomStringConvertible
|
|
{
|
|
value.write(to: &self)
|
|
}
|
|
|
|
/// Interpolates the given value's textual representation into the
|
|
/// string literal being created.
|
|
///
|
|
/// Do not call this method directly. It is used by the compiler when
|
|
/// interpreting string interpolations. Instead, use string
|
|
/// interpolation to create a new string by including values, literals,
|
|
/// variables, or expressions enclosed in parentheses, prefixed by a
|
|
/// backslash (`\(`...`)`).
|
|
///
|
|
/// let price = 2
|
|
/// let number = 3
|
|
/// let message = "If one cookie costs \(price) dollars, " +
|
|
/// "\(number) cookies cost \(price * number) dollars."
|
|
/// print(message)
|
|
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
|
|
@inlinable
|
|
public mutating func appendInterpolation<T>(_ value: T)
|
|
where T: TextOutputStreamable
|
|
{
|
|
value.write(to: &self)
|
|
}
|
|
|
|
/// Interpolates the given value's textual representation into the
|
|
/// string literal being created.
|
|
///
|
|
/// Do not call this method directly. It is used by the compiler when
|
|
/// interpreting string interpolations. Instead, use string
|
|
/// interpolation to create a new string by including values, literals,
|
|
/// variables, or expressions enclosed in parentheses, prefixed by a
|
|
/// backslash (`\(`...`)`).
|
|
///
|
|
/// let price = 2
|
|
/// let number = 3
|
|
/// let message = """
|
|
/// If one cookie costs \(price) dollars, \
|
|
/// \(number) cookies cost \(price * number) dollars.
|
|
/// """
|
|
/// print(message)
|
|
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
|
|
@inlinable
|
|
public mutating func appendInterpolation<T>(_ value: T)
|
|
where T: CustomStringConvertible
|
|
{
|
|
value.description.write(to: &self)
|
|
}
|
|
|
|
/// Interpolates the given value's textual representation into the
|
|
/// string literal being created.
|
|
///
|
|
/// Do not call this method directly. It is used by the compiler when
|
|
/// interpreting string interpolations. Instead, use string
|
|
/// interpolation to create a new string by including values, literals,
|
|
/// variables, or expressions enclosed in parentheses, prefixed by a
|
|
/// backslash (`\(`...`)`).
|
|
///
|
|
/// let price = 2
|
|
/// let number = 3
|
|
/// let message = """
|
|
/// If one cookie costs \(price) dollars, \
|
|
/// \(number) cookies cost \(price * number) dollars.
|
|
/// """
|
|
/// print(message)
|
|
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
|
|
@inlinable
|
|
public mutating func appendInterpolation<T>(_ value: T) {
|
|
_print_unlocked(value, &self)
|
|
}
|
|
|
|
/// Creates a string from this instance, consuming the instance in the
|
|
/// process.
|
|
@inlinable
|
|
internal __consuming func make() -> String {
|
|
return _storage
|
|
}
|
|
}
|
|
|
|
extension DefaultStringInterpolation: CustomStringConvertible {
|
|
@inlinable
|
|
public var description: String {
|
|
return _storage
|
|
}
|
|
}
|
|
|
|
extension DefaultStringInterpolation: TextOutputStream {
|
|
@inlinable
|
|
public mutating func write(_ string: String) {
|
|
// Most interpolations will not append to an empty string, so we bypass the
|
|
// empty-singleton check.
|
|
_storage._guts._appendSlow(string._guts)
|
|
}
|
|
|
|
@inlinable
|
|
public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) {
|
|
_storage._guts.append(_UnmanagedString(buffer))
|
|
}
|
|
}
|
|
|
|
// While not strictly necessary, declaring these is faster than using the
|
|
// default implementation.
|
|
extension String {
|
|
/// Creates a new instance from an interpolated string literal.
|
|
///
|
|
/// Do not call this initializer directly. It is used by the compiler when
|
|
/// you create a string using string interpolation. Instead, use string
|
|
/// interpolation to create a new string by including values, literals,
|
|
/// variables, or expressions enclosed in parentheses, prefixed by a
|
|
/// backslash (`\(`...`)`).
|
|
///
|
|
/// let price = 2
|
|
/// let number = 3
|
|
/// let message = """
|
|
/// If one cookie costs \(price) dollars, \
|
|
/// \(number) cookies cost \(price * number) dollars.
|
|
/// """
|
|
/// print(message)
|
|
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
|
|
@inlinable
|
|
@_effects(readonly)
|
|
public init(stringInterpolation: DefaultStringInterpolation) {
|
|
self = stringInterpolation.make()
|
|
}
|
|
}
|
|
|
|
extension Substring {
|
|
/// Creates a new instance from an interpolated string literal.
|
|
///
|
|
/// Do not call this initializer directly. It is used by the compiler when
|
|
/// you create a string using string interpolation. Instead, use string
|
|
/// interpolation to create a new string by including values, literals,
|
|
/// variables, or expressions enclosed in parentheses, prefixed by a
|
|
/// backslash (`\(`...`)`).
|
|
///
|
|
/// let price = 2
|
|
/// let number = 3
|
|
/// let message = """
|
|
/// If one cookie costs \(price) dollars, \
|
|
/// \(number) cookies cost \(price * number) dollars.
|
|
/// """
|
|
/// print(message)
|
|
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
|
|
@inlinable
|
|
@_effects(readonly)
|
|
public init(stringInterpolation: DefaultStringInterpolation) {
|
|
self.init(stringInterpolation.make())
|
|
}
|
|
}
|