|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import SwiftSyntax |
| 14 | + |
| 15 | +/// Replace `forEach` with `for-in` loop unless its argument is a function reference. |
| 16 | +/// |
| 17 | +/// Lint: invalid use of `forEach` yield will yield a lint error. |
| 18 | +@_spi(Rules) |
| 19 | +public final class ReplaceForEachWithForLoop : SyntaxLintRule { |
| 20 | + public override func visit(_ node: FunctionCallExprSyntax) -> SyntaxVisitorContinueKind { |
| 21 | + // We are only interested in calls with a single trailing closure |
| 22 | + // argument. |
| 23 | + if !node.arguments.isEmpty || node.trailingClosure == nil || |
| 24 | + !node.additionalTrailingClosures.isEmpty { |
| 25 | + return .visitChildren |
| 26 | + } |
| 27 | + |
| 28 | + guard let member = node.calledExpression.as(MemberAccessExprSyntax.self) else { |
| 29 | + return .visitChildren |
| 30 | + } |
| 31 | + |
| 32 | + guard let memberName = member.declName.baseName.as(TokenSyntax.self), |
| 33 | + memberName.text == "forEach" else { |
| 34 | + return .visitChildren |
| 35 | + } |
| 36 | + |
| 37 | + // If there is another chained member after `.forEach`, |
| 38 | + // let's skip the diagnostic because resulting code might |
| 39 | + // be less understandable. |
| 40 | + if node.parent?.is(MemberAccessExprSyntax.self) == true { |
| 41 | + return .visitChildren |
| 42 | + } |
| 43 | + |
| 44 | + diagnose(.replaceForEachWithLoop(), on: memberName) |
| 45 | + return .visitChildren |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +extension Finding.Message { |
| 50 | + public static func replaceForEachWithLoop() -> Finding.Message { |
| 51 | + "replace use of '.forEach { ... }' with for-in loop" |
| 52 | + } |
| 53 | +} |
0 commit comments