Skip to content

Commit

Permalink
Simplify assertion machinery in the standard library.
Browse files Browse the repository at this point in the history
This change includes a number of simplifications that allow us to
eliminate the type checker hack that specifically tries
AssertString. Doing so provides a 25% speedup in the
test/stdlib/ArrayNew.swift test (which is type-checker bound).

The specific simplifications here:
  - User-level
  assert/precondition/preconditionalFailure/assertionFailer/fatalError
  always take an autoclosure producing a String, eliminating the need
  for the StaticString/AssertString dance.
  - Standard-library internal _precondition/_sanityCheck/etc. always
  take a StaticString. When we want to improve the diagnostics in the
  standard library, we can provide a separate overload or
  differently-named function.
  - Remove AssertString, AssertStringType, StaticStringType, which are
  no longer used or needed
  - Remove the AssertString hack from the compiler
  - Remove the "BooleanType" overloads of these functions, because
  their usefuless left when we stopped making optional types conform
  to BooleanType (sorry, should have been a separate patch).



Swift SVN r22139
  • Loading branch information
DougGregor committed Sep 19, 2014
1 parent 531f311 commit 7764f64
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 285 deletions.
8 changes: 0 additions & 8 deletions lib/Sema/ConstraintSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,14 +284,6 @@ getAlternativeLiteralTypes(KnownProtocolKind kind) {
case KnownProtocolKind::StringInterpolationConvertible:
case KnownProtocolKind::StringLiteralConvertible:
case KnownProtocolKind::UnicodeScalarLiteralConvertible:
{
UnqualifiedLookup lookup(TC.Context.getIdentifier("AssertString"),
DC->getModuleScopeContext(),
nullptr);
if (auto typeDecl = lookup.getSingleTypeResult()) {
types.push_back(typeDecl->getDeclaredInterfaceType());
}
}
break;

case KnownProtocolKind::IntegerLiteralConvertible:
Expand Down
107 changes: 20 additions & 87 deletions stdlib/core/Assert.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,6 @@
/// release or fast mode these checks are disabled. This means they may have no
/// effect on program semantics, depending on the assert configuration.

% for (generic_params, closure_type, message_param, message_eval) in [
% ( '',
% 'Bool',
% '_ message: StaticString = StaticString()',
% 'message' ),
% ( '<Str : AssertStringType>',
% 'Bool',
% 'message: @autoclosure () -> Str',
% 'message().stringValue' ),
% ( '<T : BooleanType, Str : StaticStringType>',
% 'T',
% 'message: @autoclosure () -> Str',
% 'message().stringValue' ),
% ( '<T : BooleanType, Str : AssertStringType>',
% 'T',
% 'message: @autoclosure () -> Str',
% 'message().stringValue' ),
% ]:

/// Traditional C-style assert with an optional message.
///
/// When assertions are enabled and `condition` is false, stop program
Expand All @@ -45,14 +26,15 @@
/// When assertions are turned off, the optimizer can assume that the
/// `condition` is true.
@transparent
public func assert${generic_params}(
condition: @autoclosure () -> ${closure_type}, ${message_param},
public func assert(
condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
// Only assert in debug mode.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_assertionFailed("assertion failed", ${message_eval}, file, line)
_assertionFailed("assertion failed", message(), file, line)
}
}
}
Expand All @@ -63,40 +45,31 @@ public func assert${generic_params}(
///
/// In unchecked mode the optimizer can assume that the `condition` is true.
@transparent
public func precondition${generic_params}(
condition: @autoclosure () -> ${closure_type}, ${message_param},
public func precondition(
condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_assertionFailed("precondition failed", ${message_eval}, file, line)
_assertionFailed("precondition failed", message(), file, line)
}
} else if _isReleaseAssertConfiguration() {
let error = !condition()
Builtin.condfail(error.value)
}
}

% end

% for (generic_params, message_param, message_eval) in [
% ( '',
% 'message: StaticString',
% 'message' ),
% ( '<Str : AssertStringType>',
% 'message: Str',
% 'message.stringValue' ),
% ]:

