Skip to content

Commit 83dada2

Browse files
committed
Add floatingValue to FloatLiteralExprSyntax
1 parent bb36e7f commit 83dada2

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Sources/SwiftSyntax/Convenience.swift

Lines changed: 15 additions & 0 deletions
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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,4 +198,25 @@ class SyntaxTests: XCTestCase {
198198
XCTAssertEqual(expr.representedLiteralValue, expected, line: line)
199199
}
200200
}
201+
202+
func testFloatLiteralExprSyntax() {
203+
let testCases: [UInt: (String, Double?)] = [
204+
#line: ("2", 2),
205+
#line: ("2_00_00.001", 2_00_00.001),
206+
#line: ("5.3_8", 5.3_8),
207+
#line: ("12e3", 12000.0),
208+
#line: ("32E1", 320.0),
209+
#line: ("0xdEFACE.C0FFEEp+1", 0xdEFACE.C0FFEEp+1),
210+
#line: ("0xaffab1e.e1fP-2", 0xaffab1e.e1fP-2),
211+
#line: ("🥥", nil),
212+
#line: ("12e+3", 12000.0),
213+
#line: ("12e-3", 0.012),
214+
]
215+
216+
for (line, testCase) in testCases {
217+
let (value, expected) = testCase
218+
let expr = FloatLiteralExprSyntax(literal: .floatLiteral(value))
219+
XCTAssertEqual(expr.representedLiteralValue, expected, line: line)
220+
}
221+
}
201222
}

0 commit comments

Comments
 (0)