Enable implicit_return and fix all violations (#5658)

This commit is contained in:
Martin Redington
2024-07-10 12:15:19 +01:00
committed by GitHub
parent 202adf0220
commit ed10aec5f8
140 changed files with 360 additions and 367 deletions
@@ -59,7 +59,7 @@ public extension Array {
///
/// - returns: The elements grouped by applying the specified transformation.
func group<U: Hashable>(by transform: (Element) -> U) -> [U: [Element]] {
return Dictionary(grouping: self, by: { transform($0) })
Dictionary(grouping: self, by: { transform($0) })
}
/// Returns the elements failing the `belongsInSecondPartition` test, followed by the elements passing the
@@ -83,7 +83,7 @@ public extension Array {
///
/// - returns: The result of applying `transform` on every element and flattening the results.
func parallelFlatMap<T>(transform: (Element) -> [T]) -> [T] {
return parallelMap(transform: transform).flatMap { $0 }
parallelMap(transform: transform).flatMap { $0 }
}
/// Same as `compactMap` but spreads the work in the `transform` block in parallel using GCD's `concurrentPerform`.
@@ -92,7 +92,7 @@ public extension Array {
///
/// - returns: The result of applying `transform` on every element and discarding the `nil` ones.
func parallelCompactMap<T>(transform: (Element) -> T?) -> [T] {
return parallelMap(transform: transform).compactMap { $0 }
parallelMap(transform: transform).compactMap { $0 }
}
/// Same as `map` but spreads the work in the `transform` block in parallel using GCD's `concurrentPerform`.
@@ -114,7 +114,7 @@ public extension Array {
public extension Collection {
/// Whether this collection has one or more element.
var isNotEmpty: Bool {
return !isEmpty
!isEmpty
}
/// Get the only element in the collection.
@@ -179,7 +179,7 @@ package extension Configuration {
}
private func findPossiblyExistingVertex(sameAs vertex: Vertex) -> Vertex? {
return vertices.first {
vertices.first {
$0.originalRemoteString != nil && $0.originalRemoteString == vertex.originalRemoteString
} ?? vertices.first { $0.filePath == vertex.filePath }
}
@@ -237,7 +237,7 @@ package extension Configuration {
}
return verticesToMerge.map {
return (
(
configurationDict: $0.configurationDict,
rootDirectory: $0.rootDirectory
)
@@ -81,7 +81,7 @@ internal extension Configuration.FileGraph {
}
internal static func == (lhs: Vertex, rhs: Vertex) -> Bool {
return lhs.filePath == rhs.filePath
lhs.filePath == rhs.filePath
&& lhs.originalRemoteString == rhs.originalRemoteString
&& lhs.rootDirectory == rhs.rootDirectory
}
@@ -18,7 +18,7 @@ extension Configuration {
/// - returns: Files to lint.
public func lintableFiles(inPath path: String, forceExclude: Bool,
excludeBy: ExcludeBy) -> [SwiftLintFile] {
return lintablePaths(inPath: path, forceExclude: forceExclude, excludeBy: excludeBy)
lintablePaths(inPath: path, forceExclude: forceExclude, excludeBy: excludeBy)
.compactMap(SwiftLintFile.init(pathDeferringReading:))
}
@@ -109,7 +109,7 @@ extension Configuration {
///
/// - returns: The expanded excluded file paths.
public func excludedPaths(fileManager: some LintableFileManager = FileManager.default) -> [String] {
return excludedPaths
excludedPaths
.flatMap(Glob.resolveGlob)
.parallelFlatMap { fileManager.filesToLint(inPath: $0, rootDirectory: rootDirectory) }
}
@@ -84,7 +84,7 @@ extension Configuration {
///
/// - returns: A new configuration.
public func configuration(for file: SwiftLintFile) -> Configuration {
return (file.path?.bridge().deletingLastPathComponent).map(configuration(forDirectory:)) ?? self
(file.path?.bridge().deletingLastPathComponent).map(configuration(forDirectory:)) ?? self
}
private func configuration(forDirectory directory: String) -> Configuration {
@@ -44,7 +44,7 @@ extension Configuration {
enableAllRules: Bool = false,
cachePath: String? = nil
) throws {
func defaultStringArray(_ object: Any?) -> [String] { return [String].array(of: object) ?? [] }
func defaultStringArray(_ object: Any?) -> [String] { [String].array(of: object) ?? [] }
// Use either the new 'opt_in_rules' or fallback to the deprecated 'enabled_rules'
let optInRules = defaultStringArray(dict[Key.optInRules.rawValue] ?? dict[Key.enabledRules.rawValue])
@@ -107,7 +107,7 @@ extension Configuration {
// MARK: - Methods: Validations
private static func validKeys(ruleList: RuleList) -> Set<String> {
return validGlobalKeys.union(ruleList.allValidIdentifiers())
validGlobalKeys.union(ruleList.allValidIdentifiers())
}
private static func getIndentationLogIfInvalid(from dict: [String: Any]) -> IndentationStyle {
@@ -136,12 +136,12 @@ extension Configuration {
// Deprecation warning for rules
let deprecatedRulesIdentifiers = ruleList.list.flatMap { identifier, rule -> [(String, String)] in
return rule.description.deprecatedAliases.map { ($0, identifier) }
rule.description.deprecatedAliases.map { ($0, identifier) }
}
let userProvidedRuleIDs = Set(disabledRules + optInRules + onlyRules)
let deprecatedUsages = deprecatedRulesIdentifiers.filter { deprecatedIdentifier, _ in
return dict[deprecatedIdentifier] != nil || userProvidedRuleIDs.contains(deprecatedIdentifier)
dict[deprecatedIdentifier] != nil || userProvidedRuleIDs.contains(deprecatedIdentifier)
}
for (deprecatedIdentifier, identifier) in deprecatedUsages {
@@ -38,12 +38,12 @@ public struct SourceKittenDictionary {
/// Body length
public var bodyLength: ByteCount? {
return (value["key.bodylength"] as? Int64).map(ByteCount.init)
(value["key.bodylength"] as? Int64).map(ByteCount.init)
}
/// Body offset.
public var bodyOffset: ByteCount? {
return (value["key.bodyoffset"] as? Int64).map(ByteCount.init)
(value["key.bodyoffset"] as? Int64).map(ByteCount.init)
}
/// Body byte range.
@@ -54,26 +54,26 @@ public struct SourceKittenDictionary {
/// Kind.
public var kind: String? {
return value["key.kind"] as? String
value["key.kind"] as? String
}
/// Length.
public var length: ByteCount? {
return (value["key.length"] as? Int64).map(ByteCount.init)
(value["key.length"] as? Int64).map(ByteCount.init)
}
/// Name.
public var name: String? {
return value["key.name"] as? String
value["key.name"] as? String
}
/// Name length.
public var nameLength: ByteCount? {
return (value["key.namelength"] as? Int64).map(ByteCount.init)
(value["key.namelength"] as? Int64).map(ByteCount.init)
}
/// Name offset.
public var nameOffset: ByteCount? {
return (value["key.nameoffset"] as? Int64).map(ByteCount.init)
(value["key.nameoffset"] as? Int64).map(ByteCount.init)
}
/// Byte range of name.
@@ -84,7 +84,7 @@ public struct SourceKittenDictionary {
/// Offset.
public var offset: ByteCount? {
return (value["key.offset"] as? Int64).map(ByteCount.init)
(value["key.offset"] as? Int64).map(ByteCount.init)
}
/// Returns byte range starting from `offset` with `length` bytes
@@ -95,42 +95,42 @@ public struct SourceKittenDictionary {
/// Setter accessibility.
public var setterAccessibility: String? {
return value["key.setter_accessibility"] as? String
value["key.setter_accessibility"] as? String
}
/// Type name.
public var typeName: String? {
return value["key.typename"] as? String
value["key.typename"] as? String
}
/// Documentation length.
public var docLength: ByteCount? {
return (value["key.doclength"] as? Int64).flatMap(ByteCount.init)
(value["key.doclength"] as? Int64).flatMap(ByteCount.init)
}
/// The attribute for this dictionary, as returned by SourceKit.
public var attribute: String? {
return value["key.attribute"] as? String
value["key.attribute"] as? String
}
/// Module name in `@import` expressions.
public var moduleName: String? {
return value["key.modulename"] as? String
value["key.modulename"] as? String
}
/// The line number for this declaration.
public var line: Int64? {
return value["key.line"] as? Int64
value["key.line"] as? Int64
}
/// The column number for this declaration.
public var column: Int64? {
return value["key.column"] as? Int64
value["key.column"] as? Int64
}
/// The `SwiftDeclarationAttributeKind` values associated with this dictionary.
public var enclosedSwiftAttributes: [SwiftDeclarationAttributeKind] {
return swiftAttributes.compactMap { $0.attribute }
swiftAttributes.compactMap { $0.attribute }
.compactMap(SwiftDeclarationAttributeKind.init(rawValue:))
}
@@ -154,7 +154,7 @@ public struct SourceKittenDictionary {
}
public var enclosedVarParameters: [SourceKittenDictionary] {
return substructure.flatMap { subDict -> [SourceKittenDictionary] in
substructure.flatMap { subDict -> [SourceKittenDictionary] in
if subDict.declarationKind == .varParameter {
return [subDict]
}
@@ -168,7 +168,7 @@ public struct SourceKittenDictionary {
}
public var enclosedArguments: [SourceKittenDictionary] {
return substructure.flatMap { subDict -> [SourceKittenDictionary] in
substructure.flatMap { subDict -> [SourceKittenDictionary] in
guard subDict.expressionKind == .argument else {
return []
}
@@ -244,8 +244,8 @@ public extension Dictionary where Key == Example {
///
/// - returns: A new `Dictionary`.
func removingViolationMarkers() -> [Key: Value] {
return Dictionary(uniqueKeysWithValues: map { key, value in
return (key.removingViolationMarkers(), value)
Dictionary(uniqueKeysWithValues: map { key, value in
(key.removingViolationMarkers(), value)
})
}
}
@@ -47,7 +47,7 @@ extension FileManager: LintableFileManager {
}
public func modificationDate(forFileAtPath path: String) -> Date? {
return (try? attributesOfItem(atPath: path))?[.modificationDate] as? Date
(try? attributesOfItem(atPath: path))?[.modificationDate] as? Date
}
public func isFile(atPath path: String) -> Bool {
@@ -2,7 +2,7 @@ import Foundation
extension NSRange {
func intersects(_ range: NSRange) -> Bool {
return NSIntersectionRange(self, range).length > 0
NSIntersectionRange(self, range).length > 0
}
func intersects(_ ranges: [NSRange]) -> Bool {
@@ -57,17 +57,17 @@ public extension NSRegularExpression {
func matches(in stringView: StringView,
options: NSRegularExpression.MatchingOptions = []) -> [NSTextCheckingResult] {
return matches(in: stringView.string, options: options, range: stringView.range)
matches(in: stringView.string, options: options, range: stringView.range)
}
func matches(in stringView: StringView,
options: NSRegularExpression.MatchingOptions = [],
range: NSRange) -> [NSTextCheckingResult] {
return matches(in: stringView.string, options: options, range: range)
matches(in: stringView.string, options: options, range: range)
}
func matches(in file: SwiftLintFile,
options: NSRegularExpression.MatchingOptions = []) -> [NSTextCheckingResult] {
return matches(in: file.stringView.string, options: options, range: file.stringView.range)
matches(in: file.stringView.string, options: options, range: file.stringView.range)
}
}
@@ -15,11 +15,11 @@ public extension String {
}
func isUppercase() -> Bool {
return self == uppercased()
self == uppercased()
}
func isLowercase() -> Bool {
return self == lowercased()
self == lowercased()
}
private subscript (range: Range<Int>) -> String {
@@ -63,14 +63,14 @@ public extension String {
}
var fullNSRange: NSRange {
return NSRange(location: 0, length: utf16.count)
NSRange(location: 0, length: utf16.count)
}
/// Returns a new string, converting the path to a canonical absolute path.
///
/// - returns: A new `String`.
func absolutePathStandardized() -> String {
return bridge().absolutePathRepresentation().bridge().standardizingPath
bridge().absolutePathRepresentation().bridge().standardizingPath
}
var isFile: Bool {
@@ -88,7 +88,7 @@ public extension String {
/// - Parameter character: Character to count
/// - Returns: Number of times `character` occurs in `self`
func countOccurrences(of character: Character) -> Int {
return self.reduce(0, {
self.reduce(0, {
$1 == character ? $0 + 1 : $0
})
}
@@ -2,7 +2,7 @@ import SourceKittenFramework
public extension SwiftDeclarationAttributeKind {
static var attributesRequiringFoundation: Set<SwiftDeclarationAttributeKind> {
return [
[
.objc,
.objcName,
.objcMembers,
@@ -95,7 +95,7 @@ public extension SwiftDeclarationAttributeKind {
}
public var debugDescription: String {
return self.rawValue
self.rawValue
}
}
}
@@ -22,18 +22,18 @@ private let responseCache = Cache { file -> [String: any SourceKitRepresentable]
}
}
private let structureDictionaryCache = Cache { file in
return responseCache.get(file).map(Structure.init).map { SourceKittenDictionary($0.dictionary) }
responseCache.get(file).map(Structure.init).map { SourceKittenDictionary($0.dictionary) }
}
private let syntaxTreeCache = Cache { file -> SourceFileSyntax in
return Parser.parse(source: file.contents)
Parser.parse(source: file.contents)
}
private let foldedSyntaxTreeCache = Cache { file -> SourceFileSyntax? in
return OperatorTable.standardOperators
OperatorTable.standardOperators
.foldAll(file.syntaxTree) { _ in }
.as(SourceFileSyntax.self)
}
private let locationConverterCache = Cache { file -> SourceLocationConverter in
return SourceLocationConverter(fileName: file.path ?? "<nopath>", tree: file.syntaxTree)
SourceLocationConverter(fileName: file.path ?? "<nopath>", tree: file.syntaxTree)
}
private let commandsCache = Cache { file -> [Command] in
guard file.contents.contains("swiftlint:") else {
@@ -98,12 +98,12 @@ private class Cache<T> {
extension SwiftLintFile {
fileprivate var cacheKey: FileCacheKey {
return id
id
}
public var sourcekitdFailed: Bool {
get {
return responseCache.get(self) == nil
responseCache.get(self) == nil
}
set {
if newValue {
@@ -116,7 +116,7 @@ extension SwiftLintFile {
internal var assertHandler: AssertHandler? {
get {
return assertHandlerCache.get(self)
assertHandlerCache.get(self)
}
set {
assertHandlerCache.set(key: cacheKey, value: newValue)
@@ -18,7 +18,7 @@ extension SwiftLintFile {
let commands: [Command]
if let restrictingRuleIdentifiers {
commands = self.commands().filter { command in
return command.ruleIdentifiers.contains(where: restrictingRuleIdentifiers.contains)
command.ruleIdentifiers.contains(where: restrictingRuleIdentifiers.contains)
}
} else {
commands = self.commands()
@@ -94,7 +94,7 @@ extension SwiftLintFile {
}
public func match(pattern: String, with syntaxKinds: [SyntaxKind], range: NSRange? = nil) -> [NSRange] {
return match(pattern: pattern, range: range)
match(pattern: pattern, range: range)
.filter { $0.1 == syntaxKinds }
.map { $0.0 }
}
@@ -112,18 +112,18 @@ extension SwiftLintFile {
public func matchesAndSyntaxKinds(matching pattern: String,
range: NSRange? = nil) -> [(NSTextCheckingResult, [SyntaxKind])] {
return matchesAndTokens(matching: pattern, range: range).map { textCheckingResult, tokens in
matchesAndTokens(matching: pattern, range: range).map { textCheckingResult, tokens in
(textCheckingResult, tokens.kinds)
}
}
public func rangesAndTokens(matching pattern: String,
range: NSRange? = nil) -> [(NSRange, [SwiftLintSyntaxToken])] {
return matchesAndTokens(matching: pattern, range: range).map { ($0.0.range, $0.1) }
matchesAndTokens(matching: pattern, range: range).map { ($0.0.range, $0.1) }
}
public func match(pattern: String, range: NSRange? = nil, captureGroup: Int = 0) -> [(NSRange, [SyntaxKind])] {
return matchesAndSyntaxKinds(matching: pattern, range: range).map { textCheckingResult, syntaxKinds in
matchesAndSyntaxKinds(matching: pattern, range: range).map { textCheckingResult, syntaxKinds in
(textCheckingResult.range(at: captureGroup), syntaxKinds)
}
}
@@ -203,7 +203,7 @@ extension SwiftLintFile {
excludingSyntaxKinds syntaxKinds: Set<SyntaxKind>,
range: NSRange? = nil,
captureGroup: Int = 0) -> [NSRange] {
return match(pattern: pattern, range: range, captureGroup: captureGroup)
match(pattern: pattern, range: range, captureGroup: captureGroup)
.filter { syntaxKinds.isDisjoint(with: $0.1) }
.map { $0.0 }
}
@@ -279,7 +279,7 @@ extension SwiftLintFile {
}
public func ruleEnabled(violatingRange: NSRange, for rule: some Rule) -> NSRange? {
return ruleEnabled(violatingRanges: [violatingRange], for: rule).first
ruleEnabled(violatingRanges: [violatingRange], for: rule).first
}
public func isACL(token: SwiftLintSyntaxToken) -> Bool {
@@ -292,6 +292,6 @@ extension SwiftLintFile {
}
public func contents(for token: SwiftLintSyntaxToken) -> String? {
return stringView.substringWithByteRange(token.range)
stringView.substringWithByteRange(token.range)
}
}
@@ -12,7 +12,7 @@ public extension SwiftLintSyntaxVisitor {
}
func walk<T>(file: SwiftLintFile, handler: (Self) -> [T]) -> [T] {
return walk(tree: file.syntaxTree, handler: handler)
walk(tree: file.syntaxTree, handler: handler)
}
}
@@ -25,7 +25,7 @@ public extension SyntaxKind {
/// Syntax kinds that don't have associated module info when getting their cursor info.
static var kindsWithoutModuleInfo: Set<SyntaxKind> {
return [
[
.attributeBuiltin,
.keyword,
.number,
@@ -50,7 +50,7 @@ public enum AccessControlLevel: String, CustomStringConvertible {
/// Returns true if is `private` or `fileprivate`
public var isPrivate: Bool {
return self == .private || self == .fileprivate
self == .private || self == .fileprivate
}
}
@@ -67,6 +67,6 @@ extension AccessControlLevel: Comparable {
}
public static func < (lhs: AccessControlLevel, rhs: AccessControlLevel) -> Bool {
return lhs.priority < rhs.priority
lhs.priority < rhs.priority
}
}
@@ -306,7 +306,7 @@ extension Configuration: Hashable {
}
public static func == (lhs: Configuration, rhs: Configuration) -> Bool {
return lhs.includedPaths == rhs.includedPaths &&
lhs.includedPaths == rhs.includedPaths &&
lhs.excludedPaths == rhs.excludedPaths &&
lhs.indentation == rhs.indentation &&
lhs.warningThreshold == rhs.warningThreshold &&
@@ -327,7 +327,7 @@ extension Configuration: Hashable {
// MARK: - CustomStringConvertible
extension Configuration: CustomStringConvertible {
public var description: String {
return "Configuration: \n"
"Configuration: \n"
+ "- Indentation Style: \(indentation)\n"
+ "- Included Paths: \(includedPaths)\n"
+ "- Excluded Paths: \(excludedPaths)\n"
+1 -1
View File
@@ -7,7 +7,7 @@ public struct Correction: Equatable, Sendable {
/// The console-printable description for this correction.
public var consoleDescription: String {
return "\(location.file ?? "<nopath>"): Corrected \(ruleDescription.name)"
"\(location.file ?? "<nopath>"): Corrected \(ruleDescription.name)"
}
/// Memberwise initializer.
+3 -3
View File
@@ -86,7 +86,7 @@ public extension Example {
/// Returns a copy of the Example with all instances of the "↓" character removed.
func removingViolationMarkers() -> Example {
return with(code: code.replacingOccurrences(of: "↓", with: ""))
with(code: code.replacingOccurrences(of: "↓", with: ""))
}
}
@@ -127,7 +127,7 @@ extension Example: Hashable {
public static func == (lhs: Example, rhs: Example) -> Bool {
// Ignoring file/line metadata because two Examples could represent
// the same idea, but captured at two different points in the code
return lhs.code == rhs.code
lhs.code == rhs.code
}
public func hash(into hasher: inout Hasher) {
@@ -139,7 +139,7 @@ extension Example: Hashable {
extension Example: Comparable {
public static func < (lhs: Example, rhs: Example) -> Bool {
return lhs.code < rhs.code
lhs.code < rhs.code
}
}
@@ -5,7 +5,7 @@ internal struct HashableConfigurationRuleWrapperWrapper: Hashable {
lhs: HashableConfigurationRuleWrapperWrapper, rhs: HashableConfigurationRuleWrapperWrapper
) -> Bool {
// Only use identifier for equality check (not taking config into account)
return type(of: lhs.configurationRuleWrapper.rule).description.identifier
type(of: lhs.configurationRuleWrapper.rule).description.identifier
== type(of: rhs.configurationRuleWrapper.rule).description.identifier
}
+8 -8
View File
@@ -24,10 +24,10 @@ private extension Rule {
}
let regionsDisablingCurrentRule = regions.filter { region in
return region.isRuleDisabled(self.init())
region.isRuleDisabled(self.init())
}
let regionsDisablingSuperfluousDisableRule = regions.filter { region in
return region.isRuleDisabled(superfluousDisableCommandRule)
region.isRuleDisabled(superfluousDisableCommandRule)
}
return regionsDisablingCurrentRule.compactMap { region -> StyleViolation? in
@@ -40,7 +40,7 @@ private extension Rule {
}
let noViolationsInDisabledRegion = !allViolations.contains { violation in
return region.contains(violation.location)
region.contains(violation.location)
}
guard noViolationsInDisabledRegion else {
return nil
@@ -91,9 +91,9 @@ private extension Rule {
}
let (disabledViolationsAndRegions, enabledViolationsAndRegions) = violations.map { violation in
return (violation, regions.first { $0.contains(violation.location) })
(violation, regions.first { $0.contains(violation.location) })
}.partitioned { _, region in
return region?.isRuleEnabled(self) ?? true
region?.isRuleEnabled(self) ?? true
}
let ruleIDs = Self.description.allIdentifiers +
@@ -204,7 +204,7 @@ public struct CollectedLinter {
///
/// - returns: All style violations found by this linter.
public func styleViolations(using storage: RuleStorage) -> [StyleViolation] {
return getStyleViolations(using: storage).0
getStyleViolations(using: storage).0
}
/// Computes or retrieves style violations and the time spent executing each rule.
@@ -214,7 +214,7 @@ public struct CollectedLinter {
/// - returns: All style violations found by this linter, and the time spent executing each rule.
public func styleViolationsAndRuleTimes(using storage: RuleStorage)
-> ([StyleViolation], [(id: String, time: Double)]) {
return getStyleViolations(using: storage, benchmark: true)
getStyleViolations(using: storage, benchmark: true)
}
private func getStyleViolations(using storage: RuleStorage,
@@ -348,7 +348,7 @@ public struct CollectedLinter {
!region.disabledRuleIdentifiers.contains(.all) &&
!region.disabledRuleIdentifiers.contains(superfluousRuleIdentifier)
}).map { id in
return StyleViolation(
StyleViolation(
ruleDescription: type(of: superfluousDisableCommandRule).description,
severity: superfluousDisableCommandRule.configuration.severity,
location: region.start,
@@ -13,7 +13,7 @@ private struct FileCacheEntry: Codable {
private struct FileCache: Codable {
var entries: [String: FileCacheEntry]
static var empty: FileCache { return Self(entries: [:]) }
static var empty: FileCache { Self(entries: [:]) }
}
/// A persisted cache for storing and retrieving linter results.
@@ -115,7 +115,7 @@ public final class LinterCache {
}
internal func flushed() -> LinterCache {
return Self(cache: mergeCaches(), location: location, fileManager: fileManager, swiftVersion: swiftVersion)
Self(cache: mergeCaches(), location: location, fileManager: fileManager, swiftVersion: swiftVersion)
}
private func fileCache(cacheDescription: String) -> FileCache {
+1 -1
View File
@@ -23,7 +23,7 @@ public struct Location: CustomStringConvertible, Comparable, Codable, Sendable {
/// The file path for this location relative to the current working directory.
public var relativeFile: String? {
return file?.replacingOccurrences(of: FileManager.default.currentDirectoryPath + "/", with: "")
file?.replacingOccurrences(of: FileManager.default.currentDirectoryPath + "/", with: "")
}
/// Creates a `Location` by specifying its properties directly.
+3 -3
View File
@@ -28,7 +28,7 @@ public struct Region: Equatable {
///
/// - returns: True if the specific location is contained in this region.
public func contains(_ location: Location) -> Bool {
return start <= location && end >= location
start <= location && end >= location
}
/// Whether the specified rule is enabled in this region.
@@ -37,7 +37,7 @@ public struct Region: Equatable {
///
/// - returns: True if the specified rule is enabled in this region.
public func isRuleEnabled(_ rule: some Rule) -> Bool {
return !isRuleDisabled(rule)
!isRuleDisabled(rule)
}
/// Whether the specified rule is disabled in this region.
@@ -46,7 +46,7 @@ public struct Region: Equatable {
///
/// - returns: True if the specified rule is disabled in this region.
public func isRuleDisabled(_ rule: some Rule) -> Bool {
return areRulesDisabled(ruleIDs: type(of: rule).description.allIdentifiers)
areRulesDisabled(ruleIDs: type(of: rule).description.allIdentifiers)
}
/// Whether the given rules are disabled in this region.
@@ -52,11 +52,11 @@ public struct RuleDescription: Equatable, Sendable {
public let requiresFileOnDisk: Bool
/// The console-printable string for this description.
public var consoleDescription: String { return "\(name) (\(identifier)): \(description)" }
public var consoleDescription: String { "\(name) (\(identifier)): \(description)" }
/// All identifiers that have been used to uniquely identify this rule in past and current SwiftLint versions.
public var allIdentifiers: [String] {
return Array(deprecatedAliases) + [identifier]
Array(deprecatedAliases) + [identifier]
}
/// Creates a `RuleDescription` by specifying all its properties directly.
@@ -92,6 +92,6 @@ public struct RuleDescription: Equatable, Sendable {
// MARK: Equatable
public static func == (lhs: RuleDescription, rhs: RuleDescription) -> Bool {
return lhs.identifier == rhs.identifier
lhs.identifier == rhs.identifier
}
}
+3 -3
View File
@@ -73,11 +73,11 @@ public struct RuleList {
}
internal func identifier(for alias: String) -> String? {
return aliases[alias]
aliases[alias]
}
internal func allValidIdentifiers() -> [String] {
return list.flatMap { _, rule -> [String] in
list.flatMap { _, rule -> [String] in
rule.description.allIdentifiers
}
}
@@ -85,7 +85,7 @@ public struct RuleList {
extension RuleList: Equatable {
public static func == (lhs: RuleList, rhs: RuleList) -> Bool {
return lhs.list.map { $0.0 } == rhs.list.map { $0.0 }
lhs.list.map { $0.0 } == rhs.list.map { $0.0 }
&& lhs.list.map { $0.1.description } == rhs.list.map { $0.1.description }
&& lhs.aliases == rhs.aliases
}
@@ -27,6 +27,6 @@ public final class RuleRegistry: @unchecked Sendable {
///
/// - returns: The rule matching the specified ID, if one was found.
public func rule(forID id: String) -> (any Rule.Type)? {
return list.list[id]
list.list[id]
}
}
@@ -32,7 +32,7 @@ public class RuleStorage: CustomStringConvertible {
///
/// - returns: All file information for a given rule that was collected via `collect(...)`.
func collectedInfo<R: CollectingRule>(for rule: R) -> [SwiftLintFile: R.FileInfo]? {
return access.sync {
access.sync {
storage[ObjectIdentifier(R.self)] as? [SwiftLintFile: R.FileInfo]
}
}
@@ -20,7 +20,7 @@ public struct StyleViolation: CustomStringConvertible, Codable, Hashable {
/// A printable description for this violation.
public var description: String {
return XcodeReporter.generateForSingleViolation(self)
XcodeReporter.generateForSingleViolation(self)
}
/// Creates a `StyleViolation` by specifying its properties directly.
@@ -47,22 +47,22 @@ public final class SwiftLintFile {
/// The path on disk for this file.
public var path: String? {
return file.path
file.path
}
/// The file's contents.
public var contents: String {
return file.contents
file.contents
}
/// A string view into the contents of this file optimized for string manipulation operations.
public var stringView: StringView {
return file.stringView
file.stringView
}
/// The parsed lines for this file's contents.
public var lines: [Line] {
return file.lines
file.lines
}
/// Mark this file as used for testing purposes.
@@ -23,11 +23,11 @@ public struct SwiftLintSyntaxMap {
/// - returns: The array of syntax tokens intersecting with byte range.
public func tokens(inByteRange byteRange: ByteRange) -> [SwiftLintSyntaxToken] {
func intersect(_ token: SwiftLintSyntaxToken) -> Bool {
return token.range.intersects(byteRange)
token.range.intersects(byteRange)
}
func intersectsOrAfter(_ token: SwiftLintSyntaxToken) -> Bool {
return token.offset + token.length > byteRange.location
token.offset + token.length > byteRange.location
}
guard let startIndex = tokens.firstIndexAssumingSorted(where: intersectsOrAfter) else {
@@ -49,6 +49,6 @@ public struct SwiftLintSyntaxMap {
///
/// - returns: The syntax kinds in the specified byte range.
public func kinds(inByteRange byteRange: ByteRange) -> [SyntaxKind] {
return tokens(inByteRange: byteRange).compactMap { $0.kind }
tokens(inByteRange: byteRange).compactMap { $0.kind }
}
}
@@ -18,23 +18,23 @@ public struct SwiftLintSyntaxToken {
/// The byte range in a source file for this token.
public var range: ByteRange {
return value.range
value.range
}
/// The starting byte offset in a source file for this token.
public var offset: ByteCount {
return value.offset
value.offset
}
/// The length in bytes for this token.
public var length: ByteCount {
return value.length
value.length
}
}
public extension Array where Element == SwiftLintSyntaxToken {
/// The kinds for these tokens.
var kinds: [SyntaxKind] {
return compactMap { $0.kind }
compactMap { $0.kind }
}
}
@@ -95,14 +95,14 @@ public extension SwiftVersion {
private extension Dictionary where Key == String {
var versionMajor: Int? {
return (self["key.version_major"] as? Int64).flatMap({ Int($0) })
(self["key.version_major"] as? Int64).flatMap({ Int($0) })
}
var versionMinor: Int? {
return (self["key.version_minor"] as? Int64).flatMap({ Int($0) })
(self["key.version_minor"] as? Int64).flatMap({ Int($0) })
}
var versionPatch: Int? {
return (self["key.version_patch"] as? Int64).flatMap({ Int($0) })
(self["key.version_patch"] as? Int64).flatMap({ Int($0) })
}
}
@@ -9,6 +9,6 @@ public enum ViolationSeverity: String, Comparable, Codable, InlinableOptionType
// MARK: Comparable
public static func < (lhs: ViolationSeverity, rhs: ViolationSeverity) -> Bool {
return lhs == .warning && rhs == .error
lhs == .warning && rhs == .error
}
}
+3 -3
View File
@@ -26,7 +26,7 @@ public struct YamlParser {
private extension Constructor {
static func swiftlintConstructor(env: [String: String]) -> Constructor {
return Constructor(customScalarMap(env: env))
Constructor(customScalarMap(env: env))
}
static func customScalarMap(env: [String: String]) -> ScalarMap {
@@ -40,8 +40,8 @@ private extension Constructor {
private extension String {
static func constructExpandingEnvVars(env: [String: String]) -> (_ scalar: Node.Scalar) -> String? {
return { (scalar: Node.Scalar) -> String? in
return scalar.string.expandingEnvVars(env: env)
{ (scalar: Node.Scalar) -> String? in
scalar.string.expandingEnvVars(env: env)
}
}
+5 -5
View File
@@ -27,7 +27,7 @@ public protocol ASTRule: Rule {
public extension ASTRule {
func validate(file: SwiftLintFile) -> [StyleViolation] {
return validate(file: file, dictionary: file.structureDictionary)
validate(file: file, dictionary: file.structureDictionary)
}
/// Executes the rule on a file and a subset of its AST structure, returning any violations to the rule's
@@ -38,7 +38,7 @@ public extension ASTRule {
///
/// - returns: All style violations to the rule's expectations.
func validate(file: SwiftLintFile, dictionary: SourceKittenDictionary) -> [StyleViolation] {
return dictionary.traverseDepthFirst { subDict in
dictionary.traverseDepthFirst { subDict in
guard let kind = self.kind(from: subDict) else { return nil }
return validate(file: file, kind: kind, dictionary: subDict)
}
@@ -47,18 +47,18 @@ public extension ASTRule {
public extension ASTRule where KindType == SwiftDeclarationKind {
func kind(from dictionary: SourceKittenDictionary) -> KindType? {
return dictionary.declarationKind
dictionary.declarationKind
}
}
public extension ASTRule where KindType == SwiftExpressionKind {
func kind(from dictionary: SourceKittenDictionary) -> KindType? {
return dictionary.expressionKind
dictionary.expressionKind
}
}
public extension ASTRule where KindType == StatementKind {
func kind(from dictionary: SourceKittenDictionary) -> KindType? {
return dictionary.statementKind
dictionary.statementKind
}
}
@@ -54,11 +54,11 @@ public extension CollectingRule {
return validate(file: file, collectedInfo: info, compilerArguments: compilerArguments)
}
func collectInfo(for file: SwiftLintFile, compilerArguments: [String]) -> FileInfo {
return collectInfo(for: file)
collectInfo(for: file)
}
func validate(file: SwiftLintFile, collectedInfo: [SwiftLintFile: FileInfo],
compilerArguments: [String]) -> [StyleViolation] {
return validate(file: file, collectedInfo: collectedInfo)
validate(file: file, collectedInfo: collectedInfo)
}
func validate(file: SwiftLintFile) -> [StyleViolation] {
queuedFatalError("Must call `validate(file:collectedInfo:)` for CollectingRule")
@@ -116,7 +116,7 @@ package protocol CollectingCorrectableRule: CollectingRule, CorrectableRule {
package extension CollectingCorrectableRule {
func correct(file: SwiftLintFile, collectedInfo: [SwiftLintFile: FileInfo],
compilerArguments: [String]) -> [Correction] {
return correct(file: file, collectedInfo: collectedInfo)
correct(file: file, collectedInfo: collectedInfo)
}
func correct(file: SwiftLintFile, using storage: RuleStorage, compilerArguments: [String]) -> [Correction] {
+4 -4
View File
@@ -84,11 +84,11 @@ public extension Rule {
func validate(file: SwiftLintFile, using storage: RuleStorage,
compilerArguments: [String]) -> [StyleViolation] {
return validate(file: file, compilerArguments: compilerArguments)
validate(file: file, compilerArguments: compilerArguments)
}
func validate(file: SwiftLintFile, compilerArguments: [String]) -> [StyleViolation] {
return validate(file: file)
validate(file: file)
}
func isEqualTo(_ rule: any Rule) -> Bool {
@@ -153,10 +153,10 @@ public protocol CorrectableRule: Rule {
public extension CorrectableRule {
func correct(file: SwiftLintFile, compilerArguments: [String]) -> [Correction] {
return correct(file: file)
correct(file: file)
}
func correct(file: SwiftLintFile, using storage: RuleStorage, compilerArguments: [String]) -> [Correction] {
return correct(file: file, compilerArguments: compilerArguments)
correct(file: file, compilerArguments: compilerArguments)
}
}
@@ -26,7 +26,7 @@ struct CSVReporter: Reporter {
// MARK: - Private
private static func csvRow(for violation: StyleViolation) -> String {
return [
[
violation.location.file?.escapedForCSV() ?? "",
violation.location.line?.description ?? "",
violation.location.character?.description ?? "",
@@ -8,7 +8,7 @@ struct CheckstyleReporter: Reporter {
static let description = "Reports violations as Checkstyle XML."
static func generateReport(_ violations: [StyleViolation]) -> String {
return [
[
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<checkstyle version=\"4.3\">",
violations
.group(by: { ($0.location.file ?? "<nopath>").escapedForXML() })
@@ -21,7 +21,7 @@ struct CheckstyleReporter: Reporter {
// MARK: - Private
private static func generateForViolationFile(_ file: String, violations: [StyleViolation]) -> String {
return [
[
"\n\t<file name=\"", file, "\">\n",
violations.map(generateForSingleViolation).joined(),
"\t</file>",
@@ -13,14 +13,14 @@ struct CodeClimateReporter: Reporter {
static let description = "Reports violations as a JSON array in Code Climate format."
static func generateReport(_ violations: [StyleViolation]) -> String {
return toJSON(violations.map(dictionary(for:)))
toJSON(violations.map(dictionary(for:)))
.replacingOccurrences(of: "\\/", with: "/")
}
// MARK: - Private
private static func dictionary(for violation: StyleViolation) -> [String: Any] {
return [
[
"check_name": violation.ruleName,
"description": violation.reason,
"engine_name": "SwiftLint",
@@ -8,7 +8,7 @@ struct GitHubActionsLoggingReporter: Reporter {
"machine for Actions can recognize as messages."
static func generateReport(_ violations: [StyleViolation]) -> String {
return violations.map(generateForSingleViolation).joined(separator: "\n")
violations.map(generateForSingleViolation).joined(separator: "\n")
}
// MARK: - Private
@@ -17,7 +17,7 @@ struct GitHubActionsLoggingReporter: Reporter {
// swiftlint:disable:next line_length
// https://help.github.com/en/github/automating-your-workflow-with-github-actions/development-tools-for-github-actions#logging-commands
// ::(warning|error) file={relative_path_to_file},line={:line},col={:character}::{content}
return [
[
"::\(violation.severity.rawValue) ",
"file=\(violation.location.relativeFile ?? ""),",
"line=\(violation.location.line ?? 1),",
@@ -7,7 +7,7 @@ struct GitLabJUnitReporter: Reporter {
static let description = "Reports violations as JUnit XML supported by GitLab."
static func generateReport(_ violations: [StyleViolation]) -> String {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuites><testsuite>" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuites><testsuite>" +
violations.map({ violation -> String in
let fileName = (violation.location.relativeFile ?? "<nopath>").escapedForXML()
let line = violation.location.line.map(String.init)
@@ -15,8 +15,7 @@ struct HTMLReporter: Reporter {
static let description = "Reports violations as HTML."
static func generateReport(_ violations: [StyleViolation]) -> String {
return generateReport(violations, swiftlintVersion: Version.current.value,
dateString: formatter.string(from: Date()))
generateReport(violations, swiftlintVersion: Version.current.value, dateString: formatter.string(from: Date()))
}
// MARK: - Internal
@@ -10,13 +10,13 @@ struct JSONReporter: Reporter {
static let description = "Reports violations as a JSON array."
static func generateReport(_ violations: [StyleViolation]) -> String {
return toJSON(violations.map(dictionary(for:)))
toJSON(violations.map(dictionary(for:)))
}
// MARK: - Private
private static func dictionary(for violation: StyleViolation) -> [String: Any] {
return [
[
"file": violation.location.file ?? NSNull() as Any,
"line": violation.location.line ?? NSNull() as Any,
"character": violation.location.character ?? NSNull() as Any,
@@ -24,7 +24,7 @@ struct MarkdownReporter: Reporter {
// MARK: - Private
private static func markdownRow(for violation: StyleViolation) -> String {
return [
[
violation.location.file?.escapedForMarkdown() ?? "",
violation.location.line?.description ?? "",
severity(for: violation.severity),
@@ -7,7 +7,7 @@ struct RelativePathReporter: Reporter {
static let description = "Reports violations with relative paths."
static func generateReport(_ violations: [StyleViolation]) -> String {
return violations.map(generateForSingleViolation).joined(separator: "\n")
violations.map(generateForSingleViolation).joined(separator: "\n")
}
/// Generates a report for a single violation.
@@ -18,7 +18,7 @@ struct RelativePathReporter: Reporter {
internal static func generateForSingleViolation(_ violation: StyleViolation) -> String {
// {relative_path_to_file}{:line}{:character}: {error,warning}: {content}
return [
[
"\(violation.location.relativeFile ?? "<nopath>")",
":\(violation.location.line ?? 1)",
":\(violation.location.character ?? 1): ",
@@ -36,7 +36,7 @@ struct SARIFReporter: Reporter {
// MARK: - Private
private static func dictionary(for violation: StyleViolation) -> [String: Any] {
return [
[
"level": violation.severity.rawValue,
"ruleId": violation.ruleIdentifier,
"message": [
@@ -9,14 +9,14 @@ struct SonarQubeReporter: Reporter {
static let description = "Reports violations in SonarQube import format."
static func generateReport(_ violations: [StyleViolation]) -> String {
return toJSON(["issues": violations.map(dictionary(for:))])
toJSON(["issues": violations.map(dictionary(for:))])
}
// MARK: - Private
// refer to https://docs.sonarqube.org/display/SONAR/Generic+Issue+Data
private static func dictionary(for violation: StyleViolation) -> [String: Any] {
return [
[
"engineId": "SwiftLint",
"ruleId": violation.ruleIdentifier,
"primaryLocation": [
@@ -7,7 +7,7 @@ struct XcodeReporter: Reporter {
static let description = "Reports violations in the format Xcode uses to display in the IDE. (default)"
static func generateReport(_ violations: [StyleViolation]) -> String {
return violations.map(generateForSingleViolation).joined(separator: "\n")
violations.map(generateForSingleViolation).joined(separator: "\n")
}
/// Generates a report for a single violation.
@@ -17,7 +17,7 @@ struct XcodeReporter: Reporter {
/// - returns: The report for a single violation.
internal static func generateForSingleViolation(_ violation: StyleViolation) -> String {
// {full_path_to_file}{:line}{:character}: {error,warning}: {content}
return [
[
"\(violation.location): ",
"\(violation.severity.rawValue): ",
"\(violation.ruleName) Violation: ",
@@ -45,8 +45,8 @@ public struct RegexConfiguration<Parent: Rule>: SeverityBasedRuleConfiguration,
/// The `RuleDescription` for the custom rule defined here.
public var description: RuleDescription {
return RuleDescription(identifier: identifier, name: name ?? identifier,
description: "", kind: .style)
RuleDescription(identifier: identifier, name: name ?? identifier,
description: "", kind: .style)
}
/// Create a `RegexConfiguration` with the specified identifier, with other properties to be set later.
+2 -2
View File
@@ -38,7 +38,7 @@ struct CustomRulesConfiguration: RuleConfiguration, CacheDescriptionProvider {
struct CustomRules: Rule, CacheDescriptionProvider {
var cacheDescription: String {
return configuration.cacheDescription
configuration.cacheDescription
}
static let description = RuleDescription(
@@ -92,6 +92,6 @@ struct CustomRules: Rule, CacheDescriptionProvider {
private extension Region {
func isRuleDisabled(customRuleIdentifier: String) -> Bool {
return disabledRuleIdentifiers.contains(RuleIdentifier(customRuleIdentifier))
disabledRuleIdentifiers.contains(RuleIdentifier(customRuleIdentifier))
}
}
@@ -31,7 +31,7 @@ package struct SuperfluousDisableCommandRule: SourceKitFreeRule {
package func validate(file: SwiftLintFile) -> [StyleViolation] {
// This rule is implemented in Linter.swift
return []
[]
}
func reason(for rule: (some Rule).Type) -> String {
@@ -42,6 +42,6 @@ package struct SuperfluousDisableCommandRule: SourceKitFreeRule {
}
func reason(forNonExistentRule rule: String) -> String {
return "'\(rule)' is not a valid SwiftLint rule; remove it from the disable command"
"'\(rule)' is not a valid SwiftLint rule; remove it from the disable command"
}
}