Enable `if_let_shadowing` rule and fix all violations (#4247)

This commit is contained in:
Danny Mösch 2023-01-31 22:31:38 +01:00 committed by GitHub
parent 60610cef84
commit 5eed8fe91b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 75 additions and 78 deletions

View File

@ -33,6 +33,7 @@ opt_in_rules:
- first_where
- flatmap_over_map_reduce
- identical_operands
- if_let_shadowing
- joined_default_parameter
- last_where
- legacy_multiple

View File

@ -55,7 +55,7 @@ extension Configuration {
// MARK: SwiftLint Cache (On-Disk)
internal var cacheDescription: String {
if let computedCacheDescription = computedCacheDescription {
if let computedCacheDescription {
return computedCacheDescription
}

View File

@ -118,7 +118,7 @@ internal extension Configuration.FileGraph.FilePath {
}
private mutating func handleMissingNetwork(urlString: String, cachedFilePath: String?) throws -> String {
if let cachedFilePath = cachedFilePath {
if let cachedFilePath {
queuedPrintError(
"warning: No internet connectivity: Unable to load remote config from \"\(urlString)\". "
+ "Using cached version as a fallback."
@ -139,7 +139,7 @@ internal extension Configuration.FileGraph.FilePath {
taskDone: Bool,
timeout: TimeInterval
) throws -> String {
if let cachedFilePath = cachedFilePath {
if let cachedFilePath {
if taskDone {
queuedPrintError(
"warning: Unable to load remote config from \"\(urlString)\". Using cached version as a fallback."
@ -169,7 +169,7 @@ internal extension Configuration.FileGraph.FilePath {
}
private mutating func handleFileWriteFailure(urlString: String, cachedFilePath: String?) throws -> String {
if let cachedFilePath = cachedFilePath {
if let cachedFilePath {
queuedPrintError("Unable to cache remote config from \"\(urlString)\". Using cached version as a fallback.")
self = .existing(path: cachedFilePath)
return cachedFilePath

View File

@ -29,7 +29,7 @@ internal extension Configuration {
defer { resultingRulesLock.unlock() }
// Return existing value if it's available
if let cachedResultingRules = cachedResultingRules { return cachedResultingRules }
if let cachedResultingRules { return cachedResultingRules }
// Calculate value
let customRulesFilter: (RegexConfiguration) -> (Bool)

View File

@ -89,7 +89,7 @@ public struct SourceKittenDictionary {
/// Returns byte range starting from `offset` with `length` bytes
var byteRange: ByteRange? {
guard let offset = offset, let length = length else { return nil }
guard let offset, let length else { return nil }
return ByteRange(location: offset, length: length)
}

View File

@ -66,7 +66,7 @@ extension SourceKittenDictionary {
/// arguments appears in the view's substructure.
func hasModifier(anyOf modifiers: [SwiftUIModifier], in file: SwiftLintFile) -> Bool {
// SwiftUI ViewModifiers are treated as `call` expressions, and we make sure we can get the expression's name.
guard expressionKind == .call, let name = name else {
guard expressionKind == .call, let name else {
return false
}
@ -169,7 +169,7 @@ extension SourceKittenDictionary {
/// Helper to get the value of an argument.
func getArgumentValue(in file: SwiftLintFile) -> String? {
guard expressionKind == .argument, let bodyByteRange = bodyByteRange else {
guard expressionKind == .argument, let bodyByteRange else {
return nil
}
@ -178,7 +178,7 @@ extension SourceKittenDictionary {
/// Helper to get the value of a single unnamed argument to a function call.
func getSingleUnnamedArgumentValue(in file: SwiftLintFile) -> String? {
guard expressionKind == .call, let bodyByteRange = bodyByteRange else {
guard expressionKind == .call, let bodyByteRange else {
return nil
}

View File

@ -15,7 +15,7 @@ extension SourceKittenDictionary {
guard let range = dictionary.byteRange else {
return
}
if let byteOffset = byteOffset, !range.contains(byteOffset) {
if let byteOffset, !range.contains(byteOffset) {
return
}
if let kind = dictionary.kind {

View File

@ -40,7 +40,7 @@ extension String {
}
internal func substring(from: Int, length: Int? = nil) -> String {
if let length = length {
if let length {
return self[from..<from + length]
}
return String(self[index(startIndex, offsetBy: from, limitedBy: endIndex)!...])

View File

@ -33,7 +33,7 @@ extension SwiftDeclarationAttributeKind {
$0.swiftDeclarationAttributeKinds.contains(where: { $0.rawValue == rawAttribute })
}
if let modifierGroup = modifierGroup {
if let modifierGroup {
self = modifierGroup
} else {
return nil

View File

@ -16,7 +16,7 @@ extension SwiftLintFile {
var regions = [Region]()
var disabledRules = Set<RuleIdentifier>()
let commands: [Command]
if let restrictingRuleIdentifiers = restrictingRuleIdentifiers {
if let restrictingRuleIdentifiers {
commands = self.commands().filter { command in
return command.ruleIdentifiers.contains(where: restrictingRuleIdentifiers.contains)
}
@ -55,7 +55,7 @@ extension SwiftLintFile {
}
internal func commands(in range: NSRange? = nil) -> [Command] {
guard let range = range else {
guard let range else {
return commands
.flatMap { $0.expand() }
}
@ -233,7 +233,7 @@ extension SwiftLintFile {
guard let stringData = string.data(using: .utf8) else {
queuedFatalError("can't encode '\(string)' with UTF8")
}
guard let path = path, let fileHandle = FileHandle(forWritingAtPath: path) else {
guard let path, let fileHandle = FileHandle(forWritingAtPath: path) else {
queuedFatalError("can't write to path '\(String(describing: self.path))'")
}
_ = fileHandle.seekToEndOfFile()
@ -250,7 +250,7 @@ extension SwiftLintFile {
if isVirtual {
return
}
guard let path = path else {
guard let path else {
queuedFatalError("file needs a path to call write(_:)")
}
guard let stringData = String(string).data(using: .utf8) else {

View File

@ -225,7 +225,7 @@ extension FunctionDeclSyntax {
/// How many times this function calls the `super` implementation in its body.
/// Returns 0 if the function has no body.
func numberOfCallsToSuper() -> Int {
guard let body = body else {
guard let body else {
return 0
}

View File

@ -123,7 +123,7 @@ public struct Command: Equatable {
///
/// - returns: The expanded commands.
internal func expand() -> [Command] {
guard let modifier = modifier else {
guard let modifier else {
return [self]
}
switch modifier {

View File

@ -132,7 +132,7 @@ public struct Configuration {
pinnedVersion: String? = nil,
allowZeroLintableFiles: Bool = false
) {
if let pinnedVersion = pinnedVersion, pinnedVersion != Version.current.value {
if let pinnedVersion, pinnedVersion != Version.current.value {
queuedPrintError(
"Currently running SwiftLint \(Version.current.value) but " +
"configuration specified version \(pinnedVersion)."

View File

@ -19,7 +19,7 @@ private extension Rule {
static func superfluousDisableCommandViolations(regions: [Region],
superfluousDisableCommandRule: SuperfluousDisableCommandRule?,
allViolations: [StyleViolation]) -> [StyleViolation] {
guard regions.isNotEmpty, let superfluousDisableCommandRule = superfluousDisableCommandRule else {
guard regions.isNotEmpty, let superfluousDisableCommandRule else {
return []
}
@ -240,7 +240,7 @@ public struct CollectedLinter {
deprecatedToValidIdentifier[key] = value
}
if let cache = cache, let path = file.path {
if let cache, let path = file.path {
cache.cache(violations: violations, forFile: path, configuration: configuration)
}
@ -257,7 +257,7 @@ public struct CollectedLinter {
private func cachedStyleViolations(benchmark: Bool = false) -> ([StyleViolation], [(id: String, time: Double)])? {
let start: Date! = benchmark ? Date() : nil
guard let cache = cache, let file = file.path,
guard let cache, let file = file.path,
let cachedViolations = cache.violations(forFile: file, configuration: configuration) else {
return nil
}
@ -314,7 +314,7 @@ public struct CollectedLinter {
let formattedContents = try? file.file.format(trimmingTrailingWhitespace: true,
useTabs: useTabs,
indentWidth: indentWidth)
if let formattedContents = formattedContents {
if let formattedContents {
file.write(formattedContents)
}
}
@ -323,7 +323,7 @@ public struct CollectedLinter {
configuration: Configuration,
superfluousDisableCommandRule: SuperfluousDisableCommandRule?
) -> [StyleViolation] {
guard regions.isNotEmpty, let superfluousDisableCommandRule = superfluousDisableCommandRule else {
guard regions.isNotEmpty, let superfluousDisableCommandRule else {
return []
}

View File

@ -128,7 +128,7 @@ public final class LinterCache {
return fileCache
}
guard let location = location else {
guard let location else {
return .empty
}

View File

@ -207,7 +207,7 @@ private extension DiscouragedNoneNameRule {
}
}()
guard let type = type else {
guard let type else {
return
}

View File

@ -194,7 +194,7 @@ private extension Line {
/// For "import A.B.C" returns slices [["A", "B", "C"], ["A", "B"], ["A"]]
var importSlices: [ImportSlice] {
guard let importIdentifier = importIdentifier else { return [] }
guard let importIdentifier else { return [] }
let importedSubpathParts = importIdentifier.split(separator: ".").map { String($0) }
guard !importedSubpathParts.isEmpty else { return [] }

View File

@ -225,7 +225,7 @@ private extension ExplicitInitRule {
private extension MemberAccessExprSyntax {
var explicitInitPosition: AbsolutePosition? {
if let base = base, base.isTypeReferenceLike, name.text == "init" {
if let base, base.isTypeReferenceLike, name.text == "init" {
return base.endPositionBeforeTrailingTrivia
} else {
return nil

View File

@ -96,7 +96,7 @@ private extension ExplicitTopLevelACLRule {
}
private func hasViolation(modifiers: ModifierListSyntax?) -> Bool {
guard let modifiers = modifiers else {
guard let modifiers else {
return true
}

View File

@ -182,7 +182,7 @@ private extension RedundantOptionalInitializationRule {
private extension PatternBindingSyntax {
var violationPosition: AbsolutePosition? {
guard let initializer = initializer,
guard let initializer,
let type = typeAnnotation,
initializer.isInitializingToNil,
type.isOptionalType else {

View File

@ -103,7 +103,7 @@ private extension RedundantStringEnumValueRule {
private extension EnumDeclSyntax {
var isStringEnum: Bool {
guard let inheritanceClause = inheritanceClause else {
guard let inheritanceClause else {
return false
}

View File

@ -129,7 +129,7 @@ private extension String {
}
func strippingTrailingSwiftUIPreviewProvider(inheritedTypes: InheritedTypeListSyntax?) -> String {
guard let inheritedTypes = inheritedTypes,
guard let inheritedTypes,
hasSuffix("_Previews"),
let lastPreviewsIndex = lastIndex(of: "_Previews"),
inheritedTypes.typeNames.contains("PreviewProvider") else {

View File

@ -41,7 +41,7 @@ private final class EmptyXCTestMethodRuleVisitor: ViolationsSyntaxVisitor {
private extension FunctionDeclSyntax {
var hasEmptyBody: Bool {
if let body = body {
if let body {
return body.statements.isEmpty
}
return false

View File

@ -99,7 +99,7 @@ struct ExpiringTodoRule: ConfigurationProviderRule, OptInRule {
}
private func violationLevel(for expiryDate: Date?) -> ExpiryViolationLevel? {
guard let expiryDate = expiryDate else {
guard let expiryDate else {
return .badFormatting
}
guard expiryDate.isAfterToday else {

View File

@ -159,7 +159,7 @@ private extension DeclModifierSyntax {
private extension SyntaxProtocol {
func nearestNominalParent() -> Syntax? {
guard let parent = parent else {
guard let parent else {
return nil
}
@ -167,7 +167,7 @@ private extension SyntaxProtocol {
}
func nearestNominalExtensionDeclParent() -> Syntax? {
guard let parent = parent, !parent.isNominalTypeDecl else {
guard let parent, !parent.isNominalTypeDecl else {
return nil
}

View File

@ -53,7 +53,7 @@ struct OrphanedDocCommentRule: SourceKitFreeRule, ConfigurationProviderRule {
.compactMap { first, second in
let firstByteRange = first.range.toSourceKittenByteRange()
guard
let second = second,
let second,
first.kind == .docLineComment || first.kind == .docBlockComment,
second.kind == .lineComment || second.kind == .blockComment,
let firstString = file.stringView.substringWithByteRange(firstByteRange),

View File

@ -244,7 +244,7 @@ private extension SourceKittenDictionary {
}
func aclAtOffset(_ offset: ByteCount) -> AccessControlLevel? {
if let nameOffset = nameOffset,
if let nameOffset,
nameOffset == offset,
let acl = accessibility {
return acl
@ -288,7 +288,7 @@ private extension SourceKittenDictionary {
}
func shouldSkipResultBuilder() -> Bool {
guard let name = name, declarationKind == .functionMethodStatic else {
guard let name, declarationKind == .functionMethodStatic else {
return false
}

View File

@ -257,7 +257,7 @@ private extension SwiftLintFile {
// Operators that are a part of some body are reported as method.static
func mightBeOperator(kind: String?) -> Bool {
guard let kind = kind else { return false }
guard let kind else { return false }
return [
"source.lang.swift.ref.function.operator",
"source.lang.swift.ref.function.method.static"

View File

@ -6,7 +6,7 @@ struct NumberSeparatorConfiguration: SeverityBasedRuleConfiguration, Equatable {
var consoleDescription: String {
let minimumFractionLengthDescription: String
if let minimumFractionLength = minimumFractionLength {
if let minimumFractionLength {
minimumFractionLengthDescription = ", minimum_fraction_length: \(minimumFractionLength)"
} else {
minimumFractionLengthDescription = ", minimum_fraction_length: none"

View File

@ -20,7 +20,7 @@ public struct SeverityLevelsConfiguration: RuleConfiguration, Equatable {
var error: Int?
var params: [RuleParameter<Int>] {
if let error = error {
if let error {
return [RuleParameter(severity: .error, value: error),
RuleParameter(severity: .warning, value: warning)]
}

View File

@ -169,7 +169,7 @@ private extension AttributeListSyntax {
// swiftlint:disable:next cyclomatic_complexity
func makeHelper(locationConverter: SourceLocationConverter) -> RuleHelper? {
guard let parent = parent else {
guard let parent else {
return nil
}

View File

@ -71,7 +71,7 @@ private extension ClosingBraceRule {
private extension TokenSyntax {
var hasClosingBraceViolation: Bool {
guard tokenKind == .rightBrace,
let nextToken = nextToken,
let nextToken,
nextToken.tokenKind == .rightParen
else {
return false

View File

@ -230,7 +230,7 @@ private extension TokenSyntax {
return true
} else if case .newlines = nextToken?.leadingTrivia.first {
return true
} else if let nextToken = nextToken, allowedKinds.contains(nextToken.tokenKind) {
} else if let nextToken, allowedKinds.contains(nextToken.tokenKind) {
return true
} else {
return false

View File

@ -76,7 +76,7 @@ private extension ConditionalReturnsOnNewlineRule {
}
private func isReturn(_ returnStmt: ReturnStmtSyntax?, onTheSameLineAs token: TokenSyntax) -> Bool {
guard let returnStmt = returnStmt else {
guard let returnStmt else {
return false
}

View File

@ -100,7 +100,7 @@ private extension EmptyParenthesesWithTrailingClosureRule {
private extension FunctionCallExprSyntax {
var violationPosition: AbsolutePosition? {
guard trailingClosure != nil,
let leftParen = leftParen,
let leftParen,
argumentList.isEmpty else {
return nil
}

View File

@ -60,7 +60,7 @@ struct FileHeaderRule: ConfigurationProviderRule, OptInRule {
let requiredRegex = configuration.requiredRegex(for: file)
var violationsOffsets = [Int]()
if let firstToken = firstToken, let lastToken = lastToken {
if let firstToken, let lastToken {
let start = firstToken.offset
let length = lastToken.offset + lastToken.length - firstToken.offset
let byteRange = ByteRange(location: start, length: length)

View File

@ -69,7 +69,7 @@ private extension Array where Element == (kind: String, byteRange: ByteRange) {
return last
}
guard let last = last else {
guard let last else {
return nil
}

View File

@ -178,13 +178,9 @@ private extension SourceKittenDictionary {
}
private func kindsAndOffsets(in declarationKinds: [SwiftDeclarationKind]) -> SourceKittenDictionary? {
guard let offset = offset,
let declarationKind = declarationKind,
declarationKinds.contains(declarationKind)
else {
guard let offset, let declarationKind, declarationKinds.contains(declarationKind) else {
return nil
}
return SourceKittenDictionary(["key.kind": declarationKind.rawValue, "key.offset": Int64(offset.value)])
}
}

View File

@ -173,7 +173,7 @@ struct MultilineFunctionChainsRule: ASTRule, OptInRule, ConfigurationProviderRul
let subcalls = dictionary.subcalls
if subcalls.isEmpty, let parentCallName = parentCallName, parentCallName.starts(with: name) {
if subcalls.isEmpty, let parentCallName, parentCallName.starts(with: name) {
return [ByteRange(location: offset, length: length)]
}

View File

@ -155,7 +155,7 @@ extension NumberSeparatorValidator {
private func isInValidRanges(number: String) -> Bool {
let doubleValue = Double(number.replacingOccurrences(of: "_", with: ""))
if let doubleValue = doubleValue, configuration.excludeRanges.contains(where: { $0.contains(doubleValue) }) {
if let doubleValue, configuration.excludeRanges.contains(where: { $0.contains(doubleValue) }) {
return true
}

View File

@ -129,7 +129,7 @@ private struct ArrowViolation {
private extension TokenSyntax {
var arrowViolation: ArrowViolation? {
guard let previousToken = previousToken, let nextToken = nextToken else {
guard let previousToken, let nextToken else {
return nil
}
@ -156,7 +156,7 @@ private extension TokenSyntax {
end = endPosition
}
guard let start = start, let end = end else {
guard let start, let end else {
return nil
}

View File

@ -20,7 +20,7 @@ extension SwiftLint {
func run() async throws {
let allPaths: [String]
if let path = path {
if let path {
queuedPrintError("""
warning: The --path option is deprecated. Pass the path(s) to analyze last to the swiftlint command.
""")

View File

@ -24,7 +24,7 @@ extension SwiftLint {
func run() async throws {
let allPaths: [String]
if let path = path {
if let path {
queuedPrintError("""
warning: The --path option is deprecated. Pass the path(s) to lint last to the swiftlint command.
""")

View File

@ -24,7 +24,7 @@ extension SwiftLint {
var ruleID: String?
func run() throws {
if let ruleID = ruleID {
if let ruleID {
guard let rule = primaryRuleList.list[ruleID] else {
throw SwiftLintError.usageError(description: "No rule with identifier: \(ruleID)")
}
@ -87,7 +87,7 @@ private extension TextTable {
offsetBy: max(minWidth, maxWidth - configurationStartColumn),
limitedBy: stringWithNoNewlines.endIndex
)
if let truncatedEndIndex = truncatedEndIndex {
if let truncatedEndIndex {
return stringWithNoNewlines[..<truncatedEndIndex] + "..."
}
return stringWithNoNewlines

View File

@ -96,7 +96,7 @@ struct LintableFilesVisitor {
self.forceExclude = forceExclude
self.useExcludingByPrefix = useExcludingByPrefix
self.cache = cache
if let compilerInvocations = compilerInvocations {
if let compilerInvocations {
self.mode = .analyze(allCompilerInvocations: compilerInvocations)
// SourceKit had some changes in 5.6 that makes it ~100x more expensive
// to process files concurrently. By processing files serially, it's

View File

@ -22,14 +22,14 @@ struct Signposts {
description = file
}
let signpostID = OSSignpostID(log: log)
if let description = description {
if let description {
os_signpost(.begin, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else {
os_signpost(.begin, log: log, name: name, signpostID: signpostID)
}
let result = try body()
if let description = description {
if let description {
os_signpost(.end, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else {
os_signpost(.end, log: log, name: name, signpostID: signpostID)
@ -53,14 +53,14 @@ struct Signposts {
description = file
}
let signpostID = OSSignpostID(log: log)
if let description = description {
if let description {
os_signpost(.begin, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else {
os_signpost(.begin, log: log, name: name, signpostID: signpostID)
}
let result = try await body()
if let description = description {
if let description {
os_signpost(.end, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else {
os_signpost(.end, log: log, name: name, signpostID: signpostID)

View File

@ -54,7 +54,7 @@ struct SwiftPMCompilationDB: Codable {
.values
.first { $0.sources?.contains(swiftSource) == true }
guard let command = command,
guard let command,
let module = command.module,
let sources = command.sources,
let arguments = command.args,

View File

@ -147,13 +147,13 @@ private func execute(_ args: [String],
let process = Process()
process.launchPath = "/usr/bin/env"
process.arguments = args
if let directory = directory {
if let directory {
process.currentDirectoryPath = directory.path
}
let stdoutPipe = Pipe(), stderrPipe = Pipe()
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
if let input = input {
if let input {
let stdinPipe = Pipe()
process.standardInput = stdinPipe.fileHandleForReading
stdinPipe.fileHandleForWriting.write(input)

View File

@ -11,13 +11,13 @@ class FileNameRuleTests: XCTestCase {
let rule: FileNameRule
if let excluded = excludedOverride {
rule = try FileNameRule(configuration: ["excluded": excluded])
} else if let prefixPattern = prefixPattern, let suffixPattern = suffixPattern {
} else if let prefixPattern, let suffixPattern {
rule = try FileNameRule(configuration: ["prefix_pattern": prefixPattern, "suffix_pattern": suffixPattern])
} else if let prefixPattern = prefixPattern {
} else if let prefixPattern {
rule = try FileNameRule(configuration: ["prefix_pattern": prefixPattern])
} else if let suffixPattern = suffixPattern {
} else if let suffixPattern {
rule = try FileNameRule(configuration: ["suffix_pattern": suffixPattern])
} else if let nestedTypeSeparator = nestedTypeSeparator {
} else if let nestedTypeSeparator {
rule = try FileNameRule(configuration: ["nested_type_separator": nestedTypeSeparator])
} else {
rule = FileNameRule()

View File

@ -206,13 +206,13 @@ class IndentationWidthRuleTests: XCTestCase {
line: UInt = #line
) -> Int {
var configDict: [String: Any] = [:]
if let indentationWidth = indentationWidth {
if let indentationWidth {
configDict["indentation_width"] = indentationWidth
}
if let includeComments = includeComments {
if let includeComments {
configDict["include_comments"] = includeComments
}
if let includeCompilerDirectives = includeCompilerDirectives {
if let includeCompilerDirectives {
configDict["include_compiler_directives"] = includeCompilerDirectives
}

View File

@ -272,7 +272,7 @@ public func makeConfig(_ ruleConfiguration: Any?, _ identifier: String,
let identifiers: Set<String> = skipDisableCommandTests ? [identifier]
: [identifier, superfluousDisableCommandRuleIdentifier]
if let ruleConfiguration = ruleConfiguration, let ruleType = primaryRuleList.list[identifier] {
if let ruleConfiguration, let ruleType = primaryRuleList.list[identifier] {
// The caller has provided a custom configuration for the rule under test
return (try? ruleType.init(configuration: ruleConfiguration)).flatMap { configuredRule in
let rules = skipDisableCommandTests ? [configuredRule] : [configuredRule, SuperfluousDisableCommandRule()]