Files
SwiftLint/Source/SwiftLintBuiltInRules/Rules/Performance/FlatMapOverMapReduceRule.swift
T
Danny MöschandGitHub 3f039f26d5 Connect configs with their referencing rules to have some context in error logging (#5017)
With the binding of configurations to their associated rule types
"unknown configuration" errors can be made more specific mentioning
also the rule's identifier in the printed message.
2023-05-19 20:58:24 +02:00

44 lines
1.6 KiB
Swift

import SwiftSyntax
struct FlatMapOverMapReduceRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration<Self>(.warning)
static let description = RuleDescription(
identifier: "flatmap_over_map_reduce",
name: "Flat Map over Map Reduce",
description: "Prefer `flatMap` over `map` followed by `reduce([], +)`",
kind: .performance,
nonTriggeringExamples: [
Example("let foo = bar.map { $0.count }.reduce(0, +)"),
Example("let foo = bar.flatMap { $0.array }")
],
triggeringExamples: [
Example("let foo = ↓bar.map { $0.array }.reduce([], +)")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
}
private extension FlatMapOverMapReduceRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: FunctionCallExprSyntax) {
guard
let memberAccess = node.calledExpression.as(MemberAccessExprSyntax.self),
memberAccess.name.text == "reduce",
node.argumentList.count == 2,
let firstArgument = node.argumentList.first?.expression.as(ArrayExprSyntax.self),
firstArgument.elements.isEmpty,
let secondArgument = node.argumentList.last?.expression.as(IdentifierExprSyntax.self),
secondArgument.identifier.text == "+"
else {
return
}
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
}