Skip to content

Commit 371fa2a

Browse files
committed
Add floatingValue to FloatLiteralExprSyntax
1 parent 9c16b25 commit 371fa2a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Sources/SwiftSyntax/Convenience.swift

+15
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,21 @@ extension EnumCaseParameterSyntax {
6868
}
6969
}
7070

71+
extension FloatLiteralExprSyntax {
72+
/// A computed property representing the floating-point value parsed from the associated `literal.text` property.
73+
///
74+
/// - Returns: A double value parsed from the associated`literal.text`, or `nil` if the text cannot be parsed as a double.
75+
public var representedLiteralValue: Double? {
76+
guard !hasError else { return nil }
77+
78+
let floatingDigitsWithoutUnderscores = literal.text.filter {
79+
$0 != "_"
80+
}
81+
82+
return Double(floatingDigitsWithoutUnderscores)
83+
}
84+
}
85+
7186
extension IntegerLiteralExprSyntax {
7287
public enum Radix {
7388
case binary

Tests/SwiftSyntaxTest/SyntaxTests.swift

+19
Original file line numberDiff line numberDiff line change
@@ -195,4 +195,23 @@ class SyntaxTests: XCTestCase {
195195
XCTAssertEqual(expr.representedLiteralValue, expected, line: line)
196196
}
197197
}
198+
199+
func testFloatLiteralExprSyntax() {
200+
let testCases: [UInt: (String, Double?)] = [
201+
#line: ("2", 2),
202+
#line: ("2_00_00.001", 2_00_00.001),
203+
#line: ("5.3_8", 5.3_8),
204+
#line: ("12e3", 12000.0),
205+
#line: ("32E1", 320.0),
206+
#line: ("0xdEFACE.C0FFEEp+1", 0xdEFACE.C0FFEEp+1),
207+
#line: ("0xaffab1e.e1fP-2", 0xaffab1e.e1fP-2),
208+
#line: ("🥥", nil),
209+
]
210+
211+
for (line, testCase) in testCases {
212+
let (value, expected) = testCase
213+
let expr = FloatLiteralExprSyntax(literal: .floatLiteral(value))
214+
XCTAssertEqual(expr.representedLiteralValue, expected, line: line)
215+
}
216+
}
198217
}

0 commit comments

Comments
 (0)