/// A fatal error occurred and program execution should stop in debug mode. In
/// optimized builds this is a noop.
@transparent @noreturn
public func assertionFailure${generic_params}(
${message_param}, file: StaticString = __FILE__, line: UWord = __LINE__
public func assertionFailure(
_ message: @autoclosure () -> String = String(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
if _isDebugAssertConfiguration() {
_assertionFailed("fatal error", ${message_eval}, file, line)
_assertionFailed("fatal error", message(), file, line)
}
_conditionallyUnreachable()
}
Expand All @@ -105,12 +78,13 @@ public func assertionFailure${generic_params}(
/// in optimized mode. In unchecked builds this is a noop, but the
/// optimizer can still assume that the call is unreachable.
@transparent @noreturn
public func preconditionFailure${generic_params}(
${message_param}, file: StaticString = __FILE__, line: UWord = __LINE__
public func preconditionFailure(
_ message: @autoclosure () -> String = String(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
_assertionFailed("fatal error", ${message_eval}, file, line)
_assertionFailed("fatal error", message(), file, line)
} else if _isReleaseAssertConfiguration() {
Builtin.int_trap()
}
Expand All @@ -120,14 +94,13 @@ public func preconditionFailure${generic_params}(
/// A fatal error occurred and program execution should stop in debug,
/// optimized and unchecked modes.
@transparent @noreturn
public func fatalError${generic_params}(
${message_param}, file: StaticString = __FILE__, line: UWord = __LINE__
public func fatalError(
_ message: @autoclosure () -> String = String(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
_assertionFailed("fatal error", ${message_eval}, file, line)
_assertionFailed("fatal error", message(), file, line)
}

% end

/// Library precondition checks
///
/// Library precondition checks are enabled in debug mode and release mode. When
Expand All @@ -149,21 +122,6 @@ public func _precondition(
Builtin.condfail(error.value)
}
}
@transparent
public func _precondition<T : BooleanType>(
condition: @autoclosure () -> T, _ message: StaticString = StaticString(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_fatalErrorMessage("fatal error", message, file, line)
}
} else if _isReleaseAssertConfiguration() {
let error = !condition().boolValue
Builtin.condfail(error.value)
}
}

@transparent @noreturn
public func _preconditionFailure(
Expand Down Expand Up @@ -215,19 +173,6 @@ public func _debugPrecondition(
}
}

@transparent
public func _debugPrecondition<T : BooleanType>(
condition: @autoclosure () -> T, _ message: StaticString = StaticString(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
// Only check in debug mode.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_fatalErrorMessage("fatal error", message, file, line)
}
}
}

@transparent @noreturn
public func _debugPreconditionFailure(
_ message: StaticString = StaticString(),
Expand Down Expand Up @@ -256,18 +201,6 @@ public func _sanityCheck(
#endif
}

@transparent
public func _sanityCheck<T : BooleanType>(
condition: @autoclosure () -> T, _ message: StaticString = StaticString(),
file: StaticString = __FILE__, line: UWord = __LINE__
) {
#if INTERNAL_CHECKS_ENABLED
if !_branchHint(condition(), true) {
_fatalErrorMessage("fatal error", message, file, line)
}
#endif
}

@transparent @noreturn
public func _sanityCheckFailure(
_ message: StaticString = StaticString(),
Expand Down
99 changes: 9 additions & 90 deletions stdlib/core/StaticString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,41 +10,22 @@
//
//===----------------------------------------------------------------------===//

/// Instances of conforming types can be created from string literals
/// and are used in assertions and precondition checks.
///
/// This protocol exists only for directing overload resolution and
/// string literal type deduction in assertions.
///
/// See also: `StaticStringType`, `StaticString`, `AssertString`
public protocol AssertStringType
: UnicodeScalarLiteralConvertible,
ExtendedGraphemeClusterLiteralConvertible,
StringLiteralConvertible {
/// The textual value, as a `String`
var stringValue: String { get }
}

/// This protocol exists only for directing overload resolution and
/// string literal type deduction in assertions.
///
/// See also: `AssertStringType`, `StaticString`, `AssertString`
public protocol StaticStringType : AssertStringType {}

// Implementation Note: Because StaticString is used in the
// implementation of assert() and fatal(), we keep it extremely close
// to the bare metal. In particular, because we store only Builtin
// types, we are guaranteed that no assertions are involved in its
// construction. This feature is crucial for preventing infinite
// recursion even in non-asserting cases.
// implementation of _precondition(), _fatalErrorMessage(), etc., we
// keep it extremely close to the bare metal. In particular, because
// we store only Builtin types, we are guaranteed that no assertions
// are involved in its construction. This feature is crucial for
// preventing infinite recursion even in non-asserting cases.

/// An extremely simple string designed to represent something
/// "statically knowable".
public struct StaticString
: StaticStringType,
_BuiltinUnicodeScalarLiteralConvertible,
: _BuiltinUnicodeScalarLiteralConvertible,
_BuiltinExtendedGraphemeClusterLiteralConvertible,
_BuiltinStringLiteralConvertible,
UnicodeScalarLiteralConvertible,
ExtendedGraphemeClusterLiteralConvertible,
StringLiteralConvertible,
Printable,
DebugPrintable {

Expand Down Expand Up @@ -202,65 +183,3 @@ public struct StaticString
return self.stringValue.debugDescription
}
}

/// A String-like type that can be constructed from string interpolation, and
/// is considered less specific than `StaticString` in overload resolution.
public struct AssertString
: AssertStringType, StringInterpolationConvertible, Printable,
DebugPrintable {
public var stringValue: String

@transparent
public init() {
self.stringValue = ""
}

@transparent
public init(_ value: String) {
self.stringValue = value
}

@effects(readonly)
@transparent
public init(unicodeScalarLiteral value: String) {
self.stringValue = value
}

@effects(readonly)
@transparent
public init(extendedGraphemeClusterLiteral value: String) {
self.stringValue = value
}

@effects(readonly)
@transparent
public init(stringLiteral value: String) {
self.stringValue = value
}

public static func convertFromStringInterpolation(
strings: AssertString...
) -> AssertString {
var result = String()
for str in strings {
result += str.stringValue
}
return AssertString(result)
}

@transparent
public static func convertFromStringInterpolationSegment<T>(
expr: T
) -> AssertString {
return AssertString(String.convertFromStringInterpolationSegment(expr))
}

public var description: String {
return self.stringValue
}

public var debugDescription: String {
return self.stringValue.debugDescription
}
}

7 changes: 6 additions & 1 deletion stdlib/core/String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,12 @@ extension String : CollectionType {

@availability(*, unavailable, message="cannot subscript String with an Int")
public subscript(i: Int) -> Character {
fatalError("cannot subscript String with an Int")
_fatalErrorMessage(
"fatal error",
"cannot subscript String with an Int",
__FILE__,
__LINE__
)
}

public func generate() -> IndexingGenerator<String> {
Expand Down
2 changes: 1 addition & 1 deletion test/Generics/deduction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,4 @@ postfix func <*> (_: Test<True>) -> String? { return .None }
class Test<C: Bool_> : MetaFunction {} // picks first <*>
typealias Inty = Test<True>.Result
var iy : Inty = 5 // okay, because we picked the first <*>
var iy2 : Inty = "hello" // expected-error{{type 'Inty' does not conform to protocol 'StringLiteralConvertible'}}
var iy2 : Inty = "hello" // expected-error{{'String' is not convertible to 'Inty'}}
2 changes: 1 addition & 1 deletion test/Parse/enum.swift
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ enum RawTypeWithCharacterValues : Character {
}

enum RawTypeWithCharacterValues_Error1 : Character {
case First = "abc" // expected-error {{'Character' does not conform to protocol 'StringLiteralConvertible'}}
case First = "abc" // expected-error {{'String' is not convertible to 'Character'}}
}

enum RawTypeWithFloatValues : Float {
Expand Down
2 changes: 1 addition & 1 deletion test/Parse/type_expr.swift
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ func derivedType() {
// Referencing a nonexistent member or constructor should not trigger errors
// about the type expression.
func nonexistentMember() {
let cons = Foo("this constructor does not exist") // expected-error{{type '()' does not conform to protocol 'StringLiteralConvertible'}}
let cons = Foo("this constructor does not exist") // expected-error{{expression does not conform to type 'StringLiteralConvertible'}}
let prop = Foo.nonexistent // expected-error{{does not have a member named 'nonexistent'}}
let meth = Foo.nonexistent() // expected-error{{does not have a member named 'nonexistent'}}
}
Expand Down
2 changes: 1 addition & 1 deletion test/expr/expressions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ struct Rule {
}
var ruleVar: Rule
ruleVar = Rule("a") // expected-error {{type '(target: String, dependencies: String)' does not conform to protocol 'UnicodeScalarLiteralConvertible'}}
ruleVar = Rule("a") // expected-error {{missing argument for parameter 'dependencies' in call}}
class C {
Expand Down

0 comments on commit 7764f64

Please sign in to comment.