Ensure negative literals in initializers don't trigger `no_magic_numbers` (#4679)
This commit is contained in:
parent
5ec6112ba1
commit
b66dd13e2f
|
@ -22,7 +22,8 @@
|
|||
[jimmya](https://github.com/jimmya)
|
||||
[#issue_number](https://github.com/realm/SwiftLint/issues/4609)
|
||||
|
||||
* Separate analyzer rules as an independent section in the rule directory of the reference.
|
||||
* Separate analyzer rules as an independent section in the rule directory of
|
||||
the reference.
|
||||
[Ethan Wong](https://github.com/GetToSet)
|
||||
[#4664](https://github.com/realm/SwiftLint/pull/4664)
|
||||
|
||||
|
@ -53,6 +54,11 @@
|
|||
[SimplyDanny](https://github.com/SimplyDanny)
|
||||
[#4548](https://github.com/realm/SwiftLint/issues/4548)
|
||||
|
||||
* Ensure that negative literals in initializers do not trigger
|
||||
`no_magic_numbers` rule.
|
||||
[SimplyDanny](https://github.com/SimplyDanny)
|
||||
[#4677](https://github.com/realm/SwiftLint/issues/4677)
|
||||
|
||||
## 0.50.3: Bundle of Towels
|
||||
|
||||
#### Breaking
|
||||
|
|
|
@ -38,6 +38,12 @@ struct NoMagicNumbersRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule
|
|||
return
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Example: Int {
|
||||
case positive = 2
|
||||
case negative = -2
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
|
@ -59,13 +65,13 @@ private extension NoMagicNumbersRule {
|
|||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FloatLiteralExprSyntax) {
|
||||
if node.floatingDigits.isMagicNumber {
|
||||
self.violations.append(node.floatingDigits.positionAfterSkippingLeadingTrivia)
|
||||
violations.append(node.floatingDigits.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: IntegerLiteralExprSyntax) {
|
||||
if node.digits.isMagicNumber {
|
||||
self.violations.append(node.digits.positionAfterSkippingLeadingTrivia)
|
||||
violations.append(node.digits.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -73,14 +79,16 @@ private extension NoMagicNumbersRule {
|
|||
|
||||
private extension TokenSyntax {
|
||||
var isMagicNumber: Bool {
|
||||
let numerStr = text.replacingOccurrences(of: "_", with: "")
|
||||
|
||||
guard let number = Double(numerStr),
|
||||
![0, 1].contains(number),
|
||||
let parentToken = parent?.parent,
|
||||
!parentToken.is(InitializerClauseSyntax.self) else {
|
||||
guard let number = Double(text.replacingOccurrences(of: "_", with: "")) else {
|
||||
return false
|
||||
}
|
||||
if [0, 1].contains(number) {
|
||||
return false
|
||||
}
|
||||
guard let grandparent = parent?.parent else {
|
||||
return true
|
||||
}
|
||||
return !grandparent.is(InitializerClauseSyntax.self)
|
||||
&& grandparent.as(PrefixOperatorExprSyntax.self)?.parent?.is(InitializerClauseSyntax.self) != true
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue