mirror of
https://github.com/realm/SwiftLint.git
synced 2026-06-06 20:18:40 +00:00
13703c4466
None of these rules use SourceKit
39 lines
1.3 KiB
Swift
39 lines
1.3 KiB
Swift
import SwiftSyntax
|
|
|
|
public struct ForceCastRule: ConfigurationProviderRule, SourceKitFreeRule {
|
|
public var configuration = SeverityConfiguration(.error)
|
|
|
|
public init() {}
|
|
|
|
public static let description = RuleDescription(
|
|
identifier: "force_cast",
|
|
name: "Force Cast",
|
|
description: "Force casts should be avoided.",
|
|
kind: .idiomatic,
|
|
nonTriggeringExamples: [
|
|
Example("NSNumber() as? Int\n")
|
|
],
|
|
triggeringExamples: [ Example("NSNumber() ↓as! Int\n") ]
|
|
)
|
|
|
|
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
|
ForceCastRuleVisitor()
|
|
.walk(file: file, handler: \.positions)
|
|
.map { position in
|
|
StyleViolation(ruleDescription: Self.description,
|
|
severity: configuration.severity,
|
|
location: Location(file: file, position: position))
|
|
}
|
|
}
|
|
}
|
|
|
|
private final class ForceCastRuleVisitor: SyntaxVisitor {
|
|
var positions: [AbsolutePosition] = []
|
|
|
|
override func visitPost(_ node: AsExprSyntax) {
|
|
if node.questionOrExclamationMark?.tokenKind == .exclamationMark {
|
|
positions.append(node.asTok.positionAfterSkippingLeadingTrivia)
|
|
}
|
|
}
|
|
}
|