Files
SwiftLint/Source/SwiftLintFramework/Rules/Idiomatic/LegacyRandomRule.swift
T
Zev Eisenberg fcf848608e Add Inline test failure messages (#3040)
* Add Example wrapper in order to display test failures inline when running in Xcode.
* Stop using Swift 5.1-only features so we can compile on Xcode 10.2.
* Wrap strings in Example.
* Add Changelog entry.
* Wrap all examples in Example struct.
* Better and more complete capturing of line numbers.
* Fix broken test.
* Better test traceability.
* Address or disable linting warnings.
* Add documentation comments.
* Disable linter for a few cases.
* Limit mutability and add copy-and-mutate utility functions.
* Limit scope of mutability.
2020-02-02 10:35:37 +02:00

58 lines
1.8 KiB
Swift

public struct LegacyRandomRule: ASTRule, OptInRule, ConfigurationProviderRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static var description = RuleDescription(
identifier: "legacy_random",
name: "Legacy Random",
description: "Prefer using `type.random(in:)` over legacy functions.",
kind: .idiomatic,
minSwiftVersion: .fourDotTwo,
nonTriggeringExamples: [
Example("Int.random(in: 0..<10)\n"),
Example("Double.random(in: 8.6...111.34)\n"),
Example("Float.random(in: 0 ..< 1)\n")
],
triggeringExamples: [
Example("↓arc4random(10)\n"),
Example("↓arc4random_uniform(83)\n"),
Example("↓drand48(52)\n")
]
)
private let legacyRandomFunctions: Set<String> = [
"arc4random",
"arc4random_uniform",
"drand48"
]
public func validate(
file: SwiftLintFile,
kind: SwiftExpressionKind,
dictionary: SourceKittenDictionary
) -> [StyleViolation] {
guard containsViolation(kind: kind, dictionary: dictionary),
let offset = dictionary.offset else {
return []
}
let location = Location(file: file, byteOffset: offset)
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: location)
]
}
private func containsViolation(kind: SwiftExpressionKind, dictionary: SourceKittenDictionary) -> Bool {
guard kind == .call,
let name = dictionary.name,
legacyRandomFunctions.contains(name) else {
return false
}
return true
}
}