Re-enable redundant_self rule (#6368)

This commit is contained in:
Danny Mösch
2025-12-07 14:11:08 +01:00
committed by GitHub
parent d1cdf8ce20
commit 32c33c2588
64 changed files with 197 additions and 200 deletions
+2 -1
View File
@@ -41,7 +41,6 @@ disabled_rules:
- one_declaration_per_file
- prefer_nimble
- prefixed_toplevel_constant
- redundant_self_in_closure
- required_deinit
- sorted_enum_cases
- strict_fileprivate
@@ -86,6 +85,8 @@ identifier_name:
large_tuple: 3
number_separator:
minimum_length: 5
redundant_self:
keep_in_initializers: true
redundant_type_annotation:
consider_default_literal_types_redundant: true
single_test_class: *unit_test_configuration
@@ -26,9 +26,9 @@ private extension DiscouragedOptionalCollectionRule {
private extension SyntaxProtocol {
var isCollectionType: Bool {
self.is(ArrayTypeSyntax.self) ||
self.is(DictionaryTypeSyntax.self) ||
self.as(IdentifierTypeSyntax.self)?.isCollectionType == true
`is`(ArrayTypeSyntax.self) ||
`is`(DictionaryTypeSyntax.self) ||
`as`(IdentifierTypeSyntax.self)?.isCollectionType == true
}
}
@@ -93,7 +93,7 @@ private extension ExplicitEnumRawValueRule {
private extension SyntaxProtocol {
func enclosingEnum() -> EnumDeclSyntax? {
if let node = self.as(EnumDeclSyntax.self) {
if let node = `as`(EnumDeclSyntax.self) {
return node
}
@@ -234,14 +234,14 @@ private extension MemberAccessExprSyntax {
private extension ExprSyntax {
/// `String` or `Nested.Type`.
var isTypeReferenceLike: Bool {
if let expr = self.as(DeclReferenceExprSyntax.self), expr.baseName.text.startsWithUppercase {
if let expr = `as`(DeclReferenceExprSyntax.self), expr.baseName.text.startsWithUppercase {
return true
}
if let expr = self.as(MemberAccessExprSyntax.self),
if let expr = `as`(MemberAccessExprSyntax.self),
expr.description.split(separator: ".").allSatisfy(\.startsWithUppercase) {
return true
}
if let expr = self.as(GenericSpecializationExprSyntax.self)?.expression.as(DeclReferenceExprSyntax.self),
if let expr = `as`(GenericSpecializationExprSyntax.self)?.expression.as(DeclReferenceExprSyntax.self),
expr.baseName.text.startsWithUppercase {
return true
}
@@ -88,13 +88,13 @@ private extension StringLiteralExprSyntax {
private extension ExprSyntax {
var canBeExpressedAsColorLiteralParams: Bool {
if self.is(FloatLiteralExprSyntax.self) ||
self.is(IntegerLiteralExprSyntax.self) ||
self.is(BinaryOperatorExprSyntax.self) {
if `is`(FloatLiteralExprSyntax.self) ||
`is`(IntegerLiteralExprSyntax.self) ||
`is`(BinaryOperatorExprSyntax.self) {
return true
}
if let expr = self.as(SequenceExprSyntax.self) {
if let expr = `as`(SequenceExprSyntax.self) {
return expr.elements.allSatisfy(\.canBeExpressedAsColorLiteralParams)
}
@@ -86,7 +86,7 @@ private extension InfixOperatorExprSyntax {
if let asExpr = leftOperand.as(AsExprSyntax.self) ?? rightOperand.as(AsExprSyntax.self),
asExpr.questionOrExclamationMark?.tokenKind == .postfixQuestionMark,
!asExpr.type.is(OptionalTypeSyntax.self),
self.operator.as(BinaryOperatorExprSyntax.self)?.operator.tokenKind == .binaryOperator("!="),
`operator`.as(BinaryOperatorExprSyntax.self)?.operator.tokenKind == .binaryOperator("!="),
rightOperand.is(NilLiteralExprSyntax.self) || leftOperand.is(NilLiteralExprSyntax.self) {
asExpr
} else {
@@ -60,10 +60,10 @@ private extension AttributeListSyntax {
private extension Syntax {
var isFunctionOrStoredProperty: Bool {
if self.is(FunctionDeclSyntax.self) {
if `is`(FunctionDeclSyntax.self) {
return true
}
if let variableDecl = self.as(VariableDeclSyntax.self),
if let variableDecl = `as`(VariableDeclSyntax.self),
variableDecl.bindings.allSatisfy({ $0.accessorBlock == nil }) {
return true
}
@@ -71,10 +71,10 @@ private extension Syntax {
}
var functionOrVariableModifiers: DeclModifierListSyntax? {
if let functionDecl = self.as(FunctionDeclSyntax.self) {
if let functionDecl = `as`(FunctionDeclSyntax.self) {
return functionDecl.modifiers
}
if let variableDecl = self.as(VariableDeclSyntax.self) {
if let variableDecl = `as`(VariableDeclSyntax.self) {
return variableDecl.modifiers
}
return nil
@@ -110,7 +110,7 @@ private extension RedundantSetAccessControlRule {
private extension SyntaxProtocol {
func closestDecl() -> DeclSyntax? {
if let decl = self.parent?.as(DeclSyntax.self) {
if let decl = parent?.as(DeclSyntax.self) {
return decl
}
@@ -120,7 +120,7 @@ private extension SyntaxProtocol {
private extension DeclSyntax {
var modifiers: DeclModifierListSyntax? {
self.asProtocol((any WithModifiersSyntax).self)?.modifiers
asProtocol((any WithModifiersSyntax).self)?.modifiers
}
}
@@ -54,11 +54,11 @@ private extension ReturnValueFromVoidFunctionRule {
private extension Syntax {
func enclosingFunction() -> FunctionDeclSyntax? {
if let node = self.as(FunctionDeclSyntax.self) {
if let node = `as`(FunctionDeclSyntax.self) {
return node
}
if self.is(ClosureExprSyntax.self) || self.is(VariableDeclSyntax.self) || self.is(InitializerDeclSyntax.self) {
if `is`(ClosureExprSyntax.self) || `is`(VariableDeclSyntax.self) || `is`(InitializerDeclSyntax.self) {
return nil
}
@@ -204,7 +204,7 @@ private extension SwiftLintFile {
}
func captureListVariables(compilerArguments: [String]) -> Set<CaptureVariableRule.Variable> {
let offsets = self.captureListVariableOffsets()
let offsets = captureListVariableOffsets()
guard !offsets.isEmpty, let indexEntities = index(compilerArguments: compilerArguments) else { return Set() }
return Set(indexEntities.traverseEntitiesDepthFirst { _, entity in
@@ -243,7 +243,7 @@ private extension SwiftLintFile {
}
func declaredVariables(compilerArguments: [String]) -> Set<CaptureVariableRule.USR> {
let offsets = self.declaredVariableOffsets()
let offsets = declaredVariableOffsets()
guard !offsets.isEmpty, let indexEntities = index(compilerArguments: compilerArguments) else { return Set() }
return Set(indexEntities.traverseEntitiesDepthFirst { _, entity in
@@ -261,7 +261,7 @@ private extension SwiftLintFile {
func index(compilerArguments: [String]) -> SourceKittenDictionary? {
guard
let path = self.path,
let path,
let response = try? Request.index(file: path, arguments: compilerArguments).sendIfNotDisabled()
else {
Issue.indexingError(path: path, ruleID: CaptureVariableRule.identifier).print()
@@ -116,19 +116,19 @@ private struct DictionaryKey {
private extension ExprSyntax {
var stringContent: String? {
if let string = self.as(StringLiteralExprSyntax.self) {
if let string = `as`(StringLiteralExprSyntax.self) {
return string.description
}
if let int = self.as(IntegerLiteralExprSyntax.self) {
if let int = `as`(IntegerLiteralExprSyntax.self) {
return int.description
}
if let float = self.as(FloatLiteralExprSyntax.self) {
if let float = `as`(FloatLiteralExprSyntax.self) {
return float.description
}
if let memberAccess = self.as(MemberAccessExprSyntax.self) {
if let memberAccess = `as`(MemberAccessExprSyntax.self) {
return memberAccess.description
}
if let identifier = self.as(DeclReferenceExprSyntax.self) {
if let identifier = `as`(DeclReferenceExprSyntax.self) {
return identifier.baseName.text
}
@@ -166,10 +166,10 @@ private extension WithAttributesSyntax where Self: WithModifiersSyntax {
private extension TypeSyntax {
var isSendable: Bool {
if let identifierType = self.as(IdentifierTypeSyntax.self) {
if let identifierType = `as`(IdentifierTypeSyntax.self) {
return identifierType.name.text == "Sendable"
}
if let compositeType = self.as(CompositionTypeSyntax.self) {
if let compositeType = `as`(CompositionTypeSyntax.self) {
return compositeType.elements.contains(where: \.type.isSendable)
}
return false
@@ -166,14 +166,14 @@ private extension SyntaxProtocol {
private extension Syntax {
var isNominalTypeDecl: Bool {
self.is(StructDeclSyntax.self) ||
self.is(ClassDeclSyntax.self) ||
self.is(ActorDeclSyntax.self) ||
self.is(EnumDeclSyntax.self)
`is`(StructDeclSyntax.self) ||
`is`(ClassDeclSyntax.self) ||
`is`(ActorDeclSyntax.self) ||
`is`(EnumDeclSyntax.self)
}
var isExtensionDecl: Bool {
self.is(ExtensionDeclSyntax.self)
`is`(ExtensionDeclSyntax.self)
}
var modifiers: DeclModifierListSyntax? {
@@ -55,13 +55,13 @@ private extension NSLocalizedStringKeyRule {
private extension ExprSyntax {
var hasViolation: Bool {
if let strExpr = self.as(StringLiteralExprSyntax.self) {
if let strExpr = `as`(StringLiteralExprSyntax.self) {
return strExpr.segments.contains { segment in
!segment.is(StringSegmentSyntax.self)
}
}
if let sequenceExpr = self.as(SequenceExprSyntax.self) {
if let sequenceExpr = `as`(SequenceExprSyntax.self) {
return sequenceExpr.elements.contains { expr in
if expr.is(BinaryOperatorExprSyntax.self) {
return false
@@ -135,7 +135,7 @@ private final class IdentifierUsageVisitor: SyntaxVisitor {
private extension SyntaxProtocol {
func closestDecl() -> DeclSyntax? {
if let decl = self.parent?.as(DeclSyntax.self) {
if let decl = parent?.as(DeclSyntax.self) {
return decl
}
@@ -20,13 +20,13 @@ private extension UnneededOverrideRule {
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> {
override func visitPost(_ node: FunctionDeclSyntax) {
if node.isUnneededOverride(excludedMethods: configuration.excludedMethods) {
self.violations.append(node.positionAfterSkippingLeadingTrivia)
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
override func visitPost(_ node: InitializerDeclSyntax) {
if configuration.affectInits, node.isUnneededOverride {
self.violations.append(node.positionAfterSkippingLeadingTrivia)
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
}
@@ -99,7 +99,7 @@ private final class IdentifierReferenceVisitor: SyntaxVisitor {
private extension String {
var removingDollarsAndBackticks: String {
self.replacingOccurrences(of: "$", with: "")
replacingOccurrences(of: "$", with: "")
.replacingOccurrences(of: "`", with: "")
}
}
@@ -178,7 +178,7 @@ private extension SwiftLintFile {
}
}
let cursorInfo = self.cursorInfo(at: nameOffset, compilerArguments: compilerArguments)
let cursorInfo = cursorInfo(at: nameOffset, compilerArguments: compilerArguments)
if cursorInfo?.annotatedDeclaration?.contains("@objc ") == true {
return nil
@@ -282,7 +282,7 @@ private extension SourceKittenDictionary {
}
func shouldSkipIndexEntityToWorkAroundSR11985() -> Bool {
guard enclosedSwiftAttributes.contains(.objcName), let name = self.name else {
guard enclosedSwiftAttributes.contains(.objcName), let name else {
return false
}
@@ -214,14 +214,13 @@ private extension SwiftLintFile {
}
let operatorEntities = flatEntities(entity: index).filter { mightBeOperator(kind: $0.kind) }
let offsetPerLine = self.offsetPerLine()
let offsetPerLine = offsetPerLine()
var imports = Set<String>()
for entity in operatorEntities {
if
let line = entity.line,
let column = entity.column,
let lineOffset = offsetPerLine[Int(line) - 1] {
if let line = entity.line,
let column = entity.column,
let lineOffset = offsetPerLine[Int(line) - 1] {
let offset = lineOffset + column - 1
// Filter already processed tokens such as static methods that are not operators
@@ -170,10 +170,10 @@ private final class NewValueUsageVisitor: SyntaxVisitor {
private extension Syntax {
func closestVariableOrSubscript() -> Either<SubscriptDeclSyntax, VariableDeclSyntax>? {
if let subscriptDecl = self.as(SubscriptDeclSyntax.self) {
if let subscriptDecl = `as`(SubscriptDeclSyntax.self) {
return .left(subscriptDecl)
}
if let variableDecl = self.as(VariableDeclSyntax.self) {
if let variableDecl = `as`(VariableDeclSyntax.self) {
return .right(variableDecl)
}
@@ -88,10 +88,10 @@ private extension WeakDelegateRule {
private extension Syntax {
func enclosingClass() -> ClassDeclSyntax? {
if let classExpr = self.as(ClassDeclSyntax.self) {
if let classExpr = `as`(ClassDeclSyntax.self) {
return classExpr
}
if self.as(DeclSyntax.self) != nil {
if `as`(DeclSyntax.self) != nil {
return nil
}
@@ -168,7 +168,7 @@ private extension EmptyCountRule {
private extension ExprSyntax {
var isNonLocalCountIdentifier: Bool {
guard let declRef = self.as(DeclReferenceExprSyntax.self),
guard let declRef = `as`(DeclReferenceExprSyntax.self),
declRef.argumentNames == nil,
declRef.baseName.tokenKind == .identifier("count") else {
return false
@@ -183,7 +183,7 @@ private extension ExprSyntax {
}
func countCallPosition(onlyAfterDot: Bool) -> AbsolutePosition? {
if let expr = self.as(MemberAccessExprSyntax.self) {
if let expr = `as`(MemberAccessExprSyntax.self) {
if expr.declName.argumentNames == nil, expr.declName.baseName.tokenKind == .identifier("count") {
return expr.declName.baseName.positionAfterSkippingLeadingTrivia
}
@@ -224,8 +224,7 @@ private extension ExprSyntaxProtocol {
private extension SyntaxProtocol {
func withTrivia(from node: some SyntaxProtocol) -> Self {
self
.with(\.leadingTrivia, node.leadingTrivia)
with(\.leadingTrivia, node.leadingTrivia)
.with(\.trailingTrivia, node.trailingTrivia)
}
}
@@ -244,7 +243,7 @@ private extension InfixOperatorExprSyntax {
}
var binaryOperator: String? {
self.operator.as(BinaryOperatorExprSyntax.self)?.operator.binaryOperator
`operator`.as(BinaryOperatorExprSyntax.self)?.operator.binaryOperator
}
}
@@ -52,10 +52,10 @@ private extension FirstWhereRule {
private extension ExprSyntax {
var shouldSkip: Bool {
if self.is(StringLiteralExprSyntax.self) {
if `is`(StringLiteralExprSyntax.self) {
return true
}
if let functionCall = self.as(FunctionCallExprSyntax.self),
if let functionCall = `as`(FunctionCallExprSyntax.self),
let calledExpression = functionCall.calledExpression.as(DeclReferenceExprSyntax.self),
calledExpression.baseName.text == "NSPredicate" {
return true
@@ -48,10 +48,10 @@ private extension LastWhereRule {
private extension ExprSyntax {
var shouldSkip: Bool {
if self.is(StringLiteralExprSyntax.self) {
if `is`(StringLiteralExprSyntax.self) {
return true
}
if let functionCall = self.as(FunctionCallExprSyntax.self),
if let functionCall = `as`(FunctionCallExprSyntax.self),
let calledExpression = functionCall.calledExpression.as(DeclReferenceExprSyntax.self),
calledExpression.baseName.text == "NSPredicate" {
return true
@@ -141,13 +141,11 @@ private extension FunctionCallExprSyntax {
private extension ExprSyntax {
var isCopyOnWriteType: Bool {
if self.is(StringLiteralExprSyntax.self) ||
self.is(DictionaryExprSyntax.self) ||
self.is(ArrayExprSyntax.self) {
if `is`(StringLiteralExprSyntax.self) || `is`(DictionaryExprSyntax.self) || `is`(ArrayExprSyntax.self) {
return true
}
if let expr = self.as(FunctionCallExprSyntax.self) {
if let expr = `as`(FunctionCallExprSyntax.self) {
if let identifierExpr = expr.calledExpression.identifierExpr {
return identifierExpr.isCopyOnWriteType
}
@@ -165,10 +163,10 @@ private extension ExprSyntax {
}
var identifierExpr: DeclReferenceExprSyntax? {
if let identifierExpr = self.as(DeclReferenceExprSyntax.self) {
if let identifierExpr = `as`(DeclReferenceExprSyntax.self) {
return identifierExpr
}
if let specializeExpr = self.as(GenericSpecializationExprSyntax.self) {
if let specializeExpr = `as`(GenericSpecializationExprSyntax.self) {
return specializeExpr.expression.identifierExpr
}
@@ -61,7 +61,7 @@ struct NameConfiguration<Parent: Rule>: RuleConfiguration, InlinableOptionType {
try maxLength.apply(configuration: maxLengthConfiguration)
}
if let excluded = [String].array(of: configurationDict[$excludedRegularExpressions.key]) {
self.excludedRegularExpressions = Set(excluded.compactMap {
excludedRegularExpressions = Set(excluded.compactMap {
try? RegularExpression(pattern: "^\($0)$")
})
}
@@ -176,8 +176,7 @@ private struct RuleHelper {
private extension AttributeListSyntax {
func attributesAndPlacements(configuration: AttributesConfiguration, shouldBeOnSameLine: Bool)
-> [(AttributeSyntax, AttributePlacement)] {
self
.children(viewMode: .sourceAccurate)
children(viewMode: .sourceAccurate)
.compactMap { $0.as(AttributeSyntax.self) }
.map { attribute in
let atPrefixedName = "@\(attribute.attributeNameText)"
@@ -169,7 +169,7 @@ private extension ControlStatementRule {
private extension ExprSyntax {
var unwrapped: ExprSyntax? {
if let expr = self.as(TupleExprSyntax.self)?.elements.onlyElement?.expression {
if let expr = `as`(TupleExprSyntax.self)?.elements.onlyElement?.expression {
return containsTrailingClosure(Syntax(expr)) ? nil : expr
}
return nil
@@ -151,7 +151,7 @@ private extension EmptyEnumArgumentsRule {
private extension PatternSyntax {
func emptyEnumArgumentsViolation(rewrite: Bool) -> (position: AbsolutePosition, pattern: PatternSyntax)? {
guard
var pattern = self.as(ExpressionPatternSyntax.self),
var pattern = `as`(ExpressionPatternSyntax.self),
let expression = pattern.expression.as(FunctionCallExprSyntax.self),
expression.argumentsHasViolation,
let calledExpression = expression.calledExpression.as(MemberAccessExprSyntax.self),
@@ -195,8 +195,7 @@ private extension FunctionCallExprSyntax {
if arguments.allSatisfy({ $0.expression.is(DiscardAssignmentExprSyntax.self) }) {
let newCalledExpression = calledExpression
.with(\.trailingTrivia, rightParen?.trailingTrivia ?? Trivia())
let newExpression = self
.with(\.calledExpression, ExprSyntax(newCalledExpression))
let newExpression = with(\.calledExpression, ExprSyntax(newCalledExpression))
.with(\.leftParen, nil)
.with(\.arguments, [])
.with(\.rightParen, nil)
@@ -216,8 +215,7 @@ private extension FunctionCallExprSyntax {
private extension ExprSyntax {
var isDiscardAssignmentOrFunction: Bool {
self.is(DiscardAssignmentExprSyntax.self) ||
(self.as(FunctionCallExprSyntax.self)?.argumentsHasViolation == true)
`is`(DiscardAssignmentExprSyntax.self) || (`as`(FunctionCallExprSyntax.self)?.argumentsHasViolation == true)
}
}
@@ -20,22 +20,22 @@ struct FileTypesOrderRule: OptInRule {
guard let mainTypeSubstructure = mainTypeSubstructure(in: file),
let mainTypeSubstuctureOffset = mainTypeSubstructure.offset else { return [] }
let extensionsSubstructures = self.extensionsSubstructures(
let extensionsSubstructures = extensionsSubstructures(
in: file,
mainTypeSubstructure: mainTypeSubstructure
)
let supportingTypesSubstructures = self.supportingTypesSubstructures(
let supportingTypesSubstructures = supportingTypesSubstructures(
in: file,
mainTypeSubstructure: mainTypeSubstructure
)
let previewProviderSubstructures = self.substructures(
let previewProviderSubstructures = substructures(
in: file,
withInheritedType: "PreviewProvider"
)
let libraryContentSubstructures = self.substructures(
let libraryContentSubstructures = substructures(
in: file,
withInheritedType: "LibraryContentProvider"
)
@@ -133,13 +133,13 @@ struct FileTypesOrderRule: OptInRule {
let dict = file.structureDictionary
guard let filePath = file.path else {
return self.mainTypeSubstructure(in: dict)
return mainTypeSubstructure(in: dict)
}
let fileName = URL(fileURLWithPath: filePath, isDirectory: false)
.lastPathComponent.replacingOccurrences(of: ".swift", with: "")
guard let mainTypeSubstructure = dict.substructure.first(where: { $0.name == fileName }) else {
return self.mainTypeSubstructure(in: file.structureDictionary)
return mainTypeSubstructure(in: file.structureDictionary)
}
// specify type with name matching the files name as main type
@@ -167,7 +167,7 @@ struct FileTypesOrderRule: OptInRule {
private extension SourceKittenDictionary {
var hasExcludedInheritedType: Bool {
self.inheritedTypes.contains { inheritedType in
inheritedTypes.contains { inheritedType in
inheritedType == "PreviewProvider" || inheritedType == "LibraryContentProvider"
}
}
@@ -175,7 +175,7 @@ private extension SourceKittenDictionary {
private extension Array where Element == SourceKittenDictionary {
func offsets(for fileType: FileTypesOrderConfiguration.FileType) -> [FileTypeOffset] {
self.compactMap { substructure in
compactMap { substructure in
guard let offset = substructure.offset else { return nil }
return (fileType, offset)
}
@@ -40,7 +40,7 @@ private extension ImplicitOptionalInitializationRule {
return super.visit(node)
}
self.numberOfCorrections += 1
numberOfCorrections += 1
return switch configuration.style {
case .never:
@@ -103,7 +103,7 @@ extension SwitchCaseAlignmentRule {
}
private var indentedCases: [Example] {
let violationMarker = indentedCasesOption ? "" : self.violationMarker
let violationMarker = indentedCasesOption ? "" : violationMarker
return [
Example("""
@@ -144,7 +144,7 @@ extension SwitchCaseAlignmentRule {
}
private var nonIndentedCases: [Example] {
let violationMarker = indentedCasesOption ? self.violationMarker : ""
let violationMarker = indentedCasesOption ? violationMarker : ""
return [
Example("""
@@ -180,15 +180,13 @@ private extension FunctionCallExprSyntax {
}
func dropLastArgument() -> Self {
self
.with(\.arguments, LabeledExprListSyntax(arguments.dropLast()).dropLastTrailingComma())
with(\.arguments, LabeledExprListSyntax(arguments.dropLast()).dropLastTrailingComma())
.dropParensIfEmpty()
}
func dropParensIfEmpty() -> Self {
if arguments.isEmpty {
self
.with(\.rightParen, nil)
with(\.rightParen, nil)
.with(\.leftParen, nil)
} else {
self
@@ -321,7 +321,7 @@ private extension String {
func trailingWhitespaceInfo() -> TrailingWhitespaceInfo? {
var charCount = 0
var byteLen = 0
for char in self.reversed() {
for char in reversed() {
if char.isWhitespace, char == " " || char == "\t" { // Only count spaces and tabs
charCount += 1
byteLen += char.utf8.count
@@ -52,10 +52,10 @@ private extension UnusedOptionalBindingRule {
private extension ExprSyntax {
var isDiscardExpression: Bool {
if self.is(DiscardAssignmentExprSyntax.self) {
if `is`(DiscardAssignmentExprSyntax.self) {
return true
}
if let tuple = self.as(TupleExprSyntax.self) {
if let tuple = `as`(TupleExprSyntax.self) {
return tuple.elements.allSatisfy(\.expression.isDiscardExpression)
}
@@ -20,7 +20,7 @@ struct VerticalWhitespaceClosingBracesRule: CorrectableRule, OptInRule {
private let trivialLinePattern = "((?:\\n[ \\t]*)+)(\\n[ \\t)}\\]]*$)"
func validate(file: SwiftLintFile) -> [StyleViolation] {
let pattern = configuration.onlyEnforceBeforeTrivialLines ? self.trivialLinePattern : self.pattern
let pattern = configuration.onlyEnforceBeforeTrivialLines ? trivialLinePattern : pattern
let patternRegex: NSRegularExpression = regex(pattern)
@@ -39,7 +39,7 @@ struct VerticalWhitespaceClosingBracesRule: CorrectableRule, OptInRule {
}
func correct(file: SwiftLintFile) -> Int {
let pattern = configuration.onlyEnforceBeforeTrivialLines ? self.trivialLinePattern : self.pattern
let pattern = configuration.onlyEnforceBeforeTrivialLines ? trivialLinePattern : pattern
let violatingRanges = file.ruleEnabled(violatingRanges: file.violatingRanges(for: pattern), for: self)
guard violatingRanges.isNotEmpty else {
return 0
@@ -123,7 +123,7 @@ private extension VerticalWhitespaceRule {
consecutiveNewlines += count
if count > linesToPreserve {
self.numberOfCorrections += count - linesToPreserve
numberOfCorrections += count - linesToPreserve
}
if linesToPreserve > 0 {
@@ -32,14 +32,9 @@ public extension SourceKittenDictionary {
/// - Parameter file: File this structure occurs in
/// - Returns: The content of the file which this `SourceKittenDictionary` structure represents
func content(in file: SwiftLintFile) -> String? {
guard
let byteRange = self.byteRange,
let range = file.stringView.byteRangeToNSRange(byteRange)
else {
guard let byteRange, let range = file.stringView.byteRangeToNSRange(byteRange) else {
return nil
}
let body = file.stringView.nsString.substring(with: range)
return String(body)
return String(file.stringView.nsString.substring(with: range))
}
}
@@ -74,7 +74,7 @@ public extension String {
}
var isFile: Bool {
if self.isEmpty {
if isEmpty {
return false
}
var isDirectoryObjC: ObjCBool = false
@@ -88,9 +88,7 @@ public extension String {
/// - Parameter character: Character to count
/// - Returns: Number of times `character` occurs in `self`
func countOccurrences(of character: Character) -> Int {
self.reduce(0, {
$1 == character ? $0 + 1 : $0
})
reduce(0) { $1 == character ? $0 + 1 : $0 }
}
/// If self is a path, this method can be used to get a path expression relative to a root directory
@@ -99,7 +99,7 @@ public extension SwiftDeclarationAttributeKind {
}
public var debugDescription: String {
self.rawValue
rawValue
}
}
}
@@ -142,7 +142,7 @@ extension SwiftLintFile {
queuedFatalError("can't encode '\(string)' with UTF8")
}
guard let path, let fileHandle = FileHandle(forWritingAtPath: path) else {
queuedFatalError("can't write to path '\(String(describing: self.path))'")
queuedFatalError("can't write to path '\(String(describing: path))'")
}
_ = fileHandle.seekToEndOfFile()
fileHandle.write(stringData)
@@ -65,10 +65,10 @@ public extension ClassDeclSyntax {
public extension ExprSyntax {
var asFunctionCall: FunctionCallExprSyntax? {
if let functionCall = self.as(FunctionCallExprSyntax.self) {
if let functionCall = `as`(FunctionCallExprSyntax.self) {
return functionCall
}
if let tuple = self.as(TupleExprSyntax.self),
if let tuple = `as`(TupleExprSyntax.self),
let firstElement = tuple.elements.onlyElement,
let functionCall = firstElement.expression.as(FunctionCallExprSyntax.self) {
return functionCall
@@ -216,7 +216,7 @@ public extension FunctionDeclSyntax {
/// Returns the signature including arguments, e.g "setEditing(_:animated:)"
var resolvedName: String {
var name = self.name.text
var name = name.text
name += "("
let params = signature.parameterClause.parameters.compactMap { param in
@@ -2,7 +2,7 @@ import Foundation
public extension URL {
var filepath: String {
self.withUnsafeFileSystemRepresentation { String(cString: $0!) }
withUnsafeFileSystemRepresentation { String(cString: $0!) }
}
var isSwiftFile: Bool {
+1 -1
View File
@@ -234,7 +234,7 @@ public extension SubstitutionCorrectableRule {
var contents = file.contents
for range in violatingRanges.sorted(by: { $0.location > $1.location }) {
let contentsNSString = contents.bridge()
if let (rangeToRemove, substitution) = self.substitution(for: range, in: file) {
if let (rangeToRemove, substitution) = substitution(for: range, in: file) {
contents = contentsNSString.replacingCharacters(in: rangeToRemove, with: substitution)
numberOfCorrections += 1
}
@@ -114,10 +114,10 @@ public struct RegexConfiguration<Parent: Rule>: SeverityBasedRuleConfiguration,
guard let mode = ExecutionMode(rawValue: modeString) else {
throw Issue.invalidConfiguration(ruleID: Parent.identifier)
}
self.executionMode = mode
executionMode = mode
}
self.excludedMatchKinds = try self.excludedMatchKinds(from: configurationDict)
excludedMatchKinds = try excludedMatchKinds(from: configurationDict)
}
public func hash(into hasher: inout Hasher) {
@@ -42,14 +42,14 @@ public struct SeverityLevelsConfiguration<Parent: Rule>: RuleConfiguration, Inli
}
if let errorValue = configDict[$error.key] {
if errorValue == nil {
self.error = nil
error = nil
} else if let error = errorValue as? Int {
self.error = error
} else {
throw .invalidConfiguration(ruleID: Parent.identifier)
}
} else if warningValue != nil {
self.error = nil
error = nil
}
} else {
throw .nothingApplied(ruleID: Parent.identifier)
@@ -55,7 +55,7 @@ extension Configuration {
}
let pathsForPath = includedPaths.isEmpty ? fileManager.filesToLint(inPath: path, rootDirectory: nil) : []
let includedPaths = self.includedPaths
let includedPaths = includedPaths
.flatMap(Glob.resolveGlob)
.parallelFlatMap { fileManager.filesToLint(inPath: $0, rootDirectory: rootDirectory) }
@@ -98,7 +98,7 @@ extension Configuration {
/// - returns: The input paths after removing the excluded paths.
public func filterExcludedPathsByPrefix(in paths: [String]...) -> [String] {
let allPaths = paths.flatMap(\.self)
let excludedPaths = self.excludedPaths
let excludedPaths = excludedPaths
.parallelFlatMap { @Sendable in Glob.resolveGlob($0) }
.map { $0.absolutePathStandardized() }
return allPaths.filter { path in
@@ -10,7 +10,7 @@ extension Configuration {
withChild childConfiguration: Configuration,
rootDirectory: String = ""
) -> Configuration {
let mergedIncludedAndExcluded = self.mergedIncludedAndExcluded(
let mergedIncludedAndExcluded = mergedIncludedAndExcluded(
with: childConfiguration,
rootDirectory: rootDirectory
)
@@ -151,7 +151,7 @@ internal extension Configuration {
let newAllRulesWrapped = mergedAllRulesWrapped(with: child)
// Merge mode
let validRuleIdentifiers = self.validRuleIdentifiers.union(child.validRuleIdentifiers)
let validRuleIdentifiers = validRuleIdentifiers.union(child.validRuleIdentifiers)
let newMode: RulesMode
switch child.mode {
case let .defaultConfiguration(childDisabled, childOptIn):
@@ -429,8 +429,8 @@ extension LintOrAnalyzeOptions {
// Config file settings can be overridden by either `--strict` or `--lenient` command line options.
func leniency(strict configurationStrict: Bool, lenient configurationLenient: Bool) -> Leniency {
let strict = self.strict || (configurationStrict && !self.lenient)
let lenient = self.lenient || (configurationLenient && !self.strict)
let strict = strict || (configurationStrict && !lenient)
let lenient = lenient || (configurationLenient && !self.strict)
return Leniency(strict: strict, lenient: lenient)
}
}
@@ -100,7 +100,7 @@ struct LintableFilesVisitor {
}
func shouldSkipFile(atPath path: String?) -> Bool {
switch self.mode {
switch mode {
case .lint:
return false
case let .analyze(compilerInvocations):
@@ -110,7 +110,7 @@ struct LintableFilesVisitor {
}
func linter(forFile file: SwiftLintFile, configuration: Configuration) -> Linter {
switch self.mode {
switch mode {
case .lint:
return Linter(file: file, configuration: configuration, cache: cache)
case let .analyze(compilerInvocations):
@@ -122,7 +122,7 @@ struct LintableFilesVisitor {
private static func loadCompilerInvocations(_ options: LintOrAnalyzeOptions)
throws(SwiftLintError) -> CompilerInvocations {
if let path = options.compilerLogPath {
guard let compilerInvocations = self.loadLogCompilerInvocations(path) else {
guard let compilerInvocations = loadLogCompilerInvocations(path) else {
throw .usageError(description: "Could not read compiler log at path: '\(path)'")
}
@@ -130,7 +130,7 @@ struct LintableFilesVisitor {
}
if let path = options.compileCommands {
do {
return .compilationDatabase(compileCommands: try self.loadCompileCommands(path))
return .compilationDatabase(compileCommands: try loadCompileCommands(path))
} catch {
throw .usageError(
description: "Could not read compilation database at path: '\(path)' \(error.localizedDescription)"
@@ -352,7 +352,7 @@ public struct CollectedLinter {
superfluousDisableCommandRule: superfluousDisableCommandRule,
compilerArguments: compilerArguments)
}
let undefinedSuperfluousCommandViolations = self.undefinedSuperfluousCommandViolations(
let undefinedSuperfluousCommandViolations = undefinedSuperfluousCommandViolations(
regions: regions, configuration: configuration,
superfluousDisableCommandRule: superfluousDisableCommandRule)
@@ -106,7 +106,7 @@ private extension TextTable {
private extension String {
func leftPadded(forHeader header: String) -> String {
let headerCount = header.count - self.count
let headerCount = header.count - count
if headerCount > 0 {
return String(repeating: " ", count: headerCount) + self
}
@@ -5,7 +5,7 @@ import XCTest
final class ContainsOverFirstNotNilRuleTests: SwiftLintTestCase {
func testFirstReason() {
let example = Example("↓myList.first { $0 % 2 == 0 } != nil")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer `contains` over `first(where:) != nil`")
@@ -13,7 +13,7 @@ final class ContainsOverFirstNotNilRuleTests: SwiftLintTestCase {
func testFirstIndexReason() {
let example = Example("↓myList.firstIndex { $0 % 2 == 0 } != nil")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer `contains` over `firstIndex(where:) != nil`")
@@ -5,7 +5,7 @@ import XCTest
final class DeploymentTargetRuleTests: SwiftLintTestCase {
func testMacOSAttributeReason() {
let example = Example("@available(macOS 10.11, *)\nclass A {}")
let violations = self.violations(example, config: ["macOS_deployment_target": "10.14.0"])
let violations = violations(example, config: ["macOS_deployment_target": "10.14.0"])
let expectedMessage = "Availability attribute is using a version (10.11) that is satisfied by " +
"the deployment target (10.14) for platform macOS"
@@ -15,7 +15,7 @@ final class DeploymentTargetRuleTests: SwiftLintTestCase {
func testWatchOSConditionReason() {
let example = Example("if #available(watchOS 4, *) {}")
let violations = self.violations(example, config: ["watchOS_deployment_target": "5.0.1"])
let violations = violations(example, config: ["watchOS_deployment_target": "5.0.1"])
let expectedMessage = "Availability condition is using a version (4) that is satisfied by " +
"the deployment target (5.0.1) for platform watchOS"
@@ -27,7 +27,7 @@ final class DeploymentTargetRuleTests: SwiftLintTestCase {
try XCTSkipUnless(SwiftVersion.current >= .fiveDotSix)
let example = Example("if #unavailable(iOS 14) { legacyImplementation() }")
let violations = self.violations(example, config: ["iOS_deployment_target": "15.0"])
let violations = violations(example, config: ["iOS_deployment_target": "15.0"])
let expectedMessage = "Availability negative condition is using a version (14) that is satisfied by " +
"the deployment target (15.0) for platform iOS"
@@ -9,21 +9,21 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
func testExpiredTodo() {
let example = Example("fatalError() // TODO: [\(dateString(for: .expired))] Implement")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODO/FIXME has expired and must be resolved")
}
func testExpiredFixMe() {
let example = Example("fatalError() // FIXME: [\(dateString(for: .expired))] Implement")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODO/FIXME has expired and must be resolved")
}
func testApproachingExpiryTodo() {
let example = Example("fatalError() // TODO: [\(dateString(for: .approachingExpiry))] Implement")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODO/FIXME is approaching its expiry and should be resolved soon")
}
@@ -38,7 +38,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
dateDelimiters: .init(opening: "<", closing: ">")
)
let example = Example("fatalError() // TODO: <\(dateString(for: .expired))> Implement")
let violations = self.violations(example, ruleConfig)
let violations = violations(example, ruleConfig)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODO/FIXME has expired and must be resolved")
}
@@ -51,7 +51,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
let example = Example(
"fatalError() // TODO: [\(dateString(for: .expired, format: ruleConfig.dateFormat))] Implement"
)
let violations = self.violations(example, ruleConfig)
let violations = violations(example, ruleConfig)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODO/FIXME has expired and must be resolved")
}
@@ -61,7 +61,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
let example = Example(
"fatalError() // TODO: [\(dateString(for: .expired, format: ruleConfig.dateFormat))] Implement"
)
let violations = self.violations(example, ruleConfig)
let violations = violations(example, ruleConfig)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODO/FIXME has expired and must be resolved")
}
@@ -73,7 +73,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
fatalError() // TODO: Implement two by [\(dateString(for: .expired))]
"""
)
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 2)
XCTAssertEqual(violations[0].reason, "TODO/FIXME has expired and must be resolved")
XCTAssertEqual(violations[0].location.line, 1)
@@ -89,7 +89,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
// TODO: Implement two by [\(dateString(for: .expired))]
"""
)
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations[0].reason, "TODO/FIXME has expired and must be resolved")
XCTAssertEqual(violations[0].location.line, 3)
@@ -104,7 +104,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
// severity: fatal
"""
)
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations[0].reason, "TODO/FIXME has expired and must be resolved")
XCTAssertEqual(violations[0].location.line, 3)
@@ -117,7 +117,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
// TODO: Implement two by [\(dateString(for: .expired))]
"""
)
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations[0].reason, "TODO/FIXME has expired and must be resolved")
XCTAssertEqual(violations[0].location.line, 2)
@@ -128,7 +128,7 @@ final class ExpiringTodoRuleTests: SwiftLintTestCase {
dateFormat: "dd/yyyy/MM"
)
let example = Example("fatalError() // TODO: [31/01/2020] Implement")
let violations = self.violations(example, ruleConfig)
let violations = violations(example, ruleConfig)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Expiring TODO/FIXME is incorrectly formatted")
}
@@ -13,7 +13,7 @@ final class FunctionBodyLengthRuleTests: SwiftLintTestCase {
""")
XCTAssertEqual(
self.violations(example, configuration: ["warning": 2, "error": 4]),
violations(example, configuration: ["warning": 2, "error": 4]),
[
StyleViolation(
ruleDescription: FunctionBodyLengthRule.description,
@@ -38,7 +38,7 @@ final class FunctionBodyLengthRuleTests: SwiftLintTestCase {
""")
XCTAssertEqual(
self.violations(example, configuration: ["warning": 1, "error": 2]),
violations(example, configuration: ["warning": 1, "error": 2]),
[
StyleViolation(
ruleDescription: FunctionBodyLengthRule.description,
@@ -88,6 +88,6 @@ final class ImplicitReturnRuleTests: SwiftLintTestCase {
.with(triggeringExamples: triggeringExamples)
.with(corrections: corrections)
self.verifyRule(description, ruleConfiguration: ["included": [kind.rawValue]])
verifyRule(description, ruleConfiguration: ["included": [kind.rawValue]])
}
}
@@ -50,8 +50,8 @@ final class RequiredEnumCaseConfigurationTests: SwiftLintTestCase {
}
private func validateRulesExistForProtocol1() {
XCTAssertTrue(self.config.protocols[Self.protocol1]?.contains(Self.rule1) ?? false)
XCTAssertTrue(self.config.protocols[Self.protocol1]?.contains(Self.rule2) ?? false)
XCTAssertTrue(config.protocols[Self.protocol1]?.contains(Self.rule1) ?? false)
XCTAssertTrue(config.protocols[Self.protocol1]?.contains(Self.rule2) ?? false)
}
func testRegisterProtocolCasesRegistersCasesWithSpecifiedSeverity() {
@@ -60,8 +60,8 @@ final class RequiredEnumCaseConfigurationTests: SwiftLintTestCase {
}
private func validateRulesExistForProtocol3() {
XCTAssertTrue(self.config.protocols[Self.protocol3]?.contains(Self.rule3) ?? false)
XCTAssertTrue(self.config.protocols[Self.protocol3]?.contains(Self.rule2) ?? false)
XCTAssertTrue(config.protocols[Self.protocol3]?.contains(Self.rule3) ?? false)
XCTAssertTrue(config.protocols[Self.protocol3]?.contains(Self.rule2) ?? false)
}
func testRegisterProtocols() {
+4 -4
View File
@@ -9,14 +9,14 @@ final class TodoRuleTests: SwiftLintTestCase {
func testTodoMessage() {
let example = Example("fatalError() // TODO: Implement")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODOs should be resolved (Implement)")
}
func testFixMeMessage() {
let example = Example("fatalError() // FIXME: Implement")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "FIXMEs should be resolved (Implement)")
}
@@ -26,7 +26,7 @@ final class TodoRuleTests: SwiftLintTestCase {
fatalError() // TODO: Implement todo
fatalError() // FIXME: Implement fixme
""")
let violations = self.violations(example, config: ["only": ["FIXME"]])
let violations = violations(example, config: ["only": ["FIXME"]])
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "FIXMEs should be resolved (Implement fixme)")
}
@@ -36,7 +36,7 @@ final class TodoRuleTests: SwiftLintTestCase {
fatalError() // TODO: Implement todo
fatalError() // FIXME: Implement fixme
""")
let violations = self.violations(example, config: ["only": ["TODO"]])
let violations = violations(example, config: ["only": ["TODO"]])
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first!.reason, "TODOs should be resolved (Implement todo)")
}
@@ -13,7 +13,7 @@ final class TypeBodyLengthRuleTests: SwiftLintTestCase {
""")
XCTAssertEqual(
self.violations(example, configuration: ["warning": 2, "error": 4]),
violations(example, configuration: ["warning": 2, "error": 4]),
[
StyleViolation(
ruleDescription: TypeBodyLengthRule.description,
@@ -38,7 +38,7 @@ final class TypeBodyLengthRuleTests: SwiftLintTestCase {
""")
XCTAssertEqual(
self.violations(example, configuration: ["warning": 1, "error": 2]),
violations(example, configuration: ["warning": 1, "error": 2]),
[
StyleViolation(
ruleDescription: TypeBodyLengthRule.description,
@@ -5,7 +5,7 @@ import XCTest
final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testEqualTrue() {
let example = Example("XCTAssertEqual(a, true)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertTrue' instead")
@@ -13,7 +13,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testEqualFalse() {
let example = Example("XCTAssertEqual(a, false)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertFalse' instead")
@@ -21,7 +21,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testEqualNil() {
let example = Example("XCTAssertEqual(a, nil)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNil' instead")
@@ -29,7 +29,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testNotEqualTrue() {
let example = Example("XCTAssertNotEqual(a, true)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertFalse' instead")
@@ -37,7 +37,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testNotEqualFalse() {
let example = Example("XCTAssertNotEqual(a, false)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertTrue' instead")
@@ -45,7 +45,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testNotEqualNil() {
let example = Example("XCTAssertNotEqual(a, nil)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotNil' instead")
@@ -55,14 +55,14 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testEqualOptionalFalse() {
let example = Example("XCTAssertEqual(a?.b, false)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 0)
}
func testEqualUnwrappedOptionalFalse() {
let example = Example("XCTAssertEqual(a!.b, false)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertFalse' instead")
@@ -70,7 +70,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testEqualNilNil() {
let example = Example("XCTAssertEqual(nil, nil)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNil' instead")
@@ -78,7 +78,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testEqualTrueTrue() {
let example = Example("XCTAssertEqual(true, true)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertTrue' instead")
@@ -86,7 +86,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testEqualFalseFalse() {
let example = Example("XCTAssertEqual(false, false)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertFalse' instead")
@@ -94,7 +94,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testNotEqualNilNil() {
let example = Example("XCTAssertNotEqual(nil, nil)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotNil' instead")
@@ -102,7 +102,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testNotEqualTrueTrue() {
let example = Example("XCTAssertNotEqual(true, true)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertFalse' instead")
@@ -110,7 +110,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testNotEqualFalseFalse() {
let example = Example("XCTAssertNotEqual(false, false)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertTrue' instead")
@@ -118,7 +118,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertEqual() {
let example = Example("XCTAssert(foo == bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertEqual' instead")
@@ -126,7 +126,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertFalseNotEqual() {
let example = Example("XCTAssertFalse(bar != foo)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertEqual' instead")
@@ -134,7 +134,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertTrueEqual() {
let example = Example("XCTAssertTrue(foo == 1)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertEqual' instead")
@@ -142,7 +142,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertNotEqual() {
let example = Example("XCTAssert(foo != bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotEqual' instead")
@@ -150,7 +150,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertFalseEqual() {
let example = Example("XCTAssertFalse(bar == foo)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotEqual' instead")
@@ -158,7 +158,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertTrueNotEqual() {
let example = Example("XCTAssertTrue(foo != 1)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotEqual' instead")
@@ -166,7 +166,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testMultipleComparisons() {
let example = Example("XCTAssert(foo == (bar == baz))")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertEqual' instead")
@@ -185,7 +185,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertIdentical() {
let example = Example("XCTAssert(foo === bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertIdentical' instead")
@@ -193,7 +193,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertNotIdentical() {
let example = Example("XCTAssert(foo !== bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotIdentical' instead")
@@ -201,7 +201,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertTrueIdentical() {
let example = Example("XCTAssertTrue(foo === bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertIdentical' instead")
@@ -209,7 +209,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertTrueNotIdentical() {
let example = Example("XCTAssertTrue(foo !== bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotIdentical' instead")
@@ -217,7 +217,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertFalseIdentical() {
let example = Example("XCTAssertFalse(foo === bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertNotIdentical' instead")
@@ -225,7 +225,7 @@ final class XCTSpecificMatcherRuleTests: SwiftLintTestCase {
func testAssertFalseNotIdentical() {
let example = Example("XCTAssertFalse(foo !== bar)")
let violations = self.violations(example)
let violations = violations(example)
XCTAssertEqual(violations.count, 1)
XCTAssertEqual(violations.first?.reason, "Prefer the specific matcher 'XCTAssertIdentical' instead")
+3 -3
View File
@@ -323,7 +323,7 @@ final class CustomRulesTests: SwiftLintTestCase {
let ALLOWED = 2
""")
let violations = try self.violations(forExample: example, customRules: customRules)
let violations = try violations(forExample: example, customRules: customRules)
XCTAssertEqual(violations.count, 2)
XCTAssertTrue(violations[0].isSuperfluousDisableCommandViolation(for: "forbidden"))
XCTAssertTrue(violations[1].isSuperfluousDisableCommandViolation(for: "forbidden2"))
@@ -343,7 +343,7 @@ final class CustomRulesTests: SwiftLintTestCase {
let FORBIDDEN = 1
""")
let violations = try self.violations(forExample: example, customRules: customRules)
let violations = try violations(forExample: example, customRules: customRules)
XCTAssertEqual(violations.count, 1)
XCTAssertTrue(violations[0].isSuperfluousDisableCommandViolation(for: "forbidden2"))
}
@@ -362,7 +362,7 @@ final class CustomRulesTests: SwiftLintTestCase {
let FORBIDDEN = 1
""")
let violations = try self.violations(forExample: example, customRules: customRules)
let violations = try violations(forExample: example, customRules: customRules)
XCTAssertEqual(violations.count, 1)
XCTAssertTrue(violations[0].isSuperfluousDisableCommandViolation(for: "forbidden2"))
}
+21 -9
View File
@@ -104,7 +104,7 @@ public let allRuleIdentifiers = Set(RuleRegistry.shared.list.list.keys)
public extension Configuration {
func applyingConfiguration(from example: Example) -> Configuration {
guard let exampleConfiguration = example.configuration,
case let .onlyConfiguration(onlyRules) = self.rulesMode,
case let .onlyConfiguration(onlyRules) = rulesMode,
let firstRule = (onlyRules.first { $0 != "superfluous_disable_command" }),
case let configDict: [_: any Sendable] = ["only_rules": onlyRules, firstRule: exampleConfiguration],
let typedConfiguration = try? Configuration(dict: configDict) else { return self }
@@ -254,7 +254,7 @@ private extension Configuration {
let (cleanedBefore, _) = cleanedContentsAndMarkerOffsets(from: before.code)
let file = SwiftLintFile.testFile(withContents: cleanedBefore, persistToDisk: true)
// expectedLocations are needed to create before call `correct()`
let includeCompilerArguments = self.rules.contains(where: { $0 is any AnalyzerRule })
let includeCompilerArguments = rules.contains(where: { $0 is any AnalyzerRule })
let compilerArguments = includeCompilerArguments ? file.makeCompilerArguments() : []
let storage = RuleStorage()
let collector = Linter(file: file, configuration: self, compilerArguments: compilerArguments)
@@ -383,13 +383,25 @@ public extension XCTestCase {
disableCommands = ruleDescription.allIdentifiers.map { "// swiftlint:disable \($0)\n" }
}
self.verifyLint(ruleDescription, config: config, commentDoesntViolate: commentDoesntViolate,
stringDoesntViolate: stringDoesntViolate, skipCommentTests: skipCommentTests,
skipStringTests: skipStringTests, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets, testShebang: testShebang,
file: file, line: line)
self.verifyCorrections(ruleDescription, config: config, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets)
verifyLint(
ruleDescription,
config: config,
commentDoesntViolate: commentDoesntViolate,
stringDoesntViolate: stringDoesntViolate,
skipCommentTests: skipCommentTests,
skipStringTests: skipStringTests,
disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets,
testShebang: testShebang,
file: file,
line: line
)
verifyCorrections(
ruleDescription,
config: config,
disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets
)
}
// swiftlint:disable:next function_body_length