Skip to content

SE-0080 (4/4) - Failable initializers for Float->Int #4314

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 2 commits into from
Jan 13, 2017
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
44 changes: 22 additions & 22 deletions stdlib/public/core/FloatingPointTypes.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -13,34 +13,18 @@
import SwiftShims

%{
from SwiftIntTypes import all_integer_types
from SwiftFloatingPointTypes import all_floating_point_types

#
# Utility code for later in this template
#

# Bit counts for all int types
allIntBits = [8, 16, 32, 64, 'Int']

# Number of bits in the Builtin.Word type
word_bits = int(CMAKE_SIZEOF_VOID_P) * 8

# Number of bits in integer literals.
builtinIntLiteralBits = 2048

def allInts():
for bits in allIntBits:
for signed in False, True:
yield bits, signed

def baseIntName(name):
return 'Int' if name == 'Int' else 'Int' + str(name)

def builtinIntName(name):
return 'Int' + str(word_bits) if name == 'Int' else 'Int' + str(name)

def intName(name, signed):
return ('' if signed else 'U') + baseIntName(name)
}%

// TODO: remove once integer proposal is available ----------------------------
Expand Down Expand Up @@ -832,15 +816,31 @@ public prefix func - (x: ${Self}) -> ${Self} {

// Construction from integers.
extension ${Self} {
% for (srcBits, srcSigned) in allInts():
% That = intName(srcBits, srcSigned)
% ThatBuiltinName = builtinIntName(srcBits)
% sign = 's' if srcSigned else 'u'

% for self_ty in all_integer_types(word_bits):
% That = self_ty.stdlib_name
% ThatBuiltinName = self_ty.builtin_name
% srcBits = self_ty.bits
% sign = 's' if self_ty.is_signed else 'u'
@_transparent
public init(_ v: ${That}) {
_value = Builtin.${sign}itofp_${ThatBuiltinName}_FPIEEE${bits}(v._value)
}
% end

% if srcBits < SignificandBitCount:
@available(*, message: "Converting ${That} to ${Self} will always succeed.")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a test for this warning somewhere?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No... I hadn't thought to test these/I'm not sure I know how.

Copy link
Contributor

@CodaFi CodaFi Jan 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use GYB to write tests and the usual filecheck mechanism to check the warning.

% end
@inline(__always)
public init?(exactly value: ${That}) {
_value = Builtin.${sign}itofp_${ThatBuiltinName}_FPIEEE${bits}(value._value)

% if srcBits < SignificandBitCount:
if ${That}(self) != value {
return nil
}
% end
}
% end # all_integer_types
}

// Construction from other floating point numbers.
Expand Down
76 changes: 75 additions & 1 deletion validation-test/stdlib/FloatingPointConversion.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,14 @@
import StdlibUnittest

%{
from SwiftFloatingPointTypes import all_floating_point_types
import gyb
from SwiftFloatingPointTypes import all_floating_point_types, getFtoIBounds
from SwiftIntTypes import all_integer_types
}%

var FixedPointConversionTruncations = TestSuite("FixedPointToFloatingPointConversionTruncations")
var FixedPointConversionFailures = TestSuite("FixedPointToFloatingPointConversionFailures")

var FloatingPointConversionTruncations = TestSuite("FloatingPointToFloatingPointConversionTruncations")
var FloatingPointConversionFailures = TestSuite("FloatingPointToFloatingPointConversionFailures")

Expand Down Expand Up @@ -111,6 +116,75 @@ FloatingPointConversionFailures.test("${OtherFloat}To${Self}Conversion/AlwaysSuc

% end # for in all_floating_point_types (Other)

%{

float_to_int_conversion_template = gyb.parse_template("float_to_int_conversion",
"""
% for int_ty in all_integer_types(word_bits):
% OtherInt = int_ty.stdlib_name
% OtherMin = int_ty.min
% OtherMax = int_ty.max
% (FloatMin, FloatMax) = getFtoIBounds(self_type.bits, int_ty.bits, int_ty.is_signed)

% for testValue in [0, FloatMin, FloatMax, FloatMin - 1, FloatMax + 1, OtherMin, OtherMax]:

% if testValue < OtherMin or testValue > OtherMax:
% # Can't construct `other` value, do nothing and continue.

% elif testValue >= FloatMin and testValue <= FloatMax:

FixedPointConversionTruncations.test("${OtherInt}to${Self}Conversion/${testValue}") {
expectEqual(${Self}(${testValue} as ${OtherInt}), ${testValue})
}

FixedPointConversionFailures.test("${OtherInt}to${Self}FailableConversion/${testValue}") {
expectEqual(${Self}(exactly: ${testValue} as ${OtherInt}), ${testValue})
}

% else:

FixedPointConversionTruncations.test("${OtherInt}to${Self}Truncation/${testValue}") {
let value: ${OtherInt} = ${testValue}
let result = ${Self}(value)
expectNotEqual(${OtherInt}(result), value)
}

FixedPointConversionFailures.test("${OtherInt}to${Self}Failure/${testValue}") {
let value: ${OtherInt} = ${testValue}
let result = ${Self}(exactly: value)
expectEqual(result, ${OtherMin} as ${Self})
expectEqual(${OtherInt}(result!), value)
}

% end

% end # testValue in testValues
% end # for in all_integer_types (Other)
""")
}%

#if arch(i386) || arch(arm)

${gyb.execute_template(
float_to_int_conversion_template,
word_bits=32,
**locals()
)}

#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)

${gyb.execute_template(
float_to_int_conversion_template,
word_bits=64,
**locals()
)}

#else

_UnimplementedError()

#endif

% if Self == 'Float80':
#endif
% end
Expand Down