From 860a2bfc5c5638c88b29633fba72d51137ae7d11 Mon Sep 17 00:00:00 2001 From: Zev Eisenberg Date: Sun, 28 Jun 2026 10:16:15 -0400 Subject: [PATCH] Add #examples and #examplesDictionary macros to DRY up rule descriptions. --- CHANGELOG.md | 6 +- ...nymousArgumentInMultilineClosureRule.swift | 24 +- .../Rules/Idiomatic/BlockBasedKVORule.swift | 20 +- .../Rules/Idiomatic/ConvenienceTypeRule.swift | 82 ++--- .../Idiomatic/DiscouragedAssertRule.swift | 26 +- .../Idiomatic/DiscouragedNoneNameRule.swift | 132 +++---- .../DiscouragedObjectLiteralRule.swift | 24 +- .../DuplicateImportsRuleExamples.swift | 40 +- .../Rules/Idiomatic/ExplicitACLRule.swift | 90 ++--- .../Idiomatic/ExplicitEnumRawValueRule.swift | 52 +-- .../Rules/Idiomatic/ExplicitInitRule.swift | 110 +++--- .../Idiomatic/ExplicitTopLevelACLRule.swift | 14 +- .../Idiomatic/ExplicitTypeInterfaceRule.swift | 28 +- .../ExtensionAccessModifierRule.swift | 100 ++--- .../Rules/Idiomatic/FallthroughRule.swift | 16 +- .../Idiomatic/FatalErrorMessageRule.swift | 24 +- .../Rules/Idiomatic/ForceCastRule.swift | 8 +- .../Rules/Idiomatic/ForceTryRule.swift | 16 +- .../Rules/Idiomatic/GenericTypeNameRule.swift | 34 +- .../ImplicitlyUnwrappedOptionalRule.swift | 28 +- .../Rules/Idiomatic/IsDisjointRule.swift | 20 +- .../JoinedDefaultParameterRule.swift | 42 +-- .../LegacyCGGeometryFunctionsRule.swift | 136 +++---- .../LegacyConstantRuleExamples.swift | 76 ++-- .../Idiomatic/LegacyConstructorRule.swift | 176 ++++----- .../Rules/Idiomatic/LegacyHashingRule.swift | 36 +- .../Rules/Idiomatic/LegacyMultipleRule.swift | 42 +-- .../LegacyNSGeometryFunctionsRule.swift | 134 +++---- .../Rules/Idiomatic/LegacyObjcTypeRule.swift | 20 +- .../Rules/Idiomatic/LegacyRandomRule.swift | 20 +- .../LegacyUIGraphicsFunctionRule.swift | 32 +- .../Rules/Idiomatic/NimbleOperatorRule.swift | 106 +++--- .../Rules/Idiomatic/NoEmptyBlockRule.swift | 24 +- .../NoExtensionAccessModifierRule.swift | 24 +- .../NoFallthroughOnlyRuleExamples.swift | 72 ++-- .../Idiomatic/NoGroupingExtensionRule.swift | 22 +- .../Rules/Idiomatic/ObjectLiteralRule.swift | 33 +- .../Idiomatic/OneDeclarationPerFileRule.swift | 32 +- .../PatternMatchingKeywordsRule.swift | 132 +++---- .../Idiomatic/PreferAssetSymbolsRule.swift | 44 +-- .../Idiomatic/PreferConditionListRule.swift | 102 +++--- .../Rules/Idiomatic/PreferNimbleRule.swift | 24 +- .../Idiomatic/PreferTypeCheckingRule.swift | 58 +-- .../PreferZeroOverExplicitInitRule.swift | 48 +-- .../PrivateOverFilePrivateRule.swift | 74 ++-- .../Rules/Idiomatic/RedundantFinalRule.swift | 60 +-- .../RedundantNilCoalescingRule.swift | 24 +- .../RedundantObjcAttributeRuleExamples.swift | 208 +++++------ .../RedundantSetAccessControlRule.swift | 28 +- .../RedundantStringEnumValueRule.swift | 40 +- .../Idiomatic/RedundantVoidReturnRule.swift | 42 +-- ...urnValueFromVoidFunctionRuleExamples.swift | 92 ++--- .../ShorthandOptionalBindingRule.swift | 34 +- .../Rules/Idiomatic/StaticOperatorRule.swift | 40 +- .../Idiomatic/StaticOverFinalClassRule.swift | 52 +-- .../SyntacticSugarRuleExamples.swift | 80 ++-- .../Rules/Idiomatic/ToggleBoolRule.swift | 36 +- .../Idiomatic/TrailingSemicolonRule.swift | 28 +- .../Idiomatic/UnavailableConditionRule.swift | 20 +- .../Idiomatic/UnavailableFunctionRule.swift | 36 +- ...edSynthesizedInitializerRuleExamples.swift | 124 +++---- .../Idiomatic/UntypedErrorInCatchRule.swift | 66 ++-- .../VoidFunctionInTernaryConditionRule.swift | 76 ++-- .../Rules/Idiomatic/XCTFailMessageRule.swift | 24 +- .../XCTSpecificMatcherRuleExamples.swift | 122 +++---- ...cessibilityLabelForImageRuleExamples.swift | 172 ++++----- ...essibilityTraitForButtonRuleExamples.swift | 104 +++--- .../Rules/Lint/ArrayInitRule.swift | 54 +-- .../Lint/AsyncWithoutAwaitRuleExamples.swift | 106 +++--- .../Lint/BalancedXCTestLifecycleRule.swift | 64 ++-- .../Lint/BlanketDisableCommandRule.swift | 38 +- .../Rules/Lint/CaptureVariableRule.swift | 44 +-- .../Lint/ClassDelegateProtocolRule.swift | 54 +-- .../Rules/Lint/CommentSpacingRule.swift | 112 +++--- .../Rules/Lint/CompilerProtocolInitRule.swift | 20 +- .../Lint/DeploymentTargetRuleExamples.swift | 68 ++-- ...cardedNotificationCenterObserverRule.swift | 72 ++-- .../Lint/DiscouragedDirectInitRule.swift | 50 +-- .../Rules/Lint/DuplicateConditionsRule.swift | 84 ++--- .../Rules/Lint/DuplicateEnumCasesRule.swift | 28 +- ...DuplicatedKeyInDictionaryLiteralRule.swift | 44 +-- .../Rules/Lint/DynamicInlineRule.swift | 24 +- .../Lint/EmptyXCTestMethodRuleExamples.swift | 20 +- .../Rules/Lint/ExpiringTodoRule.swift | 36 +- .../Lint/IBInspectableInExtensionRule.swift | 16 +- .../Rules/Lint/IdenticalOperandsRule.swift | 98 ++--- ...bleConcurrencyAnnotationRuleExamples.swift | 70 ++-- .../Rules/Lint/InvisibleCharacterRule.swift | 24 +- .../Rules/Lint/LocalDocCommentRule.swift | 28 +- .../Rules/Lint/LowerACLThanParentRule.swift | 128 +++---- .../Rules/Lint/NSLocalizedStringKeyRule.swift | 30 +- .../NSLocalizedStringRequireBundleRule.swift | 36 +- .../NSNumberInitAsFunctionReferenceRule.swift | 22 +- ...ficationCenterDetachmentRuleExamples.swift | 20 +- .../OptionalDataStringConversionRule.swift | 36 +- .../Rules/Lint/OrphanedDocCommentRule.swift | 44 +-- .../Rules/Lint/OverriddenSuperCallRule.swift | 40 +- .../Rules/Lint/OverrideInExtensionRule.swift | 30 +- .../Rules/Lint/PeriodSpacingRule.swift | 40 +- .../Rules/Lint/PrivateActionRule.swift | 42 +-- .../Lint/PrivateSubjectRuleExamples.swift | 224 ++++-------- ...vateSwiftUIStatePropertyRuleExamples.swift | 182 ++++----- .../Rules/Lint/PrivateUnitTestRule.swift | 68 ++-- .../Rules/Lint/ProhibitedSuperRule.swift | 36 +- .../QuickDiscouragedCallRuleExamples.swift | 136 +++---- ...ckDiscouragedFocusedTestRuleExamples.swift | 44 +-- ...ckDiscouragedPendingTestRuleExamples.swift | 48 +-- ...RawValueForCamelCasedCodableEnumRule.swift | 56 +-- .../Rules/Lint/RedundantSendableRule.swift | 16 +- .../Rules/Lint/RequiredDeinitRule.swift | 42 +-- .../SelfInPropertyInitializationRule.swift | 12 +- .../TestCaseAccessibilityRuleExamples.swift | 20 +- .../Rules/Lint/TodoRule.swift | 28 +- .../Rules/Lint/TypesafeArrayInitRule.swift | 32 +- .../Lint/UnhandledThrowingTaskRule.swift | 108 +++--- .../Lint/UnneededEscapingRuleExamples.swift | 76 ++-- .../Lint/UnneededOverrideRuleExamples.swift | 60 +-- .../Lint/UnneededThrowsRuleExamples.swift | 288 +++++++-------- .../Lint/UnownedVariableCaptureRule.swift | 30 +- .../UnusedClosureParameterRuleExamples.swift | 174 ++++----- .../Lint/UnusedControlFlowLabelRule.swift | 66 ++-- .../Lint/UnusedDeclarationRuleExamples.swift | 92 ++--- .../Rules/Lint/UnusedImportRuleExamples.swift | 28 +- .../Rules/Lint/UnusedParameterRule.swift | 58 +-- .../Rules/Lint/UnusedSetterValueRule.swift | 28 +- .../Rules/Lint/ValidIBInspectableRule.swift | 72 ++-- .../Rules/Lint/WeakDelegateRule.swift | 12 +- .../Rules/Lint/YodaConditionRule.swift | 22 +- .../Metrics/CyclomaticComplexityRule.swift | 24 +- .../EnumCaseAssociatedValuesLengthRule.swift | 24 +- .../Metrics/FunctionParameterCountRule.swift | 40 +- .../Rules/Metrics/NestingRuleExamples.swift | 48 +-- .../ContainsOverFilterCountRule.swift | 30 +- .../ContainsOverFilterIsEmptyRule.swift | 30 +- .../ContainsOverFirstNotNilRule.swift | 24 +- .../ContainsOverRangeNilComparisonRule.swift | 18 +- .../EmptyCollectionLiteralRule.swift | 32 +- .../Rules/Performance/EmptyCountRule.swift | 68 ++-- .../Rules/Performance/EmptyStringRule.swift | 24 +- .../Rules/Performance/FinalTestCaseRule.swift | 12 +- .../Rules/Performance/FirstWhereRule.swift | 40 +- .../FlatMapOverMapReduceRule.swift | 14 +- .../Rules/Performance/LastWhereRule.swift | 32 +- .../Rules/Performance/ReduceBooleanRule.swift | 32 +- .../Rules/Performance/ReduceIntoRule.swift | 76 ++-- .../Performance/SortedFirstLastRule.swift | 68 ++-- .../Style/AttributeNameSpacingRule.swift | 88 ++--- .../Rules/Style/ClosingBraceRule.swift | 22 +- .../ClosureEndIndentationRuleExamples.swift | 92 ++--- .../Style/ClosureParameterPositionRule.swift | 72 ++-- .../Rules/Style/ClosureSpacingRule.swift | 20 +- .../Rules/Style/CollectionAlignmentRule.swift | 108 +++--- .../Rules/Style/ColonRuleExamples.swift | 344 +++++++++--------- .../Rules/Style/CommaInheritanceRule.swift | 66 ++-- .../Rules/Style/CommaRule.swift | 56 +-- .../ComputedAccessorsOrderRuleExamples.swift | 120 +++--- .../ConditionalReturnsOnNewlineRule.swift | 38 +- .../ContrastedOpeningBraceRuleExamples.swift | 198 +++++----- .../Rules/Style/ControlStatementRule.swift | 70 ++-- .../Rules/Style/DirectReturnRule.swift | 90 ++--- .../Rules/Style/EmptyParametersRule.swift | 42 +-- ...tyParenthesesWithTrailingClosureRule.swift | 56 +-- .../Rules/Style/FileHeaderRule.swift | 22 +- .../Style/ImplicitGetterRuleExamples.swift | 136 +++---- .../Style/ImplicitReturnRuleExamples.swift | 238 ++++++------ .../Style/InclusiveLanguageRuleExamples.swift | 40 +- .../Rules/Style/IndentationWidthRule.swift | 30 +- .../Rules/Style/LeadingWhitespaceRule.swift | 14 +- .../Rules/Style/LetVarWhitespaceRule.swift | 56 +-- .../LiteralExpressionEndIndentationRule.swift | 90 ++--- .../Style/ModifierOrderRuleExamples.swift | 144 ++++---- .../MultilineArgumentsRuleExamples.swift | 86 ++--- .../Style/MultilineFunctionChainsRule.swift | 60 +-- .../Style/MultilineLiteralBracketsRule.swift | 60 +-- .../MultilineParametersBracketsRule.swift | 60 +-- ...tipleClosuresWithTrailingClosureRule.swift | 34 +- .../Rules/Style/NoSpaceInMethodCallRule.swift | 56 +-- .../NonOverridableClassDeclarationRule.swift | 44 +-- .../Style/OpeningBraceRuleExamples.swift | 286 +++++++-------- .../OperatorUsageWhitespaceRuleExamples.swift | 102 +++--- .../Style/OptionalEnumCaseMatchingRule.swift | 64 ++-- ...erSelfInStaticReferencesRuleExamples.swift | 30 +- .../PreferSelfTypeOverTypeOfSelfRule.swift | 58 +-- .../Style/PrefixedTopLevelConstantRule.swift | 22 +- .../ProtocolPropertyAccessorsOrderRule.swift | 24 +- .../Style/ReturnArrowWhitespaceRule.swift | 74 ++-- .../Rules/Style/ShorthandOperatorRule.swift | 48 +-- .../Rules/Style/SingleTestClassRule.swift | 42 +-- .../Rules/Style/SortedEnumCasesRule.swift | 68 ++-- .../Rules/Style/StatementPositionRule.swift | 88 ++--- .../Rules/Style/SuperfluousElseRule.swift | 54 +-- .../Rules/Style/SwitchCaseAlignmentRule.swift | 56 +-- .../Rules/Style/TrailingCommaRule.swift | 44 +-- .../Rules/Style/TrailingNewlineRule.swift | 24 +- .../Rules/Style/TrailingWhitespaceRule.swift | 8 +- .../Style/TypeContentsOrderRuleExamples.swift | 12 +- ...ededParenthesesInClosureArgumentRule.swift | 20 +- .../Style/UnusedOptionalBindingRule.swift | 38 +- ...VerticalParameterAlignmentOnCallRule.swift | 88 ++--- ...rticalParameterAlignmentRuleExamples.swift | 84 ++--- .../VerticalWhitespaceOpeningBracesRule.swift | 72 ++-- .../Rules/Style/VerticalWhitespaceRule.swift | 50 +-- .../Rules/Style/VoidReturnRule.swift | 74 ++-- Source/SwiftLintCore/Helpers/Macros.swift | 28 ++ .../Models/RuleDescription.swift | 6 +- Source/SwiftLintCoreMacros/Examples.swift | 78 ++++ .../SwiftLintCoreMacroError.swift | 2 + .../SwiftLintCoreMacros.swift | 2 + Tests/MacroTests/ExamplesTests.swift | 192 ++++++++++ 209 files changed, 6474 insertions(+), 6243 deletions(-) create mode 100644 Source/SwiftLintCoreMacros/Examples.swift create mode 100644 Tests/MacroTests/ExamplesTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index f80760840b..02c253791a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,11 @@ ### Enhancements -* None. +* Add `#examples` and `#examplesDictionary` macros that expand lists and + dictionaries of code strings into `Example`s, reducing boilerplate when + defining a rule's triggering/non-triggering examples and corrections. Adopt + them across the built-in rules. + [ZevEisenberg](https://github.com/ZevEisenberg) ### Bug Fixes diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/AnonymousArgumentInMultilineClosureRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/AnonymousArgumentInMultilineClosureRule.swift index 2755e17a4a..62e8a20e0a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/AnonymousArgumentInMultilineClosureRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/AnonymousArgumentInMultilineClosureRule.swift @@ -26,27 +26,27 @@ struct AnonymousArgumentInMultilineClosureRule: Rule { ``` """, kind: .idiomatic, - nonTriggeringExamples: [ - Example("closure { $0 }"), - Example("closure { print($0) }"), - Example(""" + nonTriggeringExamples: #examples([ + "closure { $0 }", + "closure { print($0) }", + """ closure { arg in print(arg) } - """), - Example(""" + """, + """ closure { arg in nestedClosure { $0 + arg } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ closure { print(↓$0) } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/BlockBasedKVORule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/BlockBasedKVORule.swift index 1b1e59481d..f61bef7ebd 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/BlockBasedKVORule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/BlockBasedKVORule.swift @@ -10,29 +10,29 @@ struct BlockBasedKVORule: Rule { name: "Block Based KVO", description: "Prefer the new block based KVO API with keypaths when using Swift 3.2 or later", kind: .idiomatic, - nonTriggeringExamples: [ - Example(#""" + nonTriggeringExamples: #examples([ + #""" let observer = foo.observe(\.value, options: [.new]) { (foo, change) in print(change.newValue) } - """#), - ], - triggeringExamples: [ - Example(""" + """#, + ]), + triggeringExamples: #examples([ + """ class Foo: NSObject { override ↓func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {} } - """), - Example(""" + """, + """ class Foo: NSObject { override ↓func observeValue(forKeyPath keyPath: String?, of object: Any?, change: Dictionary?, context: UnsafeMutableRawPointer?) {} } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ConvenienceTypeRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ConvenienceTypeRule.swift index edf9e13d7a..5153702c9f 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ConvenienceTypeRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ConvenienceTypeRule.swift @@ -10,110 +10,110 @@ struct ConvenienceTypeRule: Rule { description: "Types used for hosting only static members should be implemented as a caseless enum " + "to avoid instantiation", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum Math { // enum public static let pi = 3.14 } - """), - Example(""" + """, + """ // class with inheritance class MathViewController: UIViewController { public static let pi = 3.14 } - """), - Example(""" + """, + """ @objc class Math: NSObject { // class visible to Obj-C public static let pi = 3.14 } - """), - Example(""" + """, + """ struct Math { // type with non-static declarations public static let pi = 3.14 public let randomNumber = 2 } - """), - Example("class DummyClass {}"), - Example(""" + """, + "class DummyClass {}", + """ class Foo: NSObject { // class with Obj-C class property class @objc let foo = 1 } - """), - Example(""" + """, + """ class Foo: NSObject { // class with Obj-C static property static @objc let foo = 1 } - """), - Example(""" + """, + """ class Foo { // @objc class func can't exist on an enum @objc class func foo() {} } - """), - Example(""" + """, + """ class Foo { // @objc static func can't exist on an enum @objc static func foo() {} } - """), - Example(""" + """, + """ @objcMembers class Foo { // @objc static func can't exist on an enum static func foo() {} } - """), - Example(""" + """, + """ final class Foo { // final class, but @objc class func can't exist on an enum @objc class func foo() {} } - """), - Example(""" + """, + """ final class Foo { // final class, but @objc static func can't exist on an enum @objc static func foo() {} } - """), - Example(""" + """, + """ @globalActor actor MyActor { static let shared = MyActor() } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓struct Math { public static let pi = 3.14 } - """), - Example(""" + """, + """ ↓struct Math { public static let pi = 3.14 @available(*, unavailable) init() {} } - """), - Example(""" + """, + """ final ↓class Foo { // final class can't be inherited class let foo = 1 } - """), + """, // Intentional false positives. Non-final classes could be // subclassed, but we figure it is probably rare enough that it is // more important to catch these cases, and manually disable the // rule if needed. - Example(""" + """ ↓class Foo { class let foo = 1 } - """), - Example(""" + """, + """ ↓class Foo { final class let foo = 1 } - """), - Example(""" + """, + """ ↓class SomeClass { static func foo() {} } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedAssertRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedAssertRule.swift index 7ce82d7c51..6e530662a7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedAssertRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedAssertRule.swift @@ -9,19 +9,19 @@ struct DiscouragedAssertRule: Rule { name: "Discouraged Assert", description: "Prefer `assertionFailure()` and/or `preconditionFailure()` over `assert(false)`", kind: .idiomatic, - nonTriggeringExamples: [ - Example(#"assert(true)"#), - Example(#"assert(true, "foobar")"#), - Example(#"assert(true, "foobar", file: "toto", line: 42)"#), - Example(#"assert(false || true)"#), - Example(#"XCTAssert(false)"#), - ], - triggeringExamples: [ - Example(#"↓assert(false)"#), - Example(#"↓assert(false, "foobar")"#), - Example(#"↓assert(false, "foobar", file: "toto", line: 42)"#), - Example(#"↓assert( false , "foobar")"#), - ] + nonTriggeringExamples: #examples([ + #"assert(true)"#, + #"assert(true, "foobar")"#, + #"assert(true, "foobar", file: "toto", line: 42)"#, + #"assert(false || true)"#, + #"XCTAssert(false)"#, + ]), + triggeringExamples: #examples([ + #"↓assert(false)"#, + #"↓assert(false, "foobar")"#, + #"↓assert(false, "foobar", file: "toto", line: 42)"#, + #"↓assert( false , "foobar")"#, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedNoneNameRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedNoneNameRule.swift index 8983423745..b9a69ddbe4 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedNoneNameRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedNoneNameRule.swift @@ -10,172 +10,172 @@ struct DiscouragedNoneNameRule: Rule { description: "Enum cases and static members named `none` are discouraged as they can conflict with " + "`Optional.none`.", kind: .idiomatic, - nonTriggeringExamples: [ + nonTriggeringExamples: #examples([ // Should not trigger unless exactly matches "none" - Example(""" + """ enum MyEnum { case nOne } - """), - Example(""" + """, + """ enum MyEnum { case _none } - """), - Example(""" + """, + """ enum MyEnum { case none_ } - """), - Example(""" + """, + """ enum MyEnum { case none(Any) } - """), - Example(""" + """, + """ enum MyEnum { case nonenone } - """), - Example(""" + """, + """ class MyClass { class var nonenone: MyClass { MyClass() } } - """), - Example(""" + """, + """ class MyClass { static var nonenone = MyClass() } - """), - Example(""" + """, + """ class MyClass { static let nonenone = MyClass() } - """), - Example(""" + """, + """ struct MyStruct { static var nonenone = MyStruct() } - """), - Example(""" + """, + """ struct MyStruct { static let nonenone = MyStruct() } - """), + """, // Should not trigger if not an enum case or static/class member - Example(""" + """ struct MyStruct { let none = MyStruct() } - """), - Example(""" + """, + """ struct MyStruct { var none = MyStruct() } - """), - Example(""" + """, + """ class MyClass { let none = MyClass() } - """), - Example(""" + """, + """ class MyClass { var none = MyClass() } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ enum MyEnum { case ↓none } - """), - Example(""" + """, + """ enum MyEnum { case a, ↓none } - """), - Example(""" + """, + """ enum MyEnum { case ↓none, b } - """), - Example(""" + """, + """ enum MyEnum { case a, ↓none, b } - """), - Example(""" + """, + """ enum MyEnum { case a case ↓none } - """), - Example(""" + """, + """ enum MyEnum { case ↓none case b } - """), - Example(""" + """, + """ enum MyEnum { case a case ↓none case b } - """), - Example(""" + """, + """ class MyClass { ↓static let none = MyClass() } - """), - Example(""" + """, + """ class MyClass { ↓static let none: MyClass = MyClass() } - """), - Example(""" + """, + """ class MyClass { ↓static var none: MyClass = MyClass() } - """), - Example(""" + """, + """ class MyClass { ↓class var none: MyClass { MyClass() } } - """), - Example(""" + """, + """ struct MyStruct { ↓static var none = MyStruct() } - """), - Example(""" + """, + """ struct MyStruct { ↓static var none: MyStruct = MyStruct() } - """), - Example(""" + """, + """ struct MyStruct { ↓static var none = MyStruct() } - """), - Example(""" + """, + """ struct MyStruct { ↓static var none: MyStruct = MyStruct() } - """), - Example(""" + """, + """ struct MyStruct { ↓static var a = MyStruct(), none = MyStruct() } - """), - Example(""" + """, + """ struct MyStruct { ↓static var none = MyStruct(), a = MyStruct() } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedObjectLiteralRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedObjectLiteralRule.swift index d1dff3d374..79f41d69e0 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedObjectLiteralRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DiscouragedObjectLiteralRule.swift @@ -9,18 +9,18 @@ struct DiscouragedObjectLiteralRule: Rule { name: "Discouraged Object Literal", description: "Prefer initializers over object literals", kind: .idiomatic, - nonTriggeringExamples: [ - Example("let image = UIImage(named: aVariable)"), - Example("let image = UIImage(named: \"interpolated \\(variable)\")"), - Example("let color = UIColor(red: value, green: value, blue: value, alpha: 1)"), - Example("let image = NSImage(named: aVariable)"), - Example("let image = NSImage(named: \"interpolated \\(variable)\")"), - Example("let color = NSColor(red: value, green: value, blue: value, alpha: 1)"), - ], - triggeringExamples: [ - Example("let image = ↓#imageLiteral(resourceName: \"image.jpg\")"), - Example("let color = ↓#colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)"), - ] + nonTriggeringExamples: #examples([ + "let image = UIImage(named: aVariable)", + "let image = UIImage(named: \"interpolated \\(variable)\")", + "let color = UIColor(red: value, green: value, blue: value, alpha: 1)", + "let image = NSImage(named: aVariable)", + "let image = NSImage(named: \"interpolated \\(variable)\")", + "let color = NSColor(red: value, green: value, blue: value, alpha: 1)", + ]), + triggeringExamples: #examples([ + "let image = ↓#imageLiteral(resourceName: \"image.jpg\")", + "let color = ↓#colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DuplicateImportsRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DuplicateImportsRuleExamples.swift index cf19dd2b81..9503b01e2a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DuplicateImportsRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/DuplicateImportsRuleExamples.swift @@ -1,47 +1,47 @@ internal struct DuplicateImportsRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ import A import B import C - """), - Example(""" + """, + """ import A.B import A.C - """), - Example(""" + """, + """ @_implementationOnly import A @_implementationOnly import B - """), - Example(""" + """, + """ @testable import A @testable import B - """), - Example(""" + """, + """ #if DEBUG @testable import KsApi #else import KsApi #endif - """), - Example(""" + """, + """ import A // module import B // module - """), - Example(""" + """, + """ #if TEST func test() { } - """), - Example(""" + """, + """ import Foo @testable import struct Foo.Bar - """), - Example(""" + """, + """ import CoreImage import CoreImage.CIFilterBuiltins - """), - ] + """, + ]) static let triggeringExamples = Array(corrections.keys.sorted()) diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitACLRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitACLRule.swift index 102fcb3bfe..53e9ddce8a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitACLRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitACLRule.swift @@ -10,54 +10,54 @@ struct ExplicitACLRule: Rule { name: "Explicit ACL", description: "All declarations should specify Access Control Level keywords explicitly", kind: .idiomatic, - nonTriggeringExamples: [ - Example("internal enum A {}"), - Example("public final class B {}"), - Example("private struct C {}"), - Example("internal enum A { internal enum B {} }"), - Example("internal final class Foo {}"), - Example(""" + nonTriggeringExamples: #examples([ + "internal enum A {}", + "public final class B {}", + "private struct C {}", + "internal enum A { internal enum B {} }", + "internal final class Foo {}", + """ internal class Foo { private let bar = 5 } - """), - Example("internal func a() { let a = }"), - Example("private func a() { func innerFunction() { } }"), - Example("private enum Foo { enum Bar { } }"), - Example("private struct C { let d = 5 }"), - Example(""" + """, + "internal func a() { let a = }", + "private func a() { func innerFunction() { } }", + "private enum Foo { enum Bar { } }", + "private struct C { let d = 5 }", + """ internal protocol A { func b() } - """), - Example(""" + """, + """ internal protocol A { var b: Int } - """), - Example("internal class A { deinit {} }"), - Example("extension A: Equatable {}"), - Example("extension A {}"), - Example(""" + """, + "internal class A { deinit {} }", + "extension A: Equatable {}", + "extension A {}", + """ extension Foo { internal func bar() {} } - """), - Example(""" + """, + """ internal enum Foo { case bar } - """), - Example(""" + """, + """ extension Foo { public var isValid: Bool { let result = true return result } } - """), - Example(""" + """, + """ extension Foo { private var isValid: Bool { get { @@ -68,41 +68,41 @@ struct ExplicitACLRule: Rule { } } } - """), - Example(""" + """, + """ private extension Foo { var isValid: Bool { true } struct S { let b = 2 } } - """), - ], - triggeringExamples: [ - Example("↓enum A {}"), - Example("final ↓class B {}"), - Example("internal struct C { ↓let d = 5 }"), - Example("public struct C { private(set) ↓var d = 5 }"), - Example("internal struct C { static ↓let d = 5 }"), - Example("public struct C { ↓let d = 5 }"), - Example("public struct C { ↓init() }"), - Example("static ↓func a() {}"), - Example("internal let a = 0\n↓func b() {}"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "↓enum A {}", + "final ↓class B {}", + "internal struct C { ↓let d = 5 }", + "public struct C { private(set) ↓var d = 5 }", + "internal struct C { static ↓let d = 5 }", + "public struct C { ↓let d = 5 }", + "public struct C { ↓init() }", + "static ↓func a() {}", + "internal let a = 0\n↓func b() {}", + """ extension Foo { ↓func bar() {} static ↓func baz() {} } - """), - Example(""" + """, + """ public extension E { let a = 1 struct S { ↓let b = 2 } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitEnumRawValueRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitEnumRawValueRule.swift index e7d089ca7f..1ad9c0d413 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitEnumRawValueRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitEnumRawValueRule.swift @@ -9,73 +9,73 @@ struct ExplicitEnumRawValueRule: Rule { name: "Explicit Enum Raw Value", description: "Enums should be explicitly assigned their raw values", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum Numbers { case int(Int) case short(Int16) } - """), - Example(""" + """, + """ enum Numbers: Int { case one = 1 case two = 2 } - """), - Example(""" + """, + """ enum Numbers: Double { case one = 1.1 case two = 2.2 } - """), - Example(""" + """, + """ enum Numbers: String { case one = "one" case two = "two" } - """), - Example(""" + """, + """ protocol Algebra {} enum Numbers: Algebra { case one } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ enum Numbers: Int { case one = 10, ↓two, three = 30 } - """), - Example(""" + """, + """ enum Numbers: NSInteger { case ↓one } - """), - Example(""" + """, + """ enum Numbers: String { case ↓one case ↓two } - """), - Example(""" + """, + """ enum Numbers: String { case ↓one, two = "two" } - """), - Example(""" + """, + """ enum Numbers: Decimal { case ↓one, ↓two } - """), - Example(""" + """, + """ enum Outer { enum Numbers: Decimal { case ↓one, ↓two } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitInitRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitInitRule.swift index c74d4dee2e..0ba938a820 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitInitRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitInitRule.swift @@ -10,16 +10,16 @@ struct ExplicitInitRule: Rule { name: "Explicit Init", description: "Explicitly calling .init() should be avoided", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ import Foundation class C: NSObject { override init() { super.init() } } - """), // super - Example(""" + """, // super + """ struct S { let n: Int } @@ -28,28 +28,28 @@ struct ExplicitInitRule: Rule { self.init(n: 1) } } - """), // self - Example(""" + """, // self + """ [1].flatMap(String.init) - """), // pass init as closure - Example(""" + """, // pass init as closure + """ [String.self].map { $0.init(1) } - """), // initialize from a metatype value - Example(""" + """, // initialize from a metatype value + """ [String.self].map { type in type.init(1) } - """), // initialize from a metatype value - Example(""" + """, // initialize from a metatype value + """ Observable.zip(obs1, obs2, resultSelector: MyType.init).asMaybe() - """), - Example("_ = GleanMetrics.Tabs.someType.init()"), - Example(""" + """, + "_ = GleanMetrics.Tabs.someType.init()", + """ Observable.zip( obs1, obs2, resultSelector: MyType.init ).asMaybe() - """), - ], + """, + ]), triggeringExamples: [ Example(""" [1].flatMap{String↓.init($0)} @@ -88,24 +88,24 @@ struct ExplicitInitRule: Rule { .init(1.0) """, excludeFromDocumentation: true), ], - corrections: [ - Example(""" + corrections: #examplesDictionary([ + """ [1].flatMap{String↓.init($0)} - """): - Example(""" + """: + """ [1].flatMap{String($0)} - """), - Example(""" + """, + """ func foo() -> [String] { return [1].flatMap { String↓.init($0) } } - """): - Example(""" + """: + """ func foo() -> [String] { return [1].flatMap { String($0) } } - """), - Example(""" + """, + """ class C { #if true func f() { @@ -113,8 +113,8 @@ struct ExplicitInitRule: Rule { } #endif } - """): - Example(""" + """: + """ class C { #if true func f() { @@ -122,33 +122,33 @@ struct ExplicitInitRule: Rule { } #endif } - """), - Example(""" + """, + """ let int = Int↓ .init(1.0) - """): - Example(""" + """: + """ let int = Int(1.0) - """), - Example(""" + """, + """ let int = Int↓ .init(1.0) - """): - Example(""" + """: + """ let int = Int(1.0) - """), - Example(""" + """, + """ let int = Int↓ .init(1.0) - """): - Example(""" + """: + """ let int = Int(1.0) - """), - Example(""" + """, + """ let int = Int↓ @@ -156,30 +156,30 @@ struct ExplicitInitRule: Rule { - """): - Example(""" + """: + """ let int = Int(1.0) - """), - Example(""" + """, + """ f { e in // comment A↓.init(e: e) } - """): - Example(""" + """: + """ f { e in // comment A(e: e) } - """), - Example("_ = GleanMetrics.Tabs.GroupedTabExtra↓.init()"): - Example("_ = GleanMetrics.Tabs.GroupedTabExtra()"), - Example("_ = Set↓.init()"): - Example("_ = Set()"), - ] + """, + "_ = GleanMetrics.Tabs.GroupedTabExtra↓.init()": + "_ = GleanMetrics.Tabs.GroupedTabExtra()", + "_ = Set↓.init()": + "_ = Set()", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTopLevelACLRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTopLevelACLRule.swift index faa8698103..31d89a7c49 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTopLevelACLRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTopLevelACLRule.swift @@ -26,13 +26,13 @@ struct ExplicitTopLevelACLRule: Rule { Example("f { func f() {} }", excludeFromDocumentation: true), Example("do { func f() {} }", excludeFromDocumentation: true), ], - triggeringExamples: [ - Example("↓enum A {}"), - Example("final ↓class B {}"), - Example("↓protocol P {}"), - Example("↓func a() {}"), - Example("internal let a = 0\n↓func b() {}"), - ] + triggeringExamples: #examples([ + "↓enum A {}", + "final ↓class B {}", + "↓protocol P {}", + "↓func a() {}", + "internal let a = 0\n↓func b() {}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTypeInterfaceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTypeInterfaceRule.swift index 4b96ddfb54..cca9b33c76 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTypeInterfaceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExplicitTypeInterfaceRule.swift @@ -36,38 +36,38 @@ struct ExplicitTypeInterfaceRule: Rule { } """, excludeFromDocumentation: true), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ class Foo { var ↓myVar = 0 } - """), - Example(""" + """, + """ class Foo { let ↓mylet = 0 } - """), - Example(""" + """, + """ class Foo { static var ↓myStaticVar = 0 } - """), - Example(""" + """, + """ class Foo { class var ↓myClassVar = 0 } - """), - Example(""" + """, + """ class Foo { let ↓myVar = Int(0), ↓s = "" } - """), - Example(""" + """, + """ class Foo { let ↓myVar = Set(0) } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExtensionAccessModifierRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExtensionAccessModifierRule.swift index 4ccb056a31..0a9cec1ab7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExtensionAccessModifierRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ExtensionAccessModifierRule.swift @@ -10,120 +10,120 @@ struct ExtensionAccessModifierRule: Rule { name: "Extension Access Modifier", description: "Prefer to use extension access modifiers", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ extension Foo: SomeProtocol { public var bar: Int { return 1 } } - """), - Example(""" + """, + """ extension Foo { private var bar: Int { return 1 } public var baz: Int { return 1 } } - """), - Example(""" + """, + """ extension Foo { private var bar: Int { return 1 } public func baz() {} } - """), - Example(""" + """, + """ extension Foo { var bar: Int { return 1 } var baz: Int { return 1 } } - """), - Example(""" + """, + """ extension Foo { var bar: Int { return 1 } internal var baz: Int { return 1 } } - """), - Example(""" + """, + """ internal extension Foo { var bar: Int { return 1 } var baz: Int { return 1 } } - """), - Example(""" + """, + """ public extension Foo { var bar: Int { return 1 } var baz: Int { return 1 } } - """), - Example(""" + """, + """ public extension Foo { var bar: Int { return 1 } internal var baz: Int { return 1 } } - """), - Example(""" + """, + """ extension Foo { private var bar: Int { return 1 } private var baz: Int { return 1 } } - """), - Example(""" + """, + """ extension Foo { open var bar: Int { return 1 } open var baz: Int { return 1 } } - """), - Example(""" + """, + """ extension Foo { func setup() {} public func update() {} } - """), - Example(""" + """, + """ private extension Foo { private var bar: Int { return 1 } var baz: Int { return 1 } } - """), - Example(""" + """, + """ extension Foo { internal private(set) var bar: Int { get { Foo.shared.bar } set { Foo.shared.bar = newValue } } } - """), - Example(""" + """, + """ extension Foo { private(set) internal var bar: Int { get { Foo.shared.bar } set { Foo.shared.bar = newValue } } } - """), - Example(""" + """, + """ public extension Foo { private(set) var value: Int { 1 } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓extension Foo { public var bar: Int { return 1 } public var baz: Int { return 1 } } - """), - Example(""" + """, + """ ↓extension Foo { public var bar: Int { return 1 } public func baz() {} } - """), - Example(""" + """, + """ public extension Foo { ↓public func bar() {} ↓public func baz() {} } - """), - Example(""" + """, + """ ↓extension Foo { public var bar: Int { let value = 1 @@ -132,8 +132,8 @@ struct ExtensionAccessModifierRule: Rule { public var baz: Int { return 1 } } - """), - Example(""" + """, + """ ↓extension Array where Element: Equatable { public var unique: [Element] { var uniqueValues = [Element]() @@ -143,8 +143,8 @@ struct ExtensionAccessModifierRule: Rule { return uniqueValues } } - """), - Example(""" + """, + """ ↓extension Foo { #if DEBUG public var bar: Int { @@ -155,19 +155,19 @@ struct ExtensionAccessModifierRule: Rule { public var baz: Int { return 1 } } - """), - Example(""" + """, + """ public extension Foo { ↓private func bar() {} ↓private func baz() {} } - """), - Example(""" + """, + """ ↓extension Foo { private(set) public var value: Int { 1 } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FallthroughRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FallthroughRule.swift index 99391ae5c8..bd9f868aaa 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FallthroughRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FallthroughRule.swift @@ -9,24 +9,24 @@ struct FallthroughRule: Rule { name: "Fallthrough", description: "Fallthrough should be avoided", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ switch foo { case .bar, .bar2, .bar3: something() } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ switch foo { case .bar: ↓fallthrough case .bar2: something() } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FatalErrorMessageRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FatalErrorMessageRule.swift index 9099a2f11d..9bb308b142 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FatalErrorMessageRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/FatalErrorMessageRule.swift @@ -9,30 +9,30 @@ struct FatalErrorMessageRule: Rule { name: "Fatal Error Message", description: "A fatalError call should have a message", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ func foo() { fatalError("Foo") } - """), - Example(""" + """, + """ func foo() { fatalError(x) } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ func foo() { ↓fatalError("") } - """), - Example(""" + """, + """ func foo() { ↓fatalError() } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceCastRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceCastRule.swift index ae4b5f5dfc..1d03e75e76 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceCastRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceCastRule.swift @@ -9,10 +9,10 @@ struct ForceCastRule: Rule { name: "Force Cast", description: "Force casts should be avoided", kind: .idiomatic, - nonTriggeringExamples: [ - Example("NSNumber() as? Int") - ], - triggeringExamples: [ Example("NSNumber() ↓as! Int") ] + nonTriggeringExamples: #examples([ + "NSNumber() as? Int" + ]), + triggeringExamples: #examples([ "NSNumber() ↓as! Int" ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceTryRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceTryRule.swift index c1387dfb37..153a4d140d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceTryRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceTryRule.swift @@ -9,20 +9,20 @@ struct ForceTryRule: Rule { name: "Force Try", description: "Force tries should be avoided", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ func a() throws {} do { try a() } catch {} - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ func a() throws {} ↓try! a() - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/GenericTypeNameRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/GenericTypeNameRule.swift index 0183738fc4..c19e48064c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/GenericTypeNameRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/GenericTypeNameRule.swift @@ -33,23 +33,23 @@ struct GenericTypeNameRule: Rule { Example("struct Foo {}"), Example("struct Bar {}"), ], - triggeringExamples: [ - Example("func foo<↓T_Foo>() {}"), - Example("func foo<↓`func`>() {}"), - Example("func foo(param: U_Foo) -> T {}"), - Example("func foo<↓\(String(repeating: "T", count: 21))>() {}"), - Example("func foo<↓type>() {}"), - Example("typealias StringDictionary<↓T_Foo> = Dictionary"), - Example("typealias BackwardTriple = (T3, T2_Bar, T1)"), - Example("typealias DictionaryOfStrings<↓T_Foo: Hashable> = Dictionary"), - ] + ["class", "struct", "enum"].flatMap { type -> [Example] in - [ - Example("\(type) Foo<↓T_Foo> {}"), - Example("\(type) Foo {}"), - Example("\(type) Foo<↓T_Foo, ↓U_Foo> {}"), - Example("\(type) Foo<↓\(String(repeating: "T", count: 21))> {}"), - Example("\(type) Foo<↓type> {}"), - ] + triggeringExamples: #examples([ + "func foo<↓T_Foo>() {}", + "func foo<↓`func`>() {}", + "func foo(param: U_Foo) -> T {}", + "func foo<↓\(String(repeating: "T", count: 21))>() {}", + "func foo<↓type>() {}", + "typealias StringDictionary<↓T_Foo> = Dictionary", + "typealias BackwardTriple = (T3, T2_Bar, T1)", + "typealias DictionaryOfStrings<↓T_Foo: Hashable> = Dictionary", + ]) + ["class", "struct", "enum"].flatMap { type -> [Example] in + #examples([ + "\(type) Foo<↓T_Foo> {}", + "\(type) Foo {}", + "\(type) Foo<↓T_Foo, ↓U_Foo> {}", + "\(type) Foo<↓\(String(repeating: "T", count: 21))> {}", + "\(type) Foo<↓type> {}", + ]) } ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ImplicitlyUnwrappedOptionalRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ImplicitlyUnwrappedOptionalRule.swift index feb337f970..79e55075d9 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ImplicitlyUnwrappedOptionalRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ImplicitlyUnwrappedOptionalRule.swift @@ -23,23 +23,23 @@ struct ImplicitlyUnwrappedOptionalRule: Rule { } """, configuration: ["mode": "all_except_iboutlets"], excludeFromDocumentation: true), ], - triggeringExamples: [ - Example("let label: ↓UILabel!"), - Example("let IBOutlet: ↓UILabel!"), - Example("let labels: [↓UILabel!]"), - Example("var ints: [↓Int!] = [42, nil, 42]"), - Example("let label: ↓IBOutlet!"), - Example("let int: ↓Int! = 42"), - Example("let int: ↓Int! = nil"), - Example("var int: ↓Int! = 42"), - Example("let collection: AnyCollection<↓Int!>"), - Example("func foo(int: ↓Int!) {}"), - Example(""" + triggeringExamples: #examples([ + "let label: ↓UILabel!", + "let IBOutlet: ↓UILabel!", + "let labels: [↓UILabel!]", + "var ints: [↓Int!] = [42, nil, 42]", + "let label: ↓IBOutlet!", + "let int: ↓Int! = 42", + "let int: ↓Int! = nil", + "var int: ↓Int! = 42", + "let collection: AnyCollection<↓Int!>", + "func foo(int: ↓Int!) {}", + """ class MyClass { weak var bar: ↓SomeObject! } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/IsDisjointRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/IsDisjointRule.swift index 63709b730e..80191ba59e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/IsDisjointRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/IsDisjointRule.swift @@ -9,16 +9,16 @@ struct IsDisjointRule: Rule { name: "Is Disjoint", description: "Prefer using `Set.isDisjoint(with:)` over `Set.intersection(_:).isEmpty`", kind: .idiomatic, - nonTriggeringExamples: [ - Example("_ = Set(syntaxKinds).isDisjoint(with: commentAndStringKindsSet)"), - Example("let isObjc = !objcAttributes.isDisjoint(with: dictionary.enclosedSwiftAttributes)"), - Example("_ = Set(syntaxKinds).intersection(commentAndStringKindsSet)"), - Example("_ = !objcAttributes.intersection(dictionary.enclosedSwiftAttributes)"), - ], - triggeringExamples: [ - Example("_ = Set(syntaxKinds).↓intersection(commentAndStringKindsSet).isEmpty"), - Example("let isObjc = !objcAttributes.↓intersection(dictionary.enclosedSwiftAttributes).isEmpty"), - ] + nonTriggeringExamples: #examples([ + "_ = Set(syntaxKinds).isDisjoint(with: commentAndStringKindsSet)", + "let isObjc = !objcAttributes.isDisjoint(with: dictionary.enclosedSwiftAttributes)", + "_ = Set(syntaxKinds).intersection(commentAndStringKindsSet)", + "_ = !objcAttributes.intersection(dictionary.enclosedSwiftAttributes)", + ]), + triggeringExamples: #examples([ + "_ = Set(syntaxKinds).↓intersection(commentAndStringKindsSet).isEmpty", + "let isObjc = !objcAttributes.↓intersection(dictionary.enclosedSwiftAttributes).isEmpty", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/JoinedDefaultParameterRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/JoinedDefaultParameterRule.swift index 78ac3a2cfa..2d3877b5a5 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/JoinedDefaultParameterRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/JoinedDefaultParameterRule.swift @@ -9,32 +9,32 @@ struct JoinedDefaultParameterRule: Rule { name: "Joined Default Parameter", description: "Discouraged explicit usage of the default separator", kind: .idiomatic, - nonTriggeringExamples: [ - Example("let foo = bar.joined()"), - Example("let foo = bar.joined(separator: \",\")"), - Example("let foo = bar.joined(separator: toto)"), - ], - triggeringExamples: [ - Example("let foo = bar.joined(↓separator: \"\")"), - Example(""" + nonTriggeringExamples: #examples([ + "let foo = bar.joined()", + "let foo = bar.joined(separator: \",\")", + "let foo = bar.joined(separator: toto)", + ]), + triggeringExamples: #examples([ + "let foo = bar.joined(↓separator: \"\")", + """ let foo = bar.filter(toto) .joined(↓separator: ""), - """), - Example(""" + """, + """ func foo() -> String { return ["1", "2"].joined(↓separator: "") } - """), - ], - corrections: [ - Example("let foo = bar.joined(↓separator: \"\")"): Example("let foo = bar.joined()"), - Example("let foo = bar.filter(toto)\n.joined(↓separator: \"\")"): - Example("let foo = bar.filter(toto)\n.joined()"), - Example("func foo() -> String {\n return [\"1\", \"2\"].joined(↓separator: \"\")\n}"): - Example("func foo() -> String {\n return [\"1\", \"2\"].joined()\n}"), - Example("class C {\n#if true\nlet foo = bar.joined(↓separator: \"\")\n#endif\n}"): - Example("class C {\n#if true\nlet foo = bar.joined()\n#endif\n}"), - ] + """, + ]), + corrections: #examplesDictionary([ + "let foo = bar.joined(↓separator: \"\")": "let foo = bar.joined()", + "let foo = bar.filter(toto)\n.joined(↓separator: \"\")": + "let foo = bar.filter(toto)\n.joined()", + "func foo() -> String {\n return [\"1\", \"2\"].joined(↓separator: \"\")\n}": + "func foo() -> String {\n return [\"1\", \"2\"].joined()\n}", + "class C {\n#if true\nlet foo = bar.joined(↓separator: \"\")\n#endif\n}": + "class C {\n#if true\nlet foo = bar.joined()\n#endif\n}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyCGGeometryFunctionsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyCGGeometryFunctionsRule.swift index 9f5775335a..7b7791bbfe 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyCGGeometryFunctionsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyCGGeometryFunctionsRule.swift @@ -9,75 +9,75 @@ struct LegacyCGGeometryFunctionsRule: Rule { name: "Legacy CGGeometry Functions", description: "Struct extension properties and methods are preferred over legacy functions", kind: .idiomatic, - nonTriggeringExamples: [ - Example("rect.width"), - Example("rect.height"), - Example("rect.minX"), - Example("rect.midX"), - Example("rect.maxX"), - Example("rect.minY"), - Example("rect.midY"), - Example("rect.maxY"), - Example("rect.isNull"), - Example("rect.isEmpty"), - Example("rect.isInfinite"), - Example("rect.standardized"), - Example("rect.integral"), - Example("rect.insetBy(dx: 5.0, dy: -7.0)"), - Example("rect.offsetBy(dx: 5.0, dy: -7.0)"), - Example("rect1.union(rect2)"), - Example("rect1.intersect(rect2)"), + nonTriggeringExamples: #examples([ + "rect.width", + "rect.height", + "rect.minX", + "rect.midX", + "rect.maxX", + "rect.minY", + "rect.midY", + "rect.maxY", + "rect.isNull", + "rect.isEmpty", + "rect.isInfinite", + "rect.standardized", + "rect.integral", + "rect.insetBy(dx: 5.0, dy: -7.0)", + "rect.offsetBy(dx: 5.0, dy: -7.0)", + "rect1.union(rect2)", + "rect1.intersect(rect2)", // "rect.divide(atDistance: 10.2, fromEdge: edge)", No correction available for divide - Example("rect1.contains(rect2)"), - Example("rect.contains(point)"), - Example("rect1.intersects(rect2)"), - ], - triggeringExamples: [ - Example("↓CGRectGetWidth(rect)"), - Example("↓CGRectGetHeight(rect)"), - Example("↓CGRectGetMinX(rect)"), - Example("↓CGRectGetMidX(rect)"), - Example("↓CGRectGetMaxX(rect)"), - Example("↓CGRectGetMinY(rect)"), - Example("↓CGRectGetMidY(rect)"), - Example("↓CGRectGetMaxY(rect)"), - Example("↓CGRectIsNull(rect)"), - Example("↓CGRectIsEmpty(rect)"), - Example("↓CGRectIsInfinite(rect)"), - Example("↓CGRectStandardize(rect)"), - Example("↓CGRectIntegral(rect)"), - Example("↓CGRectInset(rect, 10, 5)"), - Example("↓CGRectOffset(rect, -2, 8.3)"), - Example("↓CGRectUnion(rect1, rect2)"), - Example("↓CGRectIntersection(rect1, rect2)"), - Example("↓CGRectContainsRect(rect1, rect2)"), - Example("↓CGRectContainsPoint(rect, point)"), - Example("↓CGRectIntersectsRect(rect1, rect2)"), - ], - corrections: [ - Example("↓CGRectGetWidth( rect )"): Example("rect.width"), - Example("↓CGRectGetHeight(rect )"): Example("rect.height"), - Example("↓CGRectGetMinX( rect)"): Example("rect.minX"), - Example("↓CGRectGetMidX( rect)"): Example("rect.midX"), - Example("↓CGRectGetMaxX( rect)"): Example("rect.maxX"), - Example("↓CGRectGetMinY(rect )"): Example("rect.minY"), - Example("↓CGRectGetMidY(rect )"): Example("rect.midY"), - Example("↓CGRectGetMaxY( rect )"): Example("rect.maxY"), - Example("↓CGRectIsNull( rect )"): Example("rect.isNull"), - Example("↓CGRectIsEmpty( rect )"): Example("rect.isEmpty"), - Example("↓CGRectIsInfinite( rect )"): Example("rect.isInfinite"), - Example("↓CGRectStandardize( rect)"): Example("rect.standardized"), - Example("↓CGRectIntegral(rect )"): Example("rect.integral"), - Example("↓CGRectInset(rect, 5.0, -7.0)"): Example("rect.insetBy(dx: 5.0, dy: -7.0)"), - Example("↓CGRectOffset(rect, -2, 8.3)"): Example("rect.offsetBy(dx: -2, dy: 8.3)"), - Example("↓CGRectUnion(rect1, rect2)"): Example("rect1.union(rect2)"), - Example("↓CGRectIntersection( rect1 ,rect2)"): Example("rect1.intersection(rect2)"), - Example("↓CGRectContainsRect( rect1,rect2 )"): Example("rect1.contains(rect2)"), - Example("↓CGRectContainsPoint(rect ,point)"): Example("rect.contains(point)"), - Example("↓CGRectIntersectsRect( rect1,rect2 )"): Example("rect1.intersects(rect2)"), - Example("↓CGRectIntersectsRect(rect1, rect2 )\n↓CGRectGetWidth(rect )"): - Example("rect1.intersects(rect2)\nrect.width"), - ] + "rect1.contains(rect2)", + "rect.contains(point)", + "rect1.intersects(rect2)", + ]), + triggeringExamples: #examples([ + "↓CGRectGetWidth(rect)", + "↓CGRectGetHeight(rect)", + "↓CGRectGetMinX(rect)", + "↓CGRectGetMidX(rect)", + "↓CGRectGetMaxX(rect)", + "↓CGRectGetMinY(rect)", + "↓CGRectGetMidY(rect)", + "↓CGRectGetMaxY(rect)", + "↓CGRectIsNull(rect)", + "↓CGRectIsEmpty(rect)", + "↓CGRectIsInfinite(rect)", + "↓CGRectStandardize(rect)", + "↓CGRectIntegral(rect)", + "↓CGRectInset(rect, 10, 5)", + "↓CGRectOffset(rect, -2, 8.3)", + "↓CGRectUnion(rect1, rect2)", + "↓CGRectIntersection(rect1, rect2)", + "↓CGRectContainsRect(rect1, rect2)", + "↓CGRectContainsPoint(rect, point)", + "↓CGRectIntersectsRect(rect1, rect2)", + ]), + corrections: #examplesDictionary([ + "↓CGRectGetWidth( rect )": "rect.width", + "↓CGRectGetHeight(rect )": "rect.height", + "↓CGRectGetMinX( rect)": "rect.minX", + "↓CGRectGetMidX( rect)": "rect.midX", + "↓CGRectGetMaxX( rect)": "rect.maxX", + "↓CGRectGetMinY(rect )": "rect.minY", + "↓CGRectGetMidY(rect )": "rect.midY", + "↓CGRectGetMaxY( rect )": "rect.maxY", + "↓CGRectIsNull( rect )": "rect.isNull", + "↓CGRectIsEmpty( rect )": "rect.isEmpty", + "↓CGRectIsInfinite( rect )": "rect.isInfinite", + "↓CGRectStandardize( rect)": "rect.standardized", + "↓CGRectIntegral(rect )": "rect.integral", + "↓CGRectInset(rect, 5.0, -7.0)": "rect.insetBy(dx: 5.0, dy: -7.0)", + "↓CGRectOffset(rect, -2, 8.3)": "rect.offsetBy(dx: -2, dy: 8.3)", + "↓CGRectUnion(rect1, rect2)": "rect1.union(rect2)", + "↓CGRectIntersection( rect1 ,rect2)": "rect1.intersection(rect2)", + "↓CGRectContainsRect( rect1,rect2 )": "rect1.contains(rect2)", + "↓CGRectContainsPoint(rect ,point)": "rect.contains(point)", + "↓CGRectIntersectsRect( rect1,rect2 )": "rect1.intersects(rect2)", + "↓CGRectIntersectsRect(rect1, rect2 )\n↓CGRectGetWidth(rect )": + "rect1.intersects(rect2)\nrect.width", + ]) ) private static let legacyFunctions: [String: LegacyFunctionRewriteStrategy] = [ diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstantRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstantRuleExamples.swift index b7267bae49..4cd2a9f591 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstantRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstantRuleExamples.swift @@ -1,44 +1,44 @@ internal struct LegacyConstantRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example("CGRect.infinite"), - Example("CGPoint.zero"), - Example("CGRect.zero"), - Example("CGSize.zero"), - Example("NSPoint.zero"), - Example("NSRect.zero"), - Example("NSSize.zero"), - Example("CGRect.null"), - Example("CGFloat.pi"), - Example("Float.pi"), - ] + static let nonTriggeringExamples: [Example] = #examples([ + "CGRect.infinite", + "CGPoint.zero", + "CGRect.zero", + "CGSize.zero", + "NSPoint.zero", + "NSRect.zero", + "NSSize.zero", + "CGRect.null", + "CGFloat.pi", + "Float.pi", + ]) - static let triggeringExamples: [Example] = [ - Example("↓CGRectInfinite"), - Example("↓CGPointZero"), - Example("↓CGRectZero"), - Example("↓CGSizeZero"), - Example("↓NSZeroPoint"), - Example("↓NSZeroRect"), - Example("↓NSZeroSize"), - Example("↓CGRectNull"), - Example("↓CGFloat(M_PI)"), - Example("↓Float(M_PI)"), - ] + static let triggeringExamples: [Example] = #examples([ + "↓CGRectInfinite", + "↓CGPointZero", + "↓CGRectZero", + "↓CGSizeZero", + "↓NSZeroPoint", + "↓NSZeroRect", + "↓NSZeroSize", + "↓CGRectNull", + "↓CGFloat(M_PI)", + "↓Float(M_PI)", + ]) - static let corrections: [Example: Example] = [ - Example("↓CGRectInfinite"): Example("CGRect.infinite"), - Example("↓CGPointZero"): Example("CGPoint.zero"), - Example("↓CGRectZero"): Example("CGRect.zero"), - Example("↓CGSizeZero"): Example("CGSize.zero"), - Example("↓NSZeroPoint"): Example("NSPoint.zero"), - Example("↓NSZeroRect"): Example("NSRect.zero"), - Example("↓NSZeroSize"): Example("NSSize.zero"), - Example("↓CGRectNull"): Example("CGRect.null"), - Example("↓CGRectInfinite\n↓CGRectNull"): Example("CGRect.infinite\nCGRect.null"), - Example("↓CGFloat(M_PI)"): Example("CGFloat.pi"), - Example("↓Float(M_PI)"): Example("Float.pi"), - Example("↓CGFloat(M_PI)\n↓Float(M_PI)"): Example("CGFloat.pi\nFloat.pi"), - ] + static let corrections: [Example: Example] = #examplesDictionary([ + "↓CGRectInfinite": "CGRect.infinite", + "↓CGPointZero": "CGPoint.zero", + "↓CGRectZero": "CGRect.zero", + "↓CGSizeZero": "CGSize.zero", + "↓NSZeroPoint": "NSPoint.zero", + "↓NSZeroRect": "NSRect.zero", + "↓NSZeroSize": "NSSize.zero", + "↓CGRectNull": "CGRect.null", + "↓CGRectInfinite\n↓CGRectNull": "CGRect.infinite\nCGRect.null", + "↓CGFloat(M_PI)": "CGFloat.pi", + "↓Float(M_PI)": "Float.pi", + "↓CGFloat(M_PI)\n↓Float(M_PI)": "CGFloat.pi\nFloat.pi", + ]) static let patterns = [ "CGRectInfinite": "CGRect.infinite", diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstructorRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstructorRule.swift index c9a2f2dd75..bce15805df 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstructorRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyConstructorRule.swift @@ -9,94 +9,94 @@ struct LegacyConstructorRule: Rule { name: "Legacy Constructor", description: "Swift constructors are preferred over legacy convenience functions", kind: .idiomatic, - nonTriggeringExamples: [ - Example("CGPoint(x: 10, y: 10)"), - Example("CGPoint(x: xValue, y: yValue)"), - Example("CGSize(width: 10, height: 10)"), - Example("CGSize(width: aWidth, height: aHeight)"), - Example("CGRect(x: 0, y: 0, width: 10, height: 10)"), - Example("CGRect(x: xVal, y: yVal, width: aWidth, height: aHeight)"), - Example("CGVector(dx: 10, dy: 10)"), - Example("CGVector(dx: deltaX, dy: deltaY)"), - Example("NSPoint(x: 10, y: 10)"), - Example("NSPoint(x: xValue, y: yValue)"), - Example("NSSize(width: 10, height: 10)"), - Example("NSSize(width: aWidth, height: aHeight)"), - Example("NSRect(x: 0, y: 0, width: 10, height: 10)"), - Example("NSRect(x: xVal, y: yVal, width: aWidth, height: aHeight)"), - Example("NSRange(location: 10, length: 1)"), - Example("NSRange(location: loc, length: len)"), - Example("UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)"), - Example("UIEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)"), - Example("NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)"), - Example("NSEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)"), - Example("UIOffset(horizontal: 0, vertical: 10)"), - Example("UIOffset(horizontal: horizontal, vertical: vertical)"), - ], - triggeringExamples: [ - Example("↓CGPointMake(10, 10)"), - Example("↓CGPointMake(xVal, yVal)"), - Example("↓CGPointMake(calculateX(), 10)"), - Example("↓CGSizeMake(10, 10)"), - Example("↓CGSizeMake(aWidth, aHeight)"), - Example("↓CGRectMake(0, 0, 10, 10)"), - Example("↓CGRectMake(xVal, yVal, width, height)"), - Example("↓CGVectorMake(10, 10)"), - Example("↓CGVectorMake(deltaX, deltaY)"), - Example("↓NSMakePoint(10, 10)"), - Example("↓NSMakePoint(xVal, yVal)"), - Example("↓NSMakeSize(10, 10)"), - Example("↓NSMakeSize(aWidth, aHeight)"), - Example("↓NSMakeRect(0, 0, 10, 10)"), - Example("↓NSMakeRect(xVal, yVal, width, height)"), - Example("↓NSMakeRange(10, 1)"), - Example("↓NSMakeRange(loc, len)"), - Example("↓UIEdgeInsetsMake(0, 0, 10, 10)"), - Example("↓UIEdgeInsetsMake(top, left, bottom, right)"), - Example("↓NSEdgeInsetsMake(0, 0, 10, 10)"), - Example("↓NSEdgeInsetsMake(top, left, bottom, right)"), - Example("↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)"), - Example("↓UIOffsetMake(0, 10)"), - Example("↓UIOffsetMake(horizontal, vertical)"), - ], - corrections: [ - Example("↓CGPointMake(10, 10)"): Example("CGPoint(x: 10, y: 10)"), - Example("↓CGPointMake(xPos, yPos)"): Example("CGPoint(x: xPos, y: yPos)"), - Example("↓CGSizeMake(10, 10)"): Example("CGSize(width: 10, height: 10)"), - Example("↓CGSizeMake( aWidth, aHeight )"): Example("CGSize( width: aWidth, height: aHeight )"), - Example("↓CGRectMake(0, 0, 10, 10)"): Example("CGRect(x: 0, y: 0, width: 10, height: 10)"), - Example("↓CGRectMake(xPos, yPos , width, height)"): - Example("CGRect(x: xPos, y: yPos , width: width, height: height)"), - Example("↓CGVectorMake(10, 10)"): Example("CGVector(dx: 10, dy: 10)"), - Example("↓CGVectorMake(deltaX, deltaY)"): Example("CGVector(dx: deltaX, dy: deltaY)"), - Example("↓NSMakePoint(10, 10 )"): Example("NSPoint(x: 10, y: 10 )"), - Example("↓NSMakePoint(xPos, yPos )"): Example("NSPoint(x: xPos, y: yPos )"), - Example("↓NSMakeSize(10, 10)"): Example("NSSize(width: 10, height: 10)"), - Example("↓NSMakeSize( aWidth, aHeight )"): Example("NSSize( width: aWidth, height: aHeight )"), - Example("↓NSMakeRect(0, 0, 10, 10)"): Example("NSRect(x: 0, y: 0, width: 10, height: 10)"), - Example("↓NSMakeRect(xPos, yPos , width, height)"): - Example("NSRect(x: xPos, y: yPos , width: width, height: height)"), - Example("↓NSMakeRange(10, 1)"): Example("NSRange(location: 10, length: 1)"), - Example("↓NSMakeRange(loc, len)"): Example("NSRange(location: loc, length: len)"), - Example("↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)"): - Example("CGVector(dx: 10, dy: 10)\nNSRange(location: 10, length: 1)"), - Example("↓CGVectorMake(dx, dy)\n↓NSMakeRange(loc, len)"): - Example("CGVector(dx: dx, dy: dy)\nNSRange(location: loc, length: len)"), - Example("↓UIEdgeInsetsMake(0, 0, 10, 10)"): - Example("UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)"), - Example("↓UIEdgeInsetsMake(top, left, bottom, right)"): - Example("UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)"), - Example("↓NSEdgeInsetsMake(0, 0, 10, 10)"): - Example("NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)"), - Example("↓NSEdgeInsetsMake(top, left, bottom, right)"): - Example("NSEdgeInsets(top: top, left: left, bottom: bottom, right: right)"), - Example("↓NSMakeRange(0, attributedString.length)"): - Example("NSRange(location: 0, length: attributedString.length)"), - Example("↓CGPointMake(calculateX(), 10)"): Example("CGPoint(x: calculateX(), y: 10)"), - Example("↓UIOffsetMake(0, 10)"): Example("UIOffset(horizontal: 0, vertical: 10)"), - Example("↓UIOffsetMake(horizontal, vertical)"): - Example("UIOffset(horizontal: horizontal, vertical: vertical)"), - ] + nonTriggeringExamples: #examples([ + "CGPoint(x: 10, y: 10)", + "CGPoint(x: xValue, y: yValue)", + "CGSize(width: 10, height: 10)", + "CGSize(width: aWidth, height: aHeight)", + "CGRect(x: 0, y: 0, width: 10, height: 10)", + "CGRect(x: xVal, y: yVal, width: aWidth, height: aHeight)", + "CGVector(dx: 10, dy: 10)", + "CGVector(dx: deltaX, dy: deltaY)", + "NSPoint(x: 10, y: 10)", + "NSPoint(x: xValue, y: yValue)", + "NSSize(width: 10, height: 10)", + "NSSize(width: aWidth, height: aHeight)", + "NSRect(x: 0, y: 0, width: 10, height: 10)", + "NSRect(x: xVal, y: yVal, width: aWidth, height: aHeight)", + "NSRange(location: 10, length: 1)", + "NSRange(location: loc, length: len)", + "UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)", + "UIEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)", + "NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)", + "NSEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)", + "UIOffset(horizontal: 0, vertical: 10)", + "UIOffset(horizontal: horizontal, vertical: vertical)", + ]), + triggeringExamples: #examples([ + "↓CGPointMake(10, 10)", + "↓CGPointMake(xVal, yVal)", + "↓CGPointMake(calculateX(), 10)", + "↓CGSizeMake(10, 10)", + "↓CGSizeMake(aWidth, aHeight)", + "↓CGRectMake(0, 0, 10, 10)", + "↓CGRectMake(xVal, yVal, width, height)", + "↓CGVectorMake(10, 10)", + "↓CGVectorMake(deltaX, deltaY)", + "↓NSMakePoint(10, 10)", + "↓NSMakePoint(xVal, yVal)", + "↓NSMakeSize(10, 10)", + "↓NSMakeSize(aWidth, aHeight)", + "↓NSMakeRect(0, 0, 10, 10)", + "↓NSMakeRect(xVal, yVal, width, height)", + "↓NSMakeRange(10, 1)", + "↓NSMakeRange(loc, len)", + "↓UIEdgeInsetsMake(0, 0, 10, 10)", + "↓UIEdgeInsetsMake(top, left, bottom, right)", + "↓NSEdgeInsetsMake(0, 0, 10, 10)", + "↓NSEdgeInsetsMake(top, left, bottom, right)", + "↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)", + "↓UIOffsetMake(0, 10)", + "↓UIOffsetMake(horizontal, vertical)", + ]), + corrections: #examplesDictionary([ + "↓CGPointMake(10, 10)": "CGPoint(x: 10, y: 10)", + "↓CGPointMake(xPos, yPos)": "CGPoint(x: xPos, y: yPos)", + "↓CGSizeMake(10, 10)": "CGSize(width: 10, height: 10)", + "↓CGSizeMake( aWidth, aHeight )": "CGSize( width: aWidth, height: aHeight )", + "↓CGRectMake(0, 0, 10, 10)": "CGRect(x: 0, y: 0, width: 10, height: 10)", + "↓CGRectMake(xPos, yPos , width, height)": + "CGRect(x: xPos, y: yPos , width: width, height: height)", + "↓CGVectorMake(10, 10)": "CGVector(dx: 10, dy: 10)", + "↓CGVectorMake(deltaX, deltaY)": "CGVector(dx: deltaX, dy: deltaY)", + "↓NSMakePoint(10, 10 )": "NSPoint(x: 10, y: 10 )", + "↓NSMakePoint(xPos, yPos )": "NSPoint(x: xPos, y: yPos )", + "↓NSMakeSize(10, 10)": "NSSize(width: 10, height: 10)", + "↓NSMakeSize( aWidth, aHeight )": "NSSize( width: aWidth, height: aHeight )", + "↓NSMakeRect(0, 0, 10, 10)": "NSRect(x: 0, y: 0, width: 10, height: 10)", + "↓NSMakeRect(xPos, yPos , width, height)": + "NSRect(x: xPos, y: yPos , width: width, height: height)", + "↓NSMakeRange(10, 1)": "NSRange(location: 10, length: 1)", + "↓NSMakeRange(loc, len)": "NSRange(location: loc, length: len)", + "↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)": + "CGVector(dx: 10, dy: 10)\nNSRange(location: 10, length: 1)", + "↓CGVectorMake(dx, dy)\n↓NSMakeRange(loc, len)": + "CGVector(dx: dx, dy: dy)\nNSRange(location: loc, length: len)", + "↓UIEdgeInsetsMake(0, 0, 10, 10)": + "UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)", + "↓UIEdgeInsetsMake(top, left, bottom, right)": + "UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)", + "↓NSEdgeInsetsMake(0, 0, 10, 10)": + "NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)", + "↓NSEdgeInsetsMake(top, left, bottom, right)": + "NSEdgeInsets(top: top, left: left, bottom: bottom, right: right)", + "↓NSMakeRange(0, attributedString.length)": + "NSRange(location: 0, length: attributedString.length)", + "↓CGPointMake(calculateX(), 10)": "CGPoint(x: calculateX(), y: 10)", + "↓UIOffsetMake(0, 10)": "UIOffset(horizontal: 0, vertical: 10)", + "↓UIOffsetMake(horizontal, vertical)": + "UIOffset(horizontal: horizontal, vertical: vertical)", + ]) ) private static let constructorsToArguments = [ diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyHashingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyHashingRule.swift index 9ef7c6db57..01c5ca6424 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyHashingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyHashingRule.swift @@ -9,8 +9,8 @@ struct LegacyHashingRule: Rule { name: "Legacy Hashing", description: "Prefer using the `hash(into:)` function instead of overriding `hashValue`", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ struct Foo: Hashable { let bar: Int = 10 @@ -18,8 +18,8 @@ struct LegacyHashingRule: Rule { hasher.combine(bar) } } - """), - Example(""" + """, + """ class Foo: Hashable { let bar: Int = 10 @@ -27,12 +27,12 @@ struct LegacyHashingRule: Rule { hasher.combine(bar) } } - """), - Example(""" + """, + """ var hashValue: Int { return 1 } class Foo: Hashable { \n } - """), - Example(""" + """, + """ class Foo: Hashable { let bar: String = "Foo" @@ -40,8 +40,8 @@ struct LegacyHashingRule: Rule { return bar } } - """), - Example(""" + """, + """ class Foo: Hashable { let bar: String = "Foo" @@ -50,10 +50,10 @@ struct LegacyHashingRule: Rule { set { bar = newValue } } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ struct Foo: Hashable { let bar: Int = 10 @@ -61,8 +61,8 @@ struct LegacyHashingRule: Rule { return bar } } - """), - Example(""" + """, + """ class Foo: Hashable { let bar: Int = 10 @@ -70,8 +70,8 @@ struct LegacyHashingRule: Rule { return bar } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyMultipleRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyMultipleRule.swift index e450ea58c5..09fb5e7cd5 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyMultipleRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyMultipleRule.swift @@ -9,33 +9,33 @@ struct LegacyMultipleRule: Rule { name: "Legacy Multiple", description: "Prefer using the `isMultiple(of:)` function instead of using the remainder operator (`%`)", kind: .idiomatic, - nonTriggeringExamples: [ - Example("cell.contentView.backgroundColor = indexPath.row.isMultiple(of: 2) ? .gray : .white"), - Example("guard count.isMultiple(of: 2) else { throw DecodingError.dataCorrupted(...) }"), - Example("sanityCheck(bytes > 0 && bytes.isMultiple(of: 4), \"capacity must be multiple of 4 bytes\")"), - Example("guard let i = reversedNumbers.firstIndex(where: { $0.isMultiple(of: 2) }) else { return }"), - Example(""" + nonTriggeringExamples: #examples([ + "cell.contentView.backgroundColor = indexPath.row.isMultiple(of: 2) ? .gray : .white", + "guard count.isMultiple(of: 2) else { throw DecodingError.dataCorrupted(...) }", + "sanityCheck(bytes > 0 && bytes.isMultiple(of: 4), \"capacity must be multiple of 4 bytes\")", + "guard let i = reversedNumbers.firstIndex(where: { $0.isMultiple(of: 2) }) else { return }", + """ let constant = 56 let isMultiple = value.isMultiple(of: constant) - """), - Example(""" + """, + """ let constant = 56 let secret = value % constant == 5 - """), - Example("let secretValue = (value % 3) + 2"), - ], - triggeringExamples: [ - Example("cell.contentView.backgroundColor = indexPath.row ↓% 2 == 0 ? .gray : .white"), - Example("cell.contentView.backgroundColor = 0 == indexPath.row ↓% 2 ? .gray : .white"), - Example("cell.contentView.backgroundColor = indexPath.row ↓% 2 != 0 ? .gray : .white"), - Example("guard count ↓% 2 == 0 else { throw DecodingError.dataCorrupted(...) }"), - Example("sanityCheck(bytes > 0 && bytes ↓% 4 == 0, \"capacity must be multiple of 4 bytes\")"), - Example("guard let i = reversedNumbers.firstIndex(where: { $0 ↓% 2 == 0 }) else { return }"), - Example(""" + """, + "let secretValue = (value % 3) + 2", + ]), + triggeringExamples: #examples([ + "cell.contentView.backgroundColor = indexPath.row ↓% 2 == 0 ? .gray : .white", + "cell.contentView.backgroundColor = 0 == indexPath.row ↓% 2 ? .gray : .white", + "cell.contentView.backgroundColor = indexPath.row ↓% 2 != 0 ? .gray : .white", + "guard count ↓% 2 == 0 else { throw DecodingError.dataCorrupted(...) }", + "sanityCheck(bytes > 0 && bytes ↓% 4 == 0, \"capacity must be multiple of 4 bytes\")", + "guard let i = reversedNumbers.firstIndex(where: { $0 ↓% 2 == 0 }) else { return }", + """ let constant = 56 let isMultiple = value ↓% constant == 0 - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyNSGeometryFunctionsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyNSGeometryFunctionsRule.swift index d78eda0d89..dda3e998d2 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyNSGeometryFunctionsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyNSGeometryFunctionsRule.swift @@ -9,74 +9,74 @@ struct LegacyNSGeometryFunctionsRule: Rule { name: "Legacy NSGeometry Functions", description: "Struct extension properties and methods are preferred over legacy functions", kind: .idiomatic, - nonTriggeringExamples: [ - Example("rect.width"), - Example("rect.height"), - Example("rect.minX"), - Example("rect.midX"), - Example("rect.maxX"), - Example("rect.minY"), - Example("rect.midY"), - Example("rect.maxY"), - Example("rect.isEmpty"), - Example("rect.integral"), - Example("rect.insetBy(dx: 5.0, dy: -7.0)"), - Example("rect.offsetBy(dx: 5.0, dy: -7.0)"), - Example("rect1.union(rect2)"), - Example("rect1.intersection(rect2)"), + nonTriggeringExamples: #examples([ + "rect.width", + "rect.height", + "rect.minX", + "rect.midX", + "rect.maxX", + "rect.minY", + "rect.midY", + "rect.maxY", + "rect.isEmpty", + "rect.integral", + "rect.insetBy(dx: 5.0, dy: -7.0)", + "rect.offsetBy(dx: 5.0, dy: -7.0)", + "rect1.union(rect2)", + "rect1.intersection(rect2)", // "rect.divide(atDistance: 10.2, fromEdge: edge)", No correction available for divide - Example("rect1.contains(rect2)"), - Example("rect.contains(point)"), - Example("rect1.intersects(rect2)"), - ], - triggeringExamples: [ - Example("↓NSWidth(rect)"), - Example("↓NSHeight(rect)"), - Example("↓NSMinX(rect)"), - Example("↓NSMidX(rect)"), - Example("↓NSMaxX(rect)"), - Example("↓NSMinY(rect)"), - Example("↓NSMidY(rect)"), - Example("↓NSMaxY(rect)"), - Example("↓NSEqualRects(rect1, rect2)"), - Example("↓NSEqualSizes(size1, size2)"), - Example("↓NSEqualPoints(point1, point2)"), - Example("↓NSEdgeInsetsEqual(insets2, insets2)"), - Example("↓NSIsEmptyRect(rect)"), - Example("↓NSIntegralRect(rect)"), - Example("↓NSInsetRect(rect, 10, 5)"), - Example("↓NSOffsetRect(rect, -2, 8.3)"), - Example("↓NSUnionRect(rect1, rect2)"), - Example("↓NSIntersectionRect(rect1, rect2)"), - Example("↓NSContainsRect(rect1, rect2)"), - Example("↓NSPointInRect(rect, point)"), - Example("↓NSIntersectsRect(rect1, rect2)"), - ], - corrections: [ - Example("↓NSWidth( rect )"): Example("rect.width"), - Example("↓NSHeight(rect )"): Example("rect.height"), - Example("↓NSMinX( rect)"): Example("rect.minX"), - Example("↓NSMidX( rect)"): Example("rect.midX"), - Example("↓NSMaxX( rect)"): Example("rect.maxX"), - Example("↓NSMinY(rect )"): Example("rect.minY"), - Example("↓NSMidY(rect )"): Example("rect.midY"), - Example("↓NSMaxY( rect )"): Example("rect.maxY"), - Example("↓NSEqualPoints( point1 , point2)"): Example("point1 == point2"), - Example("↓NSEqualSizes(size1,size2 )"): Example("size1 == size2"), - Example("↓NSEqualRects( rect1, rect2)"): Example("rect1 == rect2"), - Example("↓NSEdgeInsetsEqual(insets1, insets2)"): Example("insets1 == insets2"), - Example("↓NSIsEmptyRect( rect )"): Example("rect.isEmpty"), - Example("↓NSIntegralRect(rect )"): Example("rect.integral"), - Example("↓NSInsetRect(rect, 5.0, -7.0)"): Example("rect.insetBy(dx: 5.0, dy: -7.0)"), - Example("↓NSOffsetRect(rect, -2, 8.3)"): Example("rect.offsetBy(dx: -2, dy: 8.3)"), - Example("↓NSUnionRect(rect1, rect2)"): Example("rect1.union(rect2)"), - Example("↓NSContainsRect( rect1,rect2 )"): Example("rect1.contains(rect2)"), - Example("↓NSPointInRect(point ,rect)"): Example("rect.contains(point)"), // note order of arguments - Example("↓NSIntersectsRect( rect1,rect2 )"): Example("rect1.intersects(rect2)"), - Example("↓NSIntersectsRect(rect1, rect2 )\n↓NSWidth(rect )"): - Example("rect1.intersects(rect2)\nrect.width"), - Example("↓NSIntersectionRect(rect1, rect2)"): Example("rect1.intersection(rect2)"), - ] + "rect1.contains(rect2)", + "rect.contains(point)", + "rect1.intersects(rect2)", + ]), + triggeringExamples: #examples([ + "↓NSWidth(rect)", + "↓NSHeight(rect)", + "↓NSMinX(rect)", + "↓NSMidX(rect)", + "↓NSMaxX(rect)", + "↓NSMinY(rect)", + "↓NSMidY(rect)", + "↓NSMaxY(rect)", + "↓NSEqualRects(rect1, rect2)", + "↓NSEqualSizes(size1, size2)", + "↓NSEqualPoints(point1, point2)", + "↓NSEdgeInsetsEqual(insets2, insets2)", + "↓NSIsEmptyRect(rect)", + "↓NSIntegralRect(rect)", + "↓NSInsetRect(rect, 10, 5)", + "↓NSOffsetRect(rect, -2, 8.3)", + "↓NSUnionRect(rect1, rect2)", + "↓NSIntersectionRect(rect1, rect2)", + "↓NSContainsRect(rect1, rect2)", + "↓NSPointInRect(rect, point)", + "↓NSIntersectsRect(rect1, rect2)", + ]), + corrections: #examplesDictionary([ + "↓NSWidth( rect )": "rect.width", + "↓NSHeight(rect )": "rect.height", + "↓NSMinX( rect)": "rect.minX", + "↓NSMidX( rect)": "rect.midX", + "↓NSMaxX( rect)": "rect.maxX", + "↓NSMinY(rect )": "rect.minY", + "↓NSMidY(rect )": "rect.midY", + "↓NSMaxY( rect )": "rect.maxY", + "↓NSEqualPoints( point1 , point2)": "point1 == point2", + "↓NSEqualSizes(size1,size2 )": "size1 == size2", + "↓NSEqualRects( rect1, rect2)": "rect1 == rect2", + "↓NSEdgeInsetsEqual(insets1, insets2)": "insets1 == insets2", + "↓NSIsEmptyRect( rect )": "rect.isEmpty", + "↓NSIntegralRect(rect )": "rect.integral", + "↓NSInsetRect(rect, 5.0, -7.0)": "rect.insetBy(dx: 5.0, dy: -7.0)", + "↓NSOffsetRect(rect, -2, 8.3)": "rect.offsetBy(dx: -2, dy: 8.3)", + "↓NSUnionRect(rect1, rect2)": "rect1.union(rect2)", + "↓NSContainsRect( rect1,rect2 )": "rect1.contains(rect2)", + "↓NSPointInRect(point ,rect)": "rect.contains(point)", // note order of arguments + "↓NSIntersectsRect( rect1,rect2 )": "rect1.intersects(rect2)", + "↓NSIntersectsRect(rect1, rect2 )\n↓NSWidth(rect )": + "rect1.intersects(rect2)\nrect.width", + "↓NSIntersectionRect(rect1, rect2)": "rect1.intersection(rect2)", + ]) ) private static let legacyFunctions: [String: LegacyFunctionRewriteStrategy] = [ diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyObjcTypeRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyObjcTypeRule.swift index 3bf1c23683..c5f41de63d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyObjcTypeRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyObjcTypeRule.swift @@ -51,26 +51,26 @@ struct LegacyObjcTypeRule: Rule { } """#, configuration: ["allowed_types": ["NSData", "NSNumber", "NSURLRequest"]]), ], - triggeringExamples: [ - Example("var array = ↓NSArray()"), - Example("var calendar: ↓NSCalendar? = nil"), - Example("_ = ↓NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData"), - Example(#"_ = ↓NSNotification.Name("com.apple.Music.playerInfo")"#), - Example(#""" + triggeringExamples: #examples([ + "var array = ↓NSArray()", + "var calendar: ↓NSCalendar? = nil", + "_ = ↓NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData", + #"_ = ↓NSNotification.Name("com.apple.Music.playerInfo")"#, + #""" let keyValuePair: (Int) -> (↓NSString, ↓NSString) = { let n = "\($0)" as ↓NSString; return (n, n) } dictionary = [↓NSString: ↓NSString](uniqueKeysWithValues: (1...10_000).lazy.map(keyValuePair)) - """#), - Example(""" + """#, + """ extension Foundation.Notification.Name { static var reachabilityChanged: Foundation.↓NSNotification.Name { return Foundation.Notification.Name("org.wordpress.reachability.changed") } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyRandomRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyRandomRule.swift index d20cb859f7..e207891b2c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyRandomRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyRandomRule.swift @@ -9,16 +9,16 @@ struct LegacyRandomRule: Rule { name: "Legacy Random", description: "Prefer using `type.random(in:)` over legacy functions", kind: .idiomatic, - nonTriggeringExamples: [ - Example("Int.random(in: 0..<10)"), - Example("Double.random(in: 8.6...111.34)"), - Example("Float.random(in: 0 ..< 1)"), - ], - triggeringExamples: [ - Example("↓arc4random()"), - Example("↓arc4random_uniform(83)"), - Example("↓drand48()"), - ] + nonTriggeringExamples: #examples([ + "Int.random(in: 0..<10)", + "Double.random(in: 8.6...111.34)", + "Float.random(in: 0 ..< 1)", + ]), + triggeringExamples: #examples([ + "↓arc4random()", + "↓arc4random_uniform(83)", + "↓drand48()", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyUIGraphicsFunctionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyUIGraphicsFunctionRule.swift index f4ac5416a4..384904f07a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyUIGraphicsFunctionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/LegacyUIGraphicsFunctionRule.swift @@ -10,51 +10,51 @@ struct LegacyUIGraphicsFunctionRule: Rule { description: "Prefer using `UIGraphicsImageRenderer` over legacy functions", rationale: "The modern replacement is safer, cleaner, Retina-aware and more performant.", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ let renderer = UIGraphicsImageRenderer(size: bounds.size) let screenshot = renderer.image { _ in myUIView.drawHierarchy(in: bounds, afterScreenUpdates: true) } - """), + """, - Example(""" + """ let renderer = UIGraphicsImageRenderer(size: newSize) let combined = renderer.image { _ in background.draw(in: CGRect(origin: .zero, size: newSize)) watermark.draw(in: CGRect(origin: .zero, size: watermarkSize)) } - """), + """, - Example(""" + """ UIGraphicsImageRenderer(size: newSize, format: UIGraphicsImageRendererFormat()).image { _ in image.draw(in: CGRect(origin: .zero, size: newSize)) } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓UIGraphicsBeginImageContext(newSize) myUIView.drawHierarchy(in: bounds, afterScreenUpdates: false) let optionalScreenshot = ↓UIGraphicsGetImageFromCurrentImageContext() ↓UIGraphicsEndImageContext() - """), + """, - Example(""" + """ ↓UIGraphicsBeginImageContext(newSize) background.draw(in: CGRect(origin: .zero, size: newSize)) watermark.draw(in: CGRect(origin: .zero, size: watermarkSize)) let optionalOutput = ↓UIGraphicsGetImageFromCurrentImageContext() ↓UIGraphicsEndImageContext() - """), + """, - Example(""" + """ ↓UIGraphicsBeginImageContextWithOptions(newSize, true, 1.0) image.draw(in: CGRect(origin: .zero, size: newSize)) let optionalOutput = ↓UIGraphicsGetImageFromCurrentImageContext() ↓UIGraphicsEndImageContext() - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NimbleOperatorRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NimbleOperatorRule.swift index c7d1000530..eb6494d13d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NimbleOperatorRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NimbleOperatorRule.swift @@ -11,63 +11,63 @@ struct NimbleOperatorRule: Rule { name: "Nimble Operator", description: "Prefer Nimble operator overloads over free matcher functions", kind: .idiomatic, - nonTriggeringExamples: [ - Example("expect(seagull.squawk) != \"Hi!\""), - Example("expect(\"Hi!\") == \"Hi!\""), - Example("expect(10) > 2"), - Example("expect(10) >= 10"), - Example("expect(10) < 11"), - Example("expect(10) <= 10"), - Example("expect(x) === x"), - Example("expect(10) == 10"), - Example("expect(success) == true"), - Example("expect(value) == nil"), - Example("expect(value) != nil"), - Example("expect(object.asyncFunction()).toEventually(equal(1))"), - Example("expect(actual).to(haveCount(expected))"), - Example(""" + nonTriggeringExamples: #examples([ + "expect(seagull.squawk) != \"Hi!\"", + "expect(\"Hi!\") == \"Hi!\"", + "expect(10) > 2", + "expect(10) >= 10", + "expect(10) < 11", + "expect(10) <= 10", + "expect(x) === x", + "expect(10) == 10", + "expect(success) == true", + "expect(value) == nil", + "expect(value) != nil", + "expect(object.asyncFunction()).toEventually(equal(1))", + "expect(actual).to(haveCount(expected))", + """ foo.method { expect(value).to(equal(expectedValue), description: "Failed") return Bar(value: ()) } - """), - ], - triggeringExamples: [ - Example("↓expect(seagull.squawk).toNot(equal(\"Hi\"))"), - Example("↓expect(12).toNot(equal(10))"), - Example("↓expect(10).to(equal(10))"), - Example("↓expect(10, line: 1).to(equal(10))"), - Example("↓expect(10).to(beGreaterThan(8))"), - Example("↓expect(10).to(beGreaterThanOrEqualTo(10))"), - Example("↓expect(10).to(beLessThan(11))"), - Example("↓expect(10).to(beLessThanOrEqualTo(10))"), - Example("↓expect(x).to(beIdenticalTo(x))"), - Example("↓expect(success).to(beTrue())"), - Example("↓expect(success).to(beFalse())"), - Example("↓expect(value).to(beNil())"), - Example("↓expect(value).toNot(beNil())"), - Example("expect(10) > 2\n ↓expect(10).to(beGreaterThan(2))"), - ], - corrections: [ - Example("↓expect(seagull.squawk).toNot(equal(\"Hi\"))"): Example("expect(seagull.squawk) != \"Hi\""), - Example("↓expect(\"Hi!\").to(equal(\"Hi!\"))"): Example("expect(\"Hi!\") == \"Hi!\""), - Example("↓expect(12).toNot(equal(10))"): Example("expect(12) != 10"), - Example("↓expect(value1).to(equal(value2))"): Example("expect(value1) == value2"), - Example("↓expect( value1 ).to(equal( value2.foo))"): Example("expect( value1 ) == value2.foo"), - Example("↓expect(value1).to(equal(10))"): Example("expect(value1) == 10"), - Example("↓expect(10).to(beGreaterThan(8))"): Example("expect(10) > 8"), - Example("↓expect(10).to(beGreaterThanOrEqualTo(10))"): Example("expect(10) >= 10"), - Example("↓expect(10).to(beLessThan(11))"): Example("expect(10) < 11"), - Example("↓expect(10).to(beLessThanOrEqualTo(10))"): Example("expect(10) <= 10"), - Example("↓expect(x).to(beIdenticalTo(x))"): Example("expect(x) === x"), - Example("↓expect(success).to(beTrue())"): Example("expect(success) == true"), - Example("↓expect(success).to(beFalse())"): Example("expect(success) == false"), - Example("↓expect(success).toNot(beFalse())"): Example("expect(success) != false"), - Example("↓expect(success).toNot(beTrue())"): Example("expect(success) != true"), - Example("↓expect(value).to(beNil())"): Example("expect(value) == nil"), - Example("↓expect(value).toNot(beNil())"): Example("expect(value) != nil"), - Example("expect(10) > 2\n ↓expect(10).to(beGreaterThan(2))"): Example("expect(10) > 2\n expect(10) > 2"), - ] + """, + ]), + triggeringExamples: #examples([ + "↓expect(seagull.squawk).toNot(equal(\"Hi\"))", + "↓expect(12).toNot(equal(10))", + "↓expect(10).to(equal(10))", + "↓expect(10, line: 1).to(equal(10))", + "↓expect(10).to(beGreaterThan(8))", + "↓expect(10).to(beGreaterThanOrEqualTo(10))", + "↓expect(10).to(beLessThan(11))", + "↓expect(10).to(beLessThanOrEqualTo(10))", + "↓expect(x).to(beIdenticalTo(x))", + "↓expect(success).to(beTrue())", + "↓expect(success).to(beFalse())", + "↓expect(value).to(beNil())", + "↓expect(value).toNot(beNil())", + "expect(10) > 2\n ↓expect(10).to(beGreaterThan(2))", + ]), + corrections: #examplesDictionary([ + "↓expect(seagull.squawk).toNot(equal(\"Hi\"))": "expect(seagull.squawk) != \"Hi\"", + "↓expect(\"Hi!\").to(equal(\"Hi!\"))": "expect(\"Hi!\") == \"Hi!\"", + "↓expect(12).toNot(equal(10))": "expect(12) != 10", + "↓expect(value1).to(equal(value2))": "expect(value1) == value2", + "↓expect( value1 ).to(equal( value2.foo))": "expect( value1 ) == value2.foo", + "↓expect(value1).to(equal(10))": "expect(value1) == 10", + "↓expect(10).to(beGreaterThan(8))": "expect(10) > 8", + "↓expect(10).to(beGreaterThanOrEqualTo(10))": "expect(10) >= 10", + "↓expect(10).to(beLessThan(11))": "expect(10) < 11", + "↓expect(10).to(beLessThanOrEqualTo(10))": "expect(10) <= 10", + "↓expect(x).to(beIdenticalTo(x))": "expect(x) === x", + "↓expect(success).to(beTrue())": "expect(success) == true", + "↓expect(success).to(beFalse())": "expect(success) == false", + "↓expect(success).toNot(beFalse())": "expect(success) != false", + "↓expect(success).toNot(beTrue())": "expect(success) != true", + "↓expect(value).to(beNil())": "expect(value) == nil", + "↓expect(value).toNot(beNil())": "expect(value) != nil", + "expect(10) > 2\n ↓expect(10).to(beGreaterThan(2))": "expect(10) > 2\n expect(10) > 2", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoEmptyBlockRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoEmptyBlockRule.swift index e31b097c96..3a7c5b0090 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoEmptyBlockRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoEmptyBlockRule.swift @@ -105,24 +105,24 @@ struct NoEmptyBlockRule: Rule { {}() """, configuration: ["disabled_block_types": ["closure_blocks"]]), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ func f() ↓{} var flag = true { willSet ↓{} } - """), + """, - Example(""" + """ class Apple { init() ↓{} deinit ↓{} } - """), + """, - Example(""" + """ for _ in 0..<10 ↓{} do ↓{ @@ -141,14 +141,14 @@ struct NoEmptyBlockRule: Rule { repeat ↓{} while (flag) while i < 10 ↓{} - """), - Example(""" + """, + """ f ↓{} - """), - Example(""" + """, + """ Button ↓{} label: ↓{} - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoExtensionAccessModifierRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoExtensionAccessModifierRule.swift index ed2d3b4601..9185b06a48 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoExtensionAccessModifierRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoExtensionAccessModifierRule.swift @@ -9,18 +9,18 @@ struct NoExtensionAccessModifierRule: Rule { name: "No Extension Access Modifier", description: "Prefer not to use extension access modifiers", kind: .idiomatic, - nonTriggeringExamples: [ - Example("extension String {}"), - Example("\n\n extension String {}"), - Example("nonisolated extension String {}"), - ], - triggeringExamples: [ - Example("↓private extension String {}"), - Example("↓public \n extension String {}"), - Example("↓open extension String {}"), - Example("↓internal extension String {}"), - Example("↓fileprivate extension String {}"), - ] + nonTriggeringExamples: #examples([ + "extension String {}", + "\n\n extension String {}", + "nonisolated extension String {}", + ]), + triggeringExamples: #examples([ + "↓private extension String {}", + "↓public \n extension String {}", + "↓open extension String {}", + "↓internal extension String {}", + "↓fileprivate extension String {}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoFallthroughOnlyRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoFallthroughOnlyRuleExamples.swift index 81b1b0637e..47cafdc2dc 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoFallthroughOnlyRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoFallthroughOnlyRuleExamples.swift @@ -1,6 +1,6 @@ internal struct NoFallthroughOnlyRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example(""" + static let nonTriggeringExamples: [Example] = #examples([ + """ switch myvar { case 1: var a = 1 @@ -8,8 +8,8 @@ internal struct NoFallthroughOnlyRuleExamples { case 2: var a = 2 } - """), - Example(""" + """, + """ switch myvar { case "a": var one = 1 @@ -18,8 +18,8 @@ internal struct NoFallthroughOnlyRuleExamples { case "b": /* comment */ var three = 3 } - """), - Example(""" + """, + """ switch myvar { case 1: let one = 1 @@ -27,8 +27,8 @@ internal struct NoFallthroughOnlyRuleExamples { // comment var two = 2 } - """), - Example(""" + """, + """ switch myvar { case MyFunc(x: [1, 2, YourFunc(a: 23)], y: 2): var three = 3 @@ -36,8 +36,8 @@ internal struct NoFallthroughOnlyRuleExamples { default: var three = 4 } - """), - Example(""" + """, + """ switch myvar { case .alpha: var one = 1 @@ -47,8 +47,8 @@ internal struct NoFallthroughOnlyRuleExamples { default: var four = 4 } - """), - Example(""" + """, + """ let aPoint = (1, -1) switch aPoint { case let (x, y) where x == y: @@ -59,8 +59,8 @@ internal struct NoFallthroughOnlyRuleExamples { default: let C = "C" } - """), - Example(""" + """, + """ switch myvar { case MyFun(with: { $1 }): let one = 1 @@ -68,8 +68,8 @@ internal struct NoFallthroughOnlyRuleExamples { case "abc": let two = 2 } - """), - Example(""" + """, + """ switch enumInstance { case .caseA: print("it's a") @@ -78,19 +78,19 @@ internal struct NoFallthroughOnlyRuleExamples { @unknown default: print("it's not a") } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ switch myvar { case 1: ↓fallthrough case 2: var a = 1 } - """), - Example(""" + """, + """ switch myvar { case 1: var a = 2 @@ -99,14 +99,14 @@ internal struct NoFallthroughOnlyRuleExamples { case 3: var a = 3 } - """), - Example(""" + """, + """ switch myvar { case 1: // comment ↓fallthrough } - """), - Example(""" + """, + """ switch myvar { case 1: /* multi line @@ -115,16 +115,16 @@ internal struct NoFallthroughOnlyRuleExamples { case 2: var a = 2 } - """), - Example(""" + """, + """ switch myvar { case MyFunc(x: [1, 2, YourFunc(a: 23)], y: 2): ↓fallthrough default: var three = 4 } - """), - Example(""" + """, + """ switch myvar { case .alpha: var one = 1 @@ -135,8 +135,8 @@ internal struct NoFallthroughOnlyRuleExamples { default: var four = 4 } - """), - Example(""" + """, + """ let aPoint = (1, -1) switch aPoint { case let (x, y) where x == y: @@ -146,14 +146,14 @@ internal struct NoFallthroughOnlyRuleExamples { default: let B = "B" } - """), - Example(""" + """, + """ switch myvar { case MyFun(with: { $1 }): ↓fallthrough case "abc": let two = 2 } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoGroupingExtensionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoGroupingExtensionRule.swift index 842611fae3..afa4ee1d63 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoGroupingExtensionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/NoGroupingExtensionRule.swift @@ -9,17 +9,17 @@ struct NoGroupingExtensionRule: Rule { name: "No Grouping Extension", description: "Extensions shouldn't be used to group code within the same source file", kind: .idiomatic, - nonTriggeringExamples: [ - Example("protocol Food {}\nextension Food {}"), - Example("class Apples {}\nextension Oranges {}"), - Example("class Box {}\nextension Box where T: Vegetable {}"), - ], - triggeringExamples: [ - Example("enum Fruit {}\n↓extension Fruit {}"), - Example("↓extension Tea: Error {}\nstruct Tea {}"), - Example("class Ham { class Spam {}}\n↓extension Ham.Spam {}"), - Example("extension External { struct Gotcha {}}\n↓extension External.Gotcha {}"), - ] + nonTriggeringExamples: #examples([ + "protocol Food {}\nextension Food {}", + "class Apples {}\nextension Oranges {}", + "class Box {}\nextension Box where T: Vegetable {}", + ]), + triggeringExamples: #examples([ + "enum Fruit {}\n↓extension Fruit {}", + "↓extension Tea: Error {}\nstruct Tea {}", + "class Ham { class Spam {}}\n↓extension Ham.Spam {}", + "extension External { struct Gotcha {}}\n↓extension External.Gotcha {}", + ]) ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ObjectLiteralRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ObjectLiteralRule.swift index 45e9969df9..f2f1b3fbfc 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ObjectLiteralRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ObjectLiteralRule.swift @@ -9,25 +9,24 @@ struct ObjectLiteralRule: Rule { name: "Object Literal", description: "Prefer object literals over image and color inits", kind: .idiomatic, - nonTriggeringExamples: [ - Example("let image = #imageLiteral(resourceName: \"image.jpg\")"), - Example("let color = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)"), - Example("let image = UIImage(named: aVariable)"), - Example("let image = UIImage(named: \"interpolated \\(variable)\")"), - Example("let color = UIColor(red: value, green: value, blue: value, alpha: 1)"), - Example("let image = NSImage(named: aVariable)"), - Example("let image = NSImage(named: \"interpolated \\(variable)\")"), - Example("let color = NSColor(red: value, green: value, blue: value, alpha: 1)"), - ], + nonTriggeringExamples: #examples([ + "let image = #imageLiteral(resourceName: \"image.jpg\")", + "let color = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)", + "let image = UIImage(named: aVariable)", + "let image = UIImage(named: \"interpolated \\(variable)\")", + "let color = UIColor(red: value, green: value, blue: value, alpha: 1)", + "let image = NSImage(named: aVariable)", + "let image = NSImage(named: \"interpolated \\(variable)\")", + "let color = NSColor(red: value, green: value, blue: value, alpha: 1)", + ]), triggeringExamples: ["", ".init"].flatMap { (method: String) -> [Example] in ["UI", "NS"].flatMap { (prefix: String) -> [Example] in - [ - Example("let image = ↓\(prefix)Image\(method)(named: \"foo\")"), - Example("let color = ↓\(prefix)Color\(method)(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)"), - // swiftlint:disable:next line_length - Example("let color = ↓\(prefix)Color\(method)(red: 100 / 255.0, green: 50 / 255.0, blue: 0, alpha: 1)"), - Example("let color = ↓\(prefix)Color\(method)(white: 0.5, alpha: 1)"), - ] + #examples([ + "let image = ↓\(prefix)Image\(method)(named: \"foo\")", + "let color = ↓\(prefix)Color\(method)(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)", + "let color = ↓\(prefix)Color\(method)(red: 100 / 255.0, green: 50 / 255.0, blue: 0, alpha: 1)", + "let color = ↓\(prefix)Color\(method)(white: 0.5, alpha: 1)", + ]) } } ) diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/OneDeclarationPerFileRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/OneDeclarationPerFileRule.swift index 784a4e3456..9e24be82cb 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/OneDeclarationPerFileRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/OneDeclarationPerFileRule.swift @@ -9,34 +9,34 @@ struct OneDeclarationPerFileRule: Rule { name: "One Declaration per File", description: "Only a single declaration is allowed in a file", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ actor Foo {} - """), - Example(""" + """, + """ class Foo {} extension Foo {} - """), - Example(""" + """, + """ struct S { struct N {} } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ class Foo {} ↓class Bar {} - """), - Example(""" + """, + """ protocol Foo {} ↓enum Bar {} - """), - Example(""" + """, + """ struct Foo {} ↓struct Bar {} - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PatternMatchingKeywordsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PatternMatchingKeywordsRule.swift index e2f6818701..5a288940f3 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PatternMatchingKeywordsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PatternMatchingKeywordsRule.swift @@ -21,72 +21,72 @@ struct PatternMatchingKeywordsRule: Rule { in enum cases to reduce visual noise. """, kind: .idiomatic, - nonTriggeringExamples: [ - Example("default"), - Example("case 1"), - Example("case bar"), - Example("case let (x, y)"), - Example("case .foo(let x)"), - Example("case let .foo(x, y)"), - Example("case .foo(let x), .bar(let x)"), - Example("case .foo(let x, var y)"), - Example("case var (x, y)"), - Example("case .foo(var x)"), - Example("case var .foo(x, y)"), - Example("case (y, let x, z)"), - Example("case (foo, let x)"), - Example("case (foo, let x, let y)"), - Example("case .foo(bar, let x)"), - Example("case (let x, y)"), - Example("case .foo(let x, y)"), - Example("case (.foo(let x), y)"), - Example("case let .foo(x, y), let .bar(x, y)"), - Example("case var .foo(x, y), var .bar(x, y)"), - Example("case let .foo(x, y), let .bar(x, y), let .baz(x, y)"), - Example("case .foo(bar: let x, baz: var y)"), - Example("case (.yamlParsing(var x), (.yamlParsing(var y), z))"), - Example("case (.foo(let x), (y, let z))"), - ].map(wrapInSwitch) + [ - Example("if case let (x, y) = foo {}"), - Example("guard case let (x, y) = foo else { return }"), - Example("while case let (x, y) = foo {}"), - Example("for case let (x, y) in foos {}"), - Example("if case (foo, let x) = value {}"), - Example("guard case .foo(bar, let x) = value else { return }"), - Example("do {} catch let Pattern.error(x, y) {}"), - Example("do {} catch (foo, let x) {}"), - ], - triggeringExamples: [ - Example("case (↓let x, ↓let y)"), - Example("case (↓let x, ↓let y, .foo)"), - Example("case (↓let x, ↓let y, _)"), - Example("case (↓let x, ↓let y, 1)"), - Example("case (↓let x, ↓let y, f())"), - Example("case (↓let x, ↓let y, s.f())"), - Example("case (↓let x, ↓let y, s.t)"), - Example("case .foo(↓let x, ↓let y)"), - Example("case .foo(bar: ↓let x, baz: ↓let y)"), - Example("case .foo(↓var x, ↓var y)"), - Example("case .foo(bar: ↓var x, baz: ↓var y)"), - Example("case (.yamlParsing(↓let x), .yamlParsing(↓let y))"), - Example("case (.yamlParsing(↓var x), (.yamlParsing(↓var y), _))"), - Example("case ((↓let x, ↓let y), z)"), - Example("case .foo((↓let x, ↓let y), z)"), - Example("case (.foo(↓let x, ↓let y), z)"), - Example("case .foo(.bar(↓let x), .bar(↓let y))"), - Example("case .foo(.bar(↓let x), .bar(↓let y), .baz)"), - Example("case .foo(↓let x, ↓let y), .bar(↓let x, ↓let y)"), - Example("case .foo(↓var x, ↓var y), .bar(↓var x, ↓var y)"), - ].map(wrapInSwitch) + [ - Example("if case (↓let x, ↓let y) = foo {}"), - Example("guard case (↓let x, ↓let y) = foo else { return }"), - Example("while case (↓let x, ↓let y) = foo {}"), - Example("for case (↓let x, ↓let y) in foos {}"), - Example("if case .foo(bar: ↓let x, baz: ↓let y) = value {}"), - Example("do {} catch Pattern.error(↓let x, ↓let y) {}"), - Example("do {} catch (↓let x, ↓let y) {}"), - Example("do {} catch Foo.outer(.inner(↓let x), .inner(↓let y)) {}"), - ] + nonTriggeringExamples: #examples([ + "default", + "case 1", + "case bar", + "case let (x, y)", + "case .foo(let x)", + "case let .foo(x, y)", + "case .foo(let x), .bar(let x)", + "case .foo(let x, var y)", + "case var (x, y)", + "case .foo(var x)", + "case var .foo(x, y)", + "case (y, let x, z)", + "case (foo, let x)", + "case (foo, let x, let y)", + "case .foo(bar, let x)", + "case (let x, y)", + "case .foo(let x, y)", + "case (.foo(let x), y)", + "case let .foo(x, y), let .bar(x, y)", + "case var .foo(x, y), var .bar(x, y)", + "case let .foo(x, y), let .bar(x, y), let .baz(x, y)", + "case .foo(bar: let x, baz: var y)", + "case (.yamlParsing(var x), (.yamlParsing(var y), z))", + "case (.foo(let x), (y, let z))", + ]).map(wrapInSwitch) + #examples([ + "if case let (x, y) = foo {}", + "guard case let (x, y) = foo else { return }", + "while case let (x, y) = foo {}", + "for case let (x, y) in foos {}", + "if case (foo, let x) = value {}", + "guard case .foo(bar, let x) = value else { return }", + "do {} catch let Pattern.error(x, y) {}", + "do {} catch (foo, let x) {}", + ]), + triggeringExamples: #examples([ + "case (↓let x, ↓let y)", + "case (↓let x, ↓let y, .foo)", + "case (↓let x, ↓let y, _)", + "case (↓let x, ↓let y, 1)", + "case (↓let x, ↓let y, f())", + "case (↓let x, ↓let y, s.f())", + "case (↓let x, ↓let y, s.t)", + "case .foo(↓let x, ↓let y)", + "case .foo(bar: ↓let x, baz: ↓let y)", + "case .foo(↓var x, ↓var y)", + "case .foo(bar: ↓var x, baz: ↓var y)", + "case (.yamlParsing(↓let x), .yamlParsing(↓let y))", + "case (.yamlParsing(↓var x), (.yamlParsing(↓var y), _))", + "case ((↓let x, ↓let y), z)", + "case .foo((↓let x, ↓let y), z)", + "case (.foo(↓let x, ↓let y), z)", + "case .foo(.bar(↓let x), .bar(↓let y))", + "case .foo(.bar(↓let x), .bar(↓let y), .baz)", + "case .foo(↓let x, ↓let y), .bar(↓let x, ↓let y)", + "case .foo(↓var x, ↓var y), .bar(↓var x, ↓var y)", + ]).map(wrapInSwitch) + #examples([ + "if case (↓let x, ↓let y) = foo {}", + "guard case (↓let x, ↓let y) = foo else { return }", + "while case (↓let x, ↓let y) = foo {}", + "for case (↓let x, ↓let y) in foos {}", + "if case .foo(bar: ↓let x, baz: ↓let y) = value {}", + "do {} catch Pattern.error(↓let x, ↓let y) {}", + "do {} catch (↓let x, ↓let y) {}", + "do {} catch Foo.outer(.inner(↓let x), .inner(↓let y)) {}", + ]) ) private static func wrapInSwitch(_ example: Example) -> Example { diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferAssetSymbolsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferAssetSymbolsRule.swift index f8ef1fe56d..c215ff7752 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferAssetSymbolsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferAssetSymbolsRule.swift @@ -16,35 +16,35 @@ struct PreferAssetSymbolsRule: Rule { """, kind: .idiomatic, minSwiftVersion: .fiveDotNine, - nonTriggeringExamples: [ + nonTriggeringExamples: #examples([ // UIKit - using asset symbols - Example("UIImage(resource: .someImage)"), - Example("UIImage(systemName: \"trash\")"), + "UIImage(resource: .someImage)", + "UIImage(systemName: \"trash\")", // SwiftUI - using asset symbols - Example("Image(.someImage)"), - Example("Image(systemName: \"trash\")"), + "Image(.someImage)", + "Image(systemName: \"trash\")", // Dynamic strings (variables or interpolated) - Example("UIImage(named: imageName)"), - Example("UIImage(named: \"image_\\(suffix)\")"), - Example("Image(imageName)"), - Example("Image(\"image_\\(suffix)\")"), - ], - triggeringExamples: [ + "UIImage(named: imageName)", + "UIImage(named: \"image_\\(suffix)\")", + "Image(imageName)", + "Image(\"image_\\(suffix)\")", + ]), + triggeringExamples: #examples([ // UIKit examples - Example("↓UIImage(named: \"some_image\")"), - Example("↓UIImage(named: \"some image\")"), - Example("↓UIImage.init(named: \"someImage\")"), + "↓UIImage(named: \"some_image\")", + "↓UIImage(named: \"some image\")", + "↓UIImage.init(named: \"someImage\")", // UIKit with bundle parameters - Example("↓UIImage(named: \"someImage\", in: Bundle.main, compatibleWith: nil)"), - Example("↓UIImage(named: \"someImage\", in: .main)"), + "↓UIImage(named: \"someImage\", in: Bundle.main, compatibleWith: nil)", + "↓UIImage(named: \"someImage\", in: .main)", // SwiftUI examples - Example("↓Image(\"some_image\")"), - Example("↓Image(\"some image\")"), - Example("↓Image.init(\"someImage\")"), + "↓Image(\"some_image\")", + "↓Image(\"some image\")", + "↓Image.init(\"someImage\")", // SwiftUI with bundle parameters - Example("↓Image(\"someImage\", bundle: Bundle.main)"), - Example("↓Image(\"someImage\", bundle: .main)"), - ] + "↓Image(\"someImage\", bundle: Bundle.main)", + "↓Image(\"someImage\", bundle: .main)", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferConditionListRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferConditionListRule.swift index 959e76b34b..0acd701f1c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferConditionListRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferConditionListRule.swift @@ -32,61 +32,61 @@ struct PreferConditionListRule: Rule { condition list elements. The scope of the parentheses is limited to the function call itself. """, kind: .idiomatic, - nonTriggeringExamples: [ - Example("if a, b {}"), - Example("guard a || b && c {}"), - Example("if a && b || c {}"), - Example("let result = a && b"), - Example("repeat {} while a && b"), - Example("if (f {}) {}"), - Example("if f {} {}"), - ], - triggeringExamples: [ - Example("if a ↓&& b {}"), - Example("if a ↓&& b ↓&& c {}"), - Example("while a ↓&& b {}"), - Example("guard a ↓&& b {}"), - Example("guard (a || b) ↓&& c {}"), - Example("if a ↓&& (b && c) {}"), - Example("guard a ↓&& b ↓&& c else {}"), - Example("if (a ↓&& b) {}"), - Example("if (a ↓&& f {}) {}"), - ], - corrections: [ - Example("if a && b {}"): - Example("if a, b {}"), - Example(""" + nonTriggeringExamples: #examples([ + "if a, b {}", + "guard a || b && c {}", + "if a && b || c {}", + "let result = a && b", + "repeat {} while a && b", + "if (f {}) {}", + "if f {} {}", + ]), + triggeringExamples: #examples([ + "if a ↓&& b {}", + "if a ↓&& b ↓&& c {}", + "while a ↓&& b {}", + "guard a ↓&& b {}", + "guard (a || b) ↓&& c {}", + "if a ↓&& (b && c) {}", + "guard a ↓&& b ↓&& c else {}", + "if (a ↓&& b) {}", + "if (a ↓&& f {}) {}", + ]), + corrections: #examplesDictionary([ + "if a && b {}": + "if a, b {}", + """ if a && b {} - """): Example(""" + """: """ if a, b {} - """), - Example("guard a && b && c else {}"): - Example("guard a, b, c else {}"), - Example("while a && b {}"): - Example("while a, b {}"), - Example("if a && b || c {}"): - Example("if a && b || c {}"), - Example("if (a && b) {}"): - Example("if a, b {}"), - Example("if a && (b && c) {}"): - Example("if a, b, c {}"), - Example("if (a && b) && c {}"): - Example("if a, b, c {}"), - Example("if (a && b), c {}"): - Example("if a, b, c {}"), - Example("guard (a || b) ↓&& c {}"): - Example("guard a || b, c {}"), - Example("if a && (b || c) {}"): - Example("if a, b || c {}"), - Example("if (a ↓&& f {}) {}"): - Example("if a, (f {}) {}"), - Example("if a ↓&& (b || f {}) {}"): - Example("if a, b || (f {}) {}"), - Example("if a ↓&& !f {} {}"): - Example("if a, !(f {}) {}"), - ] + """, + "guard a && b && c else {}": + "guard a, b, c else {}", + "while a && b {}": + "while a, b {}", + "if a && b || c {}": + "if a && b || c {}", + "if (a && b) {}": + "if a, b {}", + "if a && (b && c) {}": + "if a, b, c {}", + "if (a && b) && c {}": + "if a, b, c {}", + "if (a && b), c {}": + "if a, b, c {}", + "guard (a || b) ↓&& c {}": + "guard a || b, c {}", + "if a && (b || c) {}": + "if a, b || c {}", + "if (a ↓&& f {}) {}": + "if a, (f {}) {}", + "if a ↓&& (b || f {}) {}": + "if a, b || (f {}) {}", + "if a ↓&& !f {} {}": + "if a, !(f {}) {}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferNimbleRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferNimbleRule.swift index 25c09d9cb1..2373d68bd9 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferNimbleRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferNimbleRule.swift @@ -9,18 +9,18 @@ struct PreferNimbleRule: Rule { name: "Prefer Nimble", description: "Prefer Nimble matchers over XCTAssert functions", kind: .idiomatic, - nonTriggeringExamples: [ - Example("expect(foo) == 1"), - Example("expect(foo).to(equal(1))"), - ], - triggeringExamples: [ - Example("↓XCTAssertTrue(foo)"), - Example("↓XCTAssertEqual(foo, 2)"), - Example("↓XCTAssertNotEqual(foo, 2)"), - Example("↓XCTAssertNil(foo)"), - Example("↓XCTAssert(foo)"), - Example("↓XCTAssertGreaterThan(foo, 10)"), - ] + nonTriggeringExamples: #examples([ + "expect(foo) == 1", + "expect(foo).to(equal(1))", + ]), + triggeringExamples: #examples([ + "↓XCTAssertTrue(foo)", + "↓XCTAssertEqual(foo, 2)", + "↓XCTAssertNotEqual(foo, 2)", + "↓XCTAssertNil(foo)", + "↓XCTAssert(foo)", + "↓XCTAssertGreaterThan(foo, 10)", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferTypeCheckingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferTypeCheckingRule.swift index 4dd0432a00..21cde8e772 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferTypeCheckingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferTypeCheckingRule.swift @@ -10,50 +10,50 @@ struct PreferTypeCheckingRule: Rule { name: "Prefer Type Checking", description: "Prefer `a is X` to `a as? X != nil`", kind: .idiomatic, - nonTriggeringExamples: [ - Example("let foo = bar as? Foo"), - Example("bar is Foo"), - Example("2*x is X"), - Example(""" + nonTriggeringExamples: #examples([ + "let foo = bar as? Foo", + "bar is Foo", + "2*x is X", + """ if foo is Bar { doSomeThing() } - """), - Example(""" + """, + """ if let bar = foo as? Bar { foo.run() } - """), - Example("bar as Foo != nil"), - Example("nil != bar as Foo"), - Example("bar as Foo? != nil"), - Example("bar as? Foo? != nil"), - ], - triggeringExamples: [ - Example("bar ↓as? Foo != nil"), - Example("2*x as? X != nil"), - Example(""" + """, + "bar as Foo != nil", + "nil != bar as Foo", + "bar as Foo? != nil", + "bar as? Foo? != nil", + ]), + triggeringExamples: #examples([ + "bar ↓as? Foo != nil", + "2*x as? X != nil", + """ if foo ↓as? Bar != nil { doSomeThing() } - """), - Example("nil != bar ↓as? Foo"), - Example("nil != 2*x ↓as? X"), - ], - corrections: [ - Example("bar ↓as? Foo != nil"): Example("bar is Foo"), - Example("nil != bar ↓as? Foo"): Example("bar is Foo"), - Example("2*x ↓as? X != nil"): Example("2*x is X"), - Example(""" + """, + "nil != bar ↓as? Foo", + "nil != 2*x ↓as? X", + ]), + corrections: #examplesDictionary([ + "bar ↓as? Foo != nil": "bar is Foo", + "nil != bar ↓as? Foo": "bar is Foo", + "2*x ↓as? X != nil": "2*x is X", + """ if foo ↓as? Bar != nil { doSomeThing() } - """): Example(""" + """: """ if foo is Bar { doSomeThing() } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferZeroOverExplicitInitRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferZeroOverExplicitInitRule.swift index 83965f6f0e..0ef6a6a8c1 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferZeroOverExplicitInitRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PreferZeroOverExplicitInitRule.swift @@ -10,30 +10,30 @@ struct PreferZeroOverExplicitInitRule: Rule { name: "Prefer Zero Over Explicit Init", description: "Prefer `.zero` over explicit init with zero parameters (e.g. `CGPoint(x: 0, y: 0)`)", kind: .idiomatic, - nonTriggeringExamples: [ - Example("CGRect(x: 0, y: 0, width: 0, height: 1)"), - Example("CGPoint(x: 0, y: -1)"), - Example("CGSize(width: 2, height: 4)"), - Example("CGVector(dx: -5, dy: 0)"), - Example("UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)"), - ], - triggeringExamples: [ - Example("↓CGPoint(x: 0, y: 0)"), - Example("↓CGPoint(x: 0.000000, y: 0)"), - Example("↓CGPoint(x: 0.000000, y: 0.000)"), - Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"), - Example("↓CGSize(width: 0, height: 0)"), - Example("↓CGVector(dx: 0, dy: 0)"), - Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)"), - ], - corrections: [ - Example("↓CGPoint(x: 0, y: 0)"): Example("CGPoint.zero"), - Example("(↓CGPoint(x: 0, y: 0))"): Example("(CGPoint.zero)"), - Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"): Example("CGRect.zero"), - Example("↓CGSize(width: 0, height: 0.000)"): Example("CGSize.zero"), - Example("↓CGVector(dx: 0, dy: 0)"): Example("CGVector.zero"), - Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)"): Example("UIEdgeInsets.zero"), - ] + nonTriggeringExamples: #examples([ + "CGRect(x: 0, y: 0, width: 0, height: 1)", + "CGPoint(x: 0, y: -1)", + "CGSize(width: 2, height: 4)", + "CGVector(dx: -5, dy: 0)", + "UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)", + ]), + triggeringExamples: #examples([ + "↓CGPoint(x: 0, y: 0)", + "↓CGPoint(x: 0.000000, y: 0)", + "↓CGPoint(x: 0.000000, y: 0.000)", + "↓CGRect(x: 0, y: 0, width: 0, height: 0)", + "↓CGSize(width: 0, height: 0)", + "↓CGVector(dx: 0, dy: 0)", + "↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)", + ]), + corrections: #examplesDictionary([ + "↓CGPoint(x: 0, y: 0)": "CGPoint.zero", + "(↓CGPoint(x: 0, y: 0))": "(CGPoint.zero)", + "↓CGRect(x: 0, y: 0, width: 0, height: 0)": "CGRect.zero", + "↓CGSize(width: 0, height: 0.000)": "CGSize.zero", + "↓CGVector(dx: 0, dy: 0)": "CGVector.zero", + "↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)": "UIEdgeInsets.zero", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PrivateOverFilePrivateRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PrivateOverFilePrivateRule.swift index 28cb4e9ec8..0603c83c29 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PrivateOverFilePrivateRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/PrivateOverFilePrivateRule.swift @@ -9,68 +9,68 @@ struct PrivateOverFilePrivateRule: Rule { name: "Private over Fileprivate", description: "Prefer `private` over `fileprivate` declarations", kind: .idiomatic, - nonTriggeringExamples: [ - Example("extension String {}"), - Example("private extension String {}"), - Example("public protocol P {}"), - Example("open extension \n String {}"), - Example("internal extension String {}"), - Example("package typealias P = Int"), - Example(""" + nonTriggeringExamples: #examples([ + "extension String {}", + "private extension String {}", + "public protocol P {}", + "open extension \n String {}", + "internal extension String {}", + "package typealias P = Int", + """ extension String { fileprivate func Something(){} } - """), - Example(""" + """, + """ class MyClass { fileprivate let myInt = 4 } - """), - Example(""" + """, + """ actor MyActor { fileprivate let myInt = 4 } - """), - Example(""" + """, + """ class MyClass { fileprivate(set) var myInt = 4 } - """), - Example(""" + """, + """ struct Outer { struct Inter { fileprivate struct Inner {} } } - """), - ], - triggeringExamples: [ - Example("↓fileprivate enum MyEnum {}"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "↓fileprivate enum MyEnum {}", + """ ↓fileprivate class MyClass { fileprivate(set) var myInt = 4 } - """), - Example(""" + """, + """ ↓fileprivate actor MyActor { fileprivate let myInt = 4 } - """), - Example(""" + """, + """ ↓fileprivate func f() {} ↓fileprivate var x = 0 - """), - ], - corrections: [ - Example("↓fileprivate enum MyEnum {}"): - Example("private enum MyEnum {}"), - Example("↓fileprivate enum MyEnum { fileprivate class A {} }"): - Example("private enum MyEnum { fileprivate class A {} }"), - Example("↓fileprivate class MyClass { fileprivate(set) var myInt = 4 }"): - Example("private class MyClass { fileprivate(set) var myInt = 4 }"), - Example("↓fileprivate actor MyActor { fileprivate(set) var myInt = 4 }"): - Example("private actor MyActor { fileprivate(set) var myInt = 4 }"), - ] + """, + ]), + corrections: #examplesDictionary([ + "↓fileprivate enum MyEnum {}": + "private enum MyEnum {}", + "↓fileprivate enum MyEnum { fileprivate class A {} }": + "private enum MyEnum { fileprivate class A {} }", + "↓fileprivate class MyClass { fileprivate(set) var myInt = 4 }": + "private class MyClass { fileprivate(set) var myInt = 4 }", + "↓fileprivate actor MyActor { fileprivate(set) var myInt = 4 }": + "private actor MyActor { fileprivate(set) var myInt = 4 }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantFinalRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantFinalRule.swift index 22d719b19c..3259f22668 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantFinalRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantFinalRule.swift @@ -15,14 +15,14 @@ struct RedundantFinalRule: Rule { Additionally, `final` is redundant on members of a `final class` since they cannot be overridden. """, kind: .idiomatic, - nonTriggeringExamples: [ - Example("actor MyActor {}"), - Example("final class MyClass {}"), - Example(""" + nonTriggeringExamples: #examples([ + "actor MyActor {}", + "final class MyClass {}", + """ @globalActor actor MyGlobalActor {} - """), - Example(""" + """, + """ actor MyActor { func doWork() {} final class C1 {} @@ -30,31 +30,31 @@ struct RedundantFinalRule: Rule { final func doWork() {} } } - """), - Example(""" + """, + """ class MyClass { final func doWork() {} } - """), - ], - triggeringExamples: [ - Example("↓final actor MyActor {}"), - Example("public ↓final actor DataStore {}"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "↓final actor MyActor {}", + "public ↓final actor DataStore {}", + """ @globalActor ↓final actor MyGlobalActor {} - """), - Example(""" + """, + """ actor MyActor { ↓final func doWork() {} } - """), - Example(""" + """, + """ actor MyActor { ↓final var value: Int { 0 } } - """), - Example(""" + """, + """ final class C1 { ↓final actor A1 { ↓final func doWork() {} @@ -64,16 +64,16 @@ struct RedundantFinalRule: Rule { ↓final func doWork() {} } } - """), - ], - corrections: [ - Example("final actor MyActor {}"): - Example("actor MyActor {}"), - Example("public final actor DataStore {}"): - Example("public actor DataStore {}"), - Example("actor MyActor { final func doWork() {}}"): - Example("actor MyActor { func doWork() {}}"), - ] + """, + ]), + corrections: #examplesDictionary([ + "final actor MyActor {}": + "actor MyActor {}", + "public final actor DataStore {}": + "public actor DataStore {}", + "actor MyActor { final func doWork() {}}": + "actor MyActor { func doWork() {}}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantNilCoalescingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantNilCoalescingRule.swift index 50f5af2eac..1f8eddb765 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantNilCoalescingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantNilCoalescingRule.swift @@ -9,18 +9,18 @@ struct RedundantNilCoalescingRule: Rule { name: "Redundant Nil Coalescing", description: "Coalescing operator with right-hand side nil is redundant", kind: .idiomatic, - nonTriggeringExamples: [ - Example("var myVar: Int?; myVar ?? 0") - ], - triggeringExamples: [ - Example("var myVar: Int? = nil; myVar ↓?? nil") - ], - corrections: [ - Example("var myVar: Int? = nil; let foo = myVar ↓?? nil"): - Example("var myVar: Int? = nil; let foo = myVar"), - Example("let a = b ?? nil // swiftlint:disable:this redundant_nil_coalescing"): - Example("let a = b ?? nil // swiftlint:disable:this redundant_nil_coalescing"), - ] + nonTriggeringExamples: #examples([ + "var myVar: Int?; myVar ?? 0" + ]), + triggeringExamples: #examples([ + "var myVar: Int? = nil; myVar ↓?? nil" + ]), + corrections: #examplesDictionary([ + "var myVar: Int? = nil; let foo = myVar ↓?? nil": + "var myVar: Int? = nil; let foo = myVar", + "let a = b ?? nil // swiftlint:disable:this redundant_nil_coalescing": + "let a = b ?? nil // swiftlint:disable:this redundant_nil_coalescing", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantObjcAttributeRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantObjcAttributeRuleExamples.swift index 1b82b89f99..9b32913e6e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantObjcAttributeRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantObjcAttributeRuleExamples.swift @@ -1,14 +1,14 @@ struct RedundantObjcAttributeRuleExamples { - static let nonTriggeringExamples = [ - Example("@objc private var foo: String? {}"), - Example("@IBInspectable private var foo: String? {}"), - Example("@objc private func foo(_ sender: Any) {}"), - Example("@IBAction private func foo(_ sender: Any) {}"), - Example("@GKInspectable private var foo: String! {}"), - Example("private @GKInspectable var foo: String! {}"), - Example("@NSManaged var foo: String!"), - Example("@objc @NSCopying var foo: String!"), - Example(""" + static let nonTriggeringExamples = #examples([ + "@objc private var foo: String? {}", + "@IBInspectable private var foo: String? {}", + "@objc private func foo(_ sender: Any) {}", + "@IBAction private func foo(_ sender: Any) {}", + "@GKInspectable private var foo: String! {}", + "private @GKInspectable var foo: String! {}", + "@NSManaged var foo: String!", + "@objc @NSCopying var foo: String!", + """ @objcMembers class Foo { var bar: Any? @@ -18,36 +18,36 @@ struct RedundantObjcAttributeRuleExamples { var foo: Any? } } - """), - Example(""" + """, + """ @objc extension Foo { var bar: Int { return 0 } } - """), - Example(""" + """, + """ extension Foo { @objc var bar: Int { return 0 } } - """), - Example(""" + """, + """ @objc @IBDesignable extension Foo { var bar: Int { return 0 } } - """), - Example(""" + """, + """ @IBDesignable extension Foo { @objc var bar: Int { return 0 } var fooBar: Int { return 1 } } - """), - Example(""" + """, + """ @objcMembers class Foo: NSObject { @objc @@ -55,8 +55,8 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """), - Example(""" + """, + """ @objcMembers class Foo { @objc @@ -64,20 +64,20 @@ struct RedundantObjcAttributeRuleExamples { @objc var foo: Any? } } - """), - Example(""" + """, + """ @objcMembers class Foo: NSObject { @objc class Bar {} } - """), - Example(""" + """, + """ extension BlockEditorSettings { @objc(addElementsObject:) @NSManaged public func addToElements(_ value: BlockEditorSettingElement) } - """), - Example(""" + """, + """ @objcMembers public class Foo: NSObject { @objc @@ -88,8 +88,8 @@ struct RedundantObjcAttributeRuleExamples { NotificationCenter.default.addObserver(self, selector: #selector(handler(_:)), name: nil, object: nil) } } - """), - Example(""" + """, + """ class Foo: NSObject { } @objc extension Foo { @@ -99,8 +99,8 @@ struct RedundantObjcAttributeRuleExamples { var bar: Bar { .bar } } - """), - Example(""" + """, + """ class Foo: NSObject { } @objc extension Foo { @@ -110,8 +110,8 @@ struct RedundantObjcAttributeRuleExamples { private var baz: Baz { .baz } } - """), - Example(""" + """, + """ @objcMembers internal class Foo: NSObject { @objc @@ -121,34 +121,34 @@ struct RedundantObjcAttributeRuleExamples { value(forKey: "baz") } } - """), - Example(""" + """, + """ @objcMembers class Foo: NSObject { @objc enum Bar: Int { case bar } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example("↓@objc @IBInspectable private var foo: String? {}"), - Example("@IBInspectable ↓@objc private var foo: String? {}"), - Example("↓@objc @IBAction private func foo(_ sender: Any) {}"), - Example("@IBAction ↓@objc private func foo(_ sender: Any) {}"), - Example("↓@objc @GKInspectable private var foo: String! {}"), - Example("@GKInspectable ↓@objc private var foo: String! {}"), - Example("↓@objc @NSManaged private var foo: String!"), - Example("@NSManaged ↓@objc private var foo: String!"), - Example("↓@objc @IBDesignable class Foo {}"), - Example(""" + static let triggeringExamples = #examples([ + "↓@objc @IBInspectable private var foo: String? {}", + "@IBInspectable ↓@objc private var foo: String? {}", + "↓@objc @IBAction private func foo(_ sender: Any) {}", + "@IBAction ↓@objc private func foo(_ sender: Any) {}", + "↓@objc @GKInspectable private var foo: String! {}", + "@GKInspectable ↓@objc private var foo: String! {}", + "↓@objc @NSManaged private var foo: String!", + "@NSManaged ↓@objc private var foo: String!", + "↓@objc @IBDesignable class Foo {}", + """ @objcMembers class Foo: NSObject { ↓@objc var bar: Any? } - """), - Example(""" + """, + """ @objcMembers class Foo: NSObject { ↓@objc var bar: Any? @@ -159,8 +159,8 @@ struct RedundantObjcAttributeRuleExamples { var foo: Any? } } - """), - Example(""" + """, + """ @objc extension Foo { ↓@objc @@ -168,8 +168,8 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """), - Example(""" + """, + """ @objc @IBDesignable extension Foo { ↓@objc @@ -177,8 +177,8 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """), - Example(""" + """, + """ @objcMembers class Foo: NSObject { @objcMembers @@ -186,8 +186,8 @@ struct RedundantObjcAttributeRuleExamples { ↓@objc var foo: Any } } - """), - Example(""" + """, + """ @objc extension Foo { ↓@objc @@ -195,36 +195,36 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """), - ] + """, + ]) - static let corrections = [ - Example("↓@objc @IBInspectable private var foo: String? {}"): - Example("@IBInspectable private var foo: String? {}"), - Example("@IBInspectable ↓@objc private var foo: String? {}"): - Example("@IBInspectable private var foo: String? {}"), - Example("@IBAction ↓@objc private func foo(_ sender: Any) {}"): - Example("@IBAction private func foo(_ sender: Any) {}"), - Example("↓@objc @GKInspectable private var foo: String! {}"): - Example("@GKInspectable private var foo: String! {}"), - Example("@GKInspectable ↓@objc private var foo: String! {}"): - Example("@GKInspectable private var foo: String! {}"), - Example("↓@objc @NSManaged private var foo: String!"): Example("@NSManaged private var foo: String!"), - Example("@NSManaged ↓@objc private var foo: String!"): Example("@NSManaged private var foo: String!"), - Example("↓@objc @IBDesignable class Foo {}"): Example("@IBDesignable class Foo {}"), - Example(""" + static let corrections = #examplesDictionary([ + "↓@objc @IBInspectable private var foo: String? {}": + "@IBInspectable private var foo: String? {}", + "@IBInspectable ↓@objc private var foo: String? {}": + "@IBInspectable private var foo: String? {}", + "@IBAction ↓@objc private func foo(_ sender: Any) {}": + "@IBAction private func foo(_ sender: Any) {}", + "↓@objc @GKInspectable private var foo: String! {}": + "@GKInspectable private var foo: String! {}", + "@GKInspectable ↓@objc private var foo: String! {}": + "@GKInspectable private var foo: String! {}", + "↓@objc @NSManaged private var foo: String!": "@NSManaged private var foo: String!", + "@NSManaged ↓@objc private var foo: String!": "@NSManaged private var foo: String!", + "↓@objc @IBDesignable class Foo {}": "@IBDesignable class Foo {}", + """ @objcMembers class Foo: NSObject { ↓@objc var bar: Any? } - """): - Example(""" + """: + """ @objcMembers class Foo: NSObject { var bar: Any? } - """), - Example(""" + """, + """ @objcMembers class Foo: NSObject { ↓@objc var bar: Any? @@ -235,8 +235,8 @@ struct RedundantObjcAttributeRuleExamples { var foo2: Any? } } - """): - Example(""" + """: + """ @objcMembers class Foo: NSObject { var bar: Any? @@ -247,8 +247,8 @@ struct RedundantObjcAttributeRuleExamples { var foo2: Any? } } - """), - Example(""" + """, + """ @objc extension Foo { ↓@objc @@ -256,16 +256,16 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """): - Example(""" + """: + """ @objc extension Foo { var bar: Int { return 0 } } - """), - Example(""" + """, + """ @objc @IBDesignable extension Foo { ↓@objc @@ -273,16 +273,16 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """): - Example(""" + """: + """ @objc @IBDesignable extension Foo { var bar: Int { return 0 } } - """), - Example(""" + """, + """ @objcMembers class Foo: NSObject { @objcMembers @@ -290,8 +290,8 @@ struct RedundantObjcAttributeRuleExamples { ↓@objc var foo: Any } } - """): - Example(""" + """: + """ @objcMembers class Foo: NSObject { @objcMembers @@ -299,8 +299,8 @@ struct RedundantObjcAttributeRuleExamples { var foo: Any } } - """), - Example(""" + """, + """ @objc extension Foo { ↓@objc @@ -308,16 +308,16 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """): - Example(""" + """: + """ @objc extension Foo { private var bar: Int { return 0 } } - """), - Example(""" + """, + """ @objc extension Foo { ↓@objc @@ -327,14 +327,14 @@ struct RedundantObjcAttributeRuleExamples { return 0 } } - """): - Example(""" + """: + """ @objc extension Foo { private var bar: Int { return 0 } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantSetAccessControlRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantSetAccessControlRule.swift index 92fc0a426c..280a39bfbe 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantSetAccessControlRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantSetAccessControlRule.swift @@ -31,32 +31,32 @@ struct RedundantSetAccessControlRule: Rule { } """), ], - triggeringExamples: [ - Example("↓private(set) private var foo: Int"), - Example("↓fileprivate(set) fileprivate var foo: Int"), - Example("↓internal(set) internal var foo: Int"), - Example("↓public(set) public var foo: Int"), - Example(""" + triggeringExamples: #examples([ + "↓private(set) private var foo: Int", + "↓fileprivate(set) fileprivate var foo: Int", + "↓internal(set) internal var foo: Int", + "↓public(set) public var foo: Int", + """ open class Foo { ↓open(set) open var bar: Int } - """), - Example(""" + """, + """ class A { ↓internal(set) var value: Int } - """), - Example(""" + """, + """ internal class A { ↓internal(set) var value: Int } - """), - Example(""" + """, + """ fileprivate class A { ↓fileprivate(set) var value: Int } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantStringEnumValueRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantStringEnumValueRule.swift index e39ffed5a9..2d3c7db646 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantStringEnumValueRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantStringEnumValueRule.swift @@ -9,55 +9,55 @@ struct RedundantStringEnumValueRule: Rule { name: "Redundant String Enum Value", description: "String enum values can be omitted when they are equal to the enumcase name", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum Numbers: String { case one case two } - """), - Example(""" + """, + """ enum Numbers: Int { case one = 1 case two = 2 } - """), - Example(""" + """, + """ enum Numbers: String { case one = "ONE" case two = "TWO" } - """), - Example(""" + """, + """ enum Numbers: String { case one = "ONE" case two = "two" } - """), - Example(""" + """, + """ enum Numbers: String { case one, two } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ enum Numbers: String { case one = ↓"one" case two = ↓"two" } - """), - Example(""" + """, + """ enum Numbers: String { case one = ↓"one", two = ↓"two" } - """), - Example(""" + """, + """ enum Numbers: String { case one, two = ↓"two" } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantVoidReturnRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantVoidReturnRule.swift index 8ed486f525..6c0acd830e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantVoidReturnRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/RedundantVoidReturnRule.swift @@ -34,39 +34,39 @@ struct RedundantVoidReturnRule: Rule { } """, configuration: ["include_closures": false]), ], - triggeringExamples: [ - Example("func foo()↓ -> Void {}"), - Example(""" + triggeringExamples: #examples([ + "func foo()↓ -> Void {}", + """ protocol Foo { func foo()↓ -> Void } - """), - Example("func foo()↓ -> () {}"), - Example("func foo()↓ -> ( ) {}"), - Example(""" + """, + "func foo()↓ -> () {}", + "func foo()↓ -> ( ) {}", + """ protocol Foo { func foo()↓ -> () } - """), - Example(""" + """, + """ doSomething { arg↓ -> () in print(arg) } - """), - Example(""" + """, + """ doSomething { arg↓ -> Void in print(arg) } - """), - ], - corrections: [ - Example("func foo()↓ -> Void {}"): Example("func foo() {}"), - Example("protocol Foo {\n func foo()↓ -> Void\n}"): Example("protocol Foo {\n func foo()\n}"), - Example("func foo()↓ -> () {}"): Example("func foo() {}"), - Example("protocol Foo {\n func foo()↓ -> ()\n}"): Example("protocol Foo {\n func foo()\n}"), - Example("protocol Foo {\n #if true\n func foo()↓ -> Void\n #endif\n}"): - Example("protocol Foo {\n #if true\n func foo()\n #endif\n}"), - ] + """, + ]), + corrections: #examplesDictionary([ + "func foo()↓ -> Void {}": "func foo() {}", + "protocol Foo {\n func foo()↓ -> Void\n}": "protocol Foo {\n func foo()\n}", + "func foo()↓ -> () {}": "func foo() {}", + "protocol Foo {\n func foo()↓ -> ()\n}": "protocol Foo {\n func foo()\n}", + "protocol Foo {\n #if true\n func foo()↓ -> Void\n #endif\n}": + "protocol Foo {\n #if true\n func foo()\n #endif\n}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ReturnValueFromVoidFunctionRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ReturnValueFromVoidFunctionRuleExamples.swift index 5dd45d712f..eac0c84552 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ReturnValueFromVoidFunctionRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ReturnValueFromVoidFunctionRuleExamples.swift @@ -149,56 +149,56 @@ internal struct ReturnValueFromVoidFunctionRuleExamples { """#, excludeFromDocumentation: true), ] - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ func foo() { ↓return bar() } - """), - Example(""" + """, + """ func foo() -> () { ↓return self.bar() } - """), - Example(""" + """, + """ func foo() -> Void { ↓return bar() } - """), - Example(""" + """, + """ func foo() -> Void { ↓return /* comment */ bar() } - """), - Example(""" + """, + """ func foo() { ↓return self.bar() } - """), - Example(""" + """, + """ func foo() { variable += 1 ↓return variable += 1 } - """), - Example(""" + """, + """ func initThing() { guard foo else { ↓return print("") } } - """), - Example(""" + """, + """ // Leading comment func test() { guard condition else { ↓return assertionfailure("") } } - """), - Example(""" + """, + """ func test() -> Result { func other() { guard false else { @@ -207,8 +207,8 @@ internal struct ReturnValueFromVoidFunctionRuleExamples { } func otherVoid() -> Void {} } - """), - Example(""" + """, + """ func test() { guard conditionIsTrue else { sideEffects() @@ -219,24 +219,24 @@ internal struct ReturnValueFromVoidFunctionRuleExamples { } differentSideEffect() } - """), - Example(""" + """, + """ func test() { guard otherCondition else { ↓return assertionfailure(""); // comment } differentSideEffect() } - """), - Example(""" + """, + """ func test() { if x { ↓return foo() } bar() } - """), - Example(""" + """, + """ func test() { switch x { case .a: @@ -246,8 +246,8 @@ internal struct ReturnValueFromVoidFunctionRuleExamples { } baz() } - """), - Example(""" + """, + """ func test() { if check { if otherCheck { @@ -256,28 +256,28 @@ internal struct ReturnValueFromVoidFunctionRuleExamples { } bar() } - """), - Example(""" + """, + """ func test() { ↓return foo() } - """), - Example(""" + """, + """ func test() { ↓return foo({ return bar() }) } - """), - Example(""" + """, + """ func test() { guard x else { ↓return foo() } bar() } - """), - Example(""" + """, + """ func test() { let closure: () -> () = { return assert() @@ -289,30 +289,30 @@ internal struct ReturnValueFromVoidFunctionRuleExamples { } ↓return foo() } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ func f() -> Void { ↓return g() // some comment } - """): Example(""" + """: """ func f() -> Void { g() return // some comment } - """), - Example(""" + """, + """ func f(b: Bool) { if b { // some comment ↓return g() } } - """): Example(""" + """: """ func f(b: Bool) { if b { // some comment @@ -320,6 +320,6 @@ internal struct ReturnValueFromVoidFunctionRuleExamples { return } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ShorthandOptionalBindingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ShorthandOptionalBindingRule.swift index 4e50af8092..c147caea68 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ShorthandOptionalBindingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ShorthandOptionalBindingRule.swift @@ -50,33 +50,33 @@ struct ShorthandOptionalBindingRule: Rule { while ↓var i = i { i = nil } """), ], - corrections: [ - Example(""" + corrections: #examplesDictionary([ + """ if ↓let i = i {} - """): Example(""" + """: """ if let i {} - """), - Example(""" + """, + """ if ↓let self = self {} - """): Example(""" + """: """ if let self {} - """), - Example(""" + """, + """ if ↓var `self` = `self` {} - """): Example(""" + """: """ if var `self` {} - """), - Example(""" + """, + """ guard ↓let i = i, ↓var j = j , ↓let k =k else {} - """): Example(""" + """: """ guard let i, var j , let k else {} - """), - Example(""" + """, + """ while j > 0, ↓var i = i { i = nil } - """): Example(""" + """: """ while j > 0, var i { i = nil } - """), - ], + """, + ]), deprecatedAliases: ["if_let_shadowing"] ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOperatorRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOperatorRule.swift index 54da156dcd..8cb3d91fea 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOperatorRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOperatorRule.swift @@ -9,28 +9,28 @@ struct StaticOperatorRule: Rule { name: "Static Operator", description: "Operators should be declared as static functions, not free functions", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class A: Equatable { static func == (lhs: A, rhs: A) -> Bool { return false } - """), - Example(""" + """, + """ class A: Equatable { static func == (lhs: A, rhs: A) -> Bool { return false } - """), - Example(""" + """, + """ public extension Array where Element == Rule { static func == (lhs: Array, rhs: Array) -> Bool { if lhs.count != rhs.count { return false } return !zip(lhs, rhs).contains { !$0.0.isEqualTo($0.1) } } } - """), - Example(""" + """, + """ private extension Optional where Wrapped: Comparable { static func < (lhs: Optional, rhs: Optional) -> Bool { switch (lhs, rhs) { @@ -43,26 +43,26 @@ struct StaticOperatorRule: Rule { } } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓func == (lhs: A, rhs: A) -> Bool { return false } - """), - Example(""" + """, + """ ↓func == (lhs: A, rhs: A) -> Bool { return false } - """), - Example(""" + """, + """ ↓func == (lhs: [Rule], rhs: [Rule]) -> Bool { if lhs.count != rhs.count { return false } return !zip(lhs, rhs).contains { !$0.0.isEqualTo($0.1) } } - """), - Example(""" + """, + """ private ↓func < (lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (lhs?, rhs?): @@ -73,8 +73,8 @@ struct StaticOperatorRule: Rule { return false } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOverFinalClassRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOverFinalClassRule.swift index b0cf8be5f1..d8e3dfbd6d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOverFinalClassRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/StaticOverFinalClassRule.swift @@ -13,67 +13,67 @@ struct StaticOverFinalClassRule: Rule { about `open` being used in `final` classes. """, kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class C { static func f() {} } - """), - Example(""" + """, + """ class C { static var i: Int { 0 } } - """), - Example(""" + """, + """ class C { static subscript(_: Int) -> Int { 0 } } - """), - Example(""" + """, + """ class C { class func f() {} } - """), - Example(""" + """, + """ final class C {} - """), - Example(""" + """, + """ final class C { class D { class func f() {} } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ class C { ↓final class func f() {} } - """), - Example(""" + """, + """ class C { ↓final class var i: Int { 0 } } - """), - Example(""" + """, + """ class C { ↓final class subscript(_: Int) -> Int { 0 } } - """), - Example(""" + """, + """ final class C { ↓class func f() {} } - """), - Example(""" + """, + """ class C { final class D { ↓class func f() {} } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/SyntacticSugarRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/SyntacticSugarRuleExamples.swift index 6b1a57c35a..fdcb3fe5a0 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/SyntacticSugarRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/SyntacticSugarRuleExamples.swift @@ -31,56 +31,56 @@ internal enum SyntacticSugarRuleExamples { Example("func f() -> [Array.Index] { [Array.Index]() }", excludeFromDocumentation: true), ] - static let triggering = [ - Example("let x: ↓Array"), - Example("let x: ↓Dictionary"), - Example("let x: ↓Optional"), - Example("let x: ↓Swift.Array"), + static let triggering = #examples([ + "let x: ↓Array", + "let x: ↓Dictionary", + "let x: ↓Optional", + "let x: ↓Swift.Array", - Example("func x(a: ↓Array, b: Int) -> [Int: Any]"), - Example("func x(a: ↓Swift.Array, b: Int) -> [Int: Any]"), + "func x(a: ↓Array, b: Int) -> [Int: Any]", + "func x(a: ↓Swift.Array, b: Int) -> [Int: Any]", - Example("func x(a: [Int], b: Int) -> ↓Dictionary"), - Example("let x = y as? ↓Array<[String: Any]>"), - Example("let x = Box>()"), - Example("func x() -> Box<↓Array>"), - Example("func x() -> ↓Dictionary?"), + "func x(a: [Int], b: Int) -> ↓Dictionary", + "let x = y as? ↓Array<[String: Any]>", + "let x = Box>()", + "func x() -> Box<↓Array>", + "func x() -> ↓Dictionary?", - Example("typealias Document = ↓Dictionary"), - Example("func x(_ y: inout ↓Array)"), - Example("let x:↓Dictionary>"), - Example("func x() -> Any { return ↓Dictionary()}"), + "typealias Document = ↓Dictionary", + "func x(_ y: inout ↓Array)", + "let x:↓Dictionary>", + "func x() -> Any { return ↓Dictionary()}", - Example("let x = ↓Array.array(of: object)"), - Example("let x = ↓Swift.Array.array(of: object)"), + "let x = ↓Array.array(of: object)", + "let x = ↓Swift.Array.array(of: object)", - Example(""" + """ @_specialize(where S == ↓Array) public init(_ elements: S) - """), + """, - Example(""" + """ let dict: [String: Any] = [:] _ = dict["key"] as? ↓Optional ?? Optional.none - """), - ] + """, + ]) - static let corrections = [ - Example("let x: Array"): Example("let x: [String]"), - Example("let x: Array< String >"): Example("let x: [String]"), - Example("let x: Dictionary"): Example("let x: [Int: String]"), - Example("let x: Optional"): Example("let x: Int?"), - Example("let x: Optional< Int >"): Example("let x: Int?"), - Example("func f() -> Optional {}"): Example("func f() -> (any Foo)? {}"), - Example("func f() -> Optional {}"): Example("func f() -> (some Foo)? {}"), + static let corrections = #examplesDictionary([ + "let x: Array": "let x: [String]", + "let x: Array< String >": "let x: [String]", + "let x: Dictionary": "let x: [Int: String]", + "let x: Optional": "let x: Int?", + "let x: Optional< Int >": "let x: Int?", + "func f() -> Optional {}": "func f() -> (any Foo)? {}", + "func f() -> Optional {}": "func f() -> (some Foo)? {}", - Example("let x: Dictionary"): Example("let x: [Int: String]"), - Example("let x: Swift.Optional"): Example("let x: String?"), - Example("let x:↓Dictionary>"): Example("let x:[String: [Int: Int]]"), - Example("let x:↓Dictionary<↓Dictionary, String>"): Example("let x:[[Int: Int]: String]"), - Example("let x:↓Dictionary<↓Dictionary<↓Dictionary, Int>, String>"): - Example("let x:[[[Int: Int]: Int]: String]"), - Example("let x:↓Array<↓Dictionary>"): Example("let x:[[Int: Int]]"), - Example("let x:↓Optional<↓Dictionary>"): Example("let x:[Int: Int]?"), - ] + "let x: Dictionary": "let x: [Int: String]", + "let x: Swift.Optional": "let x: String?", + "let x:↓Dictionary>": "let x:[String: [Int: Int]]", + "let x:↓Dictionary<↓Dictionary, String>": "let x:[[Int: Int]: String]", + "let x:↓Dictionary<↓Dictionary<↓Dictionary, Int>, String>": + "let x:[[[Int: Int]: Int]: String]", + "let x:↓Array<↓Dictionary>": "let x:[[Int: Int]]", + "let x:↓Optional<↓Dictionary>": "let x:[Int: Int]?", + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ToggleBoolRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ToggleBoolRule.swift index 326d1da4d5..fa359c80f1 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ToggleBoolRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ToggleBoolRule.swift @@ -10,24 +10,24 @@ struct ToggleBoolRule: Rule { name: "Toggle Bool", description: "Prefer `someBool.toggle()` over `someBool = !someBool`", kind: .idiomatic, - nonTriggeringExamples: [ - Example("isHidden.toggle()"), - Example("view.clipsToBounds.toggle()"), - Example("func foo() { abc.toggle() }"), - Example("view.clipsToBounds = !clipsToBounds"), - Example("disconnected = !connected"), - Example("result = !result.toggle()"), - ], - triggeringExamples: [ - Example("↓isHidden = !isHidden"), - Example("↓view.clipsToBounds = !view.clipsToBounds"), - Example("func foo() { ↓abc = !abc }"), - ], - corrections: [ - Example("↓isHidden = !isHidden"): Example("isHidden.toggle()"), - Example("↓view.clipsToBounds = !view.clipsToBounds"): Example("view.clipsToBounds.toggle()"), - Example("func foo() { ↓abc = !abc }"): Example("func foo() { abc.toggle() }"), - ] + nonTriggeringExamples: #examples([ + "isHidden.toggle()", + "view.clipsToBounds.toggle()", + "func foo() { abc.toggle() }", + "view.clipsToBounds = !clipsToBounds", + "disconnected = !connected", + "result = !result.toggle()", + ]), + triggeringExamples: #examples([ + "↓isHidden = !isHidden", + "↓view.clipsToBounds = !view.clipsToBounds", + "func foo() { ↓abc = !abc }", + ]), + corrections: #examplesDictionary([ + "↓isHidden = !isHidden": "isHidden.toggle()", + "↓view.clipsToBounds = !view.clipsToBounds": "view.clipsToBounds.toggle()", + "func foo() { ↓abc = !abc }": "func foo() { abc.toggle() }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/TrailingSemicolonRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/TrailingSemicolonRule.swift index 1a77cde0fe..198d076840 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/TrailingSemicolonRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/TrailingSemicolonRule.swift @@ -9,20 +9,20 @@ struct TrailingSemicolonRule: Rule { name: "Trailing Semicolon", description: "Lines should not have trailing semicolons", kind: .idiomatic, - nonTriggeringExamples: [ - Example("let a = 0"), - Example("let a = 0; let b = 0"), - ], - triggeringExamples: [ - Example("let a = 0↓;\n"), - Example("let a = 0↓;\nlet b = 1"), - Example("let a = 0↓; // a comment\n"), - ], - corrections: [ - Example("let a = 0↓;\n"): Example("let a = 0\n"), - Example("let a = 0↓;\nlet b = 1"): Example("let a = 0\nlet b = 1"), - Example("let foo = 12↓; // comment\n"): Example("let foo = 12 // comment\n"), - ] + nonTriggeringExamples: #examples([ + "let a = 0", + "let a = 0; let b = 0", + ]), + triggeringExamples: #examples([ + "let a = 0↓;\n", + "let a = 0↓;\nlet b = 1", + "let a = 0↓; // a comment\n", + ]), + corrections: #examplesDictionary([ + "let a = 0↓;\n": "let a = 0\n", + "let a = 0↓;\nlet b = 1": "let a = 0\nlet b = 1", + "let foo = 12↓; // comment\n": "let foo = 12 // comment\n", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableConditionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableConditionRule.swift index 2a6c8954b7..d2d9ff4f33 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableConditionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableConditionRule.swift @@ -40,34 +40,34 @@ struct UnavailableConditionRule: Rule { } """, excludeFromDocumentation: true), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ if ↓#available(iOS 14.0) { } else { oldIos13TrackingLogic(isEnabled: ASIdentifierManager.shared().isAdvertisingTrackingEnabled) } - """), - Example(""" + """, + """ if ↓#available(iOS 14.0) { // we don't need to do anything here } else { oldIos13TrackingLogic(isEnabled: ASIdentifierManager.shared().isAdvertisingTrackingEnabled) } - """), - Example(""" + """, + """ if ↓#available(iOS 13, *) {} else { loadMainWindow() } - """), - Example(""" + """, + """ if ↓#unavailable(iOS 13) { // Do nothing } else if i < 2 { loadMainWindow() } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableFunctionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableFunctionRule.swift index d7ab62bceb..8678b8fda5 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableFunctionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnavailableFunctionRule.swift @@ -9,16 +9,16 @@ struct UnavailableFunctionRule: Rule { name: "Unavailable Function", description: "Unimplemented functions should be marked as unavailable", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class ViewController: UIViewController { @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { preconditionFailure("init(coder:) has not been implemented") } } - """), - Example(""" + """, + """ func jsonValue(_ jsonString: String) -> NSObject { let data = jsonString.data(using: .utf8)! let result = try! JSONSerialization.jsonObject(with: data, options: []) @@ -29,46 +29,46 @@ struct UnavailableFunctionRule: Rule { } fatalError() } - """), - Example(""" + """, + """ func resetOnboardingStateAndCrash() -> Never { resetUserDefaults() // Crash the app to re-start the onboarding flow. fatalError("Onboarding re-start crash.") } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ class ViewController: UIViewController { public required ↓init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } - """), - Example(""" + """, + """ class ViewController: UIViewController { public required ↓init?(coder aDecoder: NSCoder) { let reason = "init(coder:) has not been implemented" fatalError(reason) } } - """), - Example(""" + """, + """ class ViewController: UIViewController { public required ↓init?(coder aDecoder: NSCoder) { preconditionFailure("init(coder:) has not been implemented") } } - """), - Example(""" + """, + """ ↓func resetOnboardingStateAndCrash() { resetUserDefaults() // Crash the app to re-start the onboarding flow. fatalError("Onboarding re-start crash.") } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift index ebeec84c4e..d590ad5465 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift @@ -252,8 +252,8 @@ enum UnneededSynthesizedInitializerRuleExamples { """), ] - static let triggering = [ - Example(""" + static let triggering = #examples([ + """ struct Foo { let bar: String @@ -261,8 +261,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ struct Foo { var bar: String @@ -270,8 +270,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ private struct Foo { let bar: String @@ -279,8 +279,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ fileprivate struct Foo { let bar: String @@ -288,8 +288,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ internal struct Foo { fileprivate var bar: String @@ -297,8 +297,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ internal struct Foo { private var bar: String @@ -306,8 +306,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ struct Foo { var foo: String var bar: String @@ -317,8 +317,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ internal struct Foo { var bar: String @@ -326,8 +326,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ struct Foo { var bar: String = "" @@ -336,8 +336,8 @@ enum UnneededSynthesizedInitializerRuleExamples { // when all vars have default values. } } - """), - Example(""" + """, + """ struct Foo { var bar: String = "" @@ -349,8 +349,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ struct Foo { var bar = "" @@ -358,8 +358,8 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """), - Example(""" + """, + """ struct Outer { struct Inner { let prop: Int @@ -369,8 +369,8 @@ enum UnneededSynthesizedInitializerRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { struct Bar { let baz: Int @@ -380,8 +380,8 @@ enum UnneededSynthesizedInitializerRuleExamples { } } } - """), - Example(""" + """, + """ struct Foo { let i: Int struct Bar { @@ -394,11 +394,11 @@ enum UnneededSynthesizedInitializerRuleExamples { self.i = i } } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ struct Foo { let bar: String @@ -411,7 +411,7 @@ enum UnneededSynthesizedInitializerRuleExamples { // Padding } } - """): Example(""" + """: """ struct Foo { let bar: String @@ -420,8 +420,8 @@ enum UnneededSynthesizedInitializerRuleExamples { // Padding } } - """), - Example(""" + """, + """ struct Foo { var bar: String @@ -429,12 +429,12 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """): Example(""" + """: """ struct Foo { var bar: String } - """), - Example(""" + """, + """ private struct Foo { let bar: String @@ -442,12 +442,12 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """): Example(""" + """: """ private struct Foo { let bar: String } - """), - Example(""" + """, + """ fileprivate struct Foo { let bar: String @@ -455,12 +455,12 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """): Example(""" + """: """ fileprivate struct Foo { let bar: String } - """), - Example(""" + """, + """ internal struct Foo { fileprivate var bar: String @@ -468,12 +468,12 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """): Example(""" + """: """ internal struct Foo { fileprivate var bar: String } - """), - Example(""" + """, + """ internal struct Foo { private var bar: String @@ -481,12 +481,12 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """): Example(""" + """: """ internal struct Foo { private var bar: String } - """), - Example(""" + """, + """ struct Foo { var foo: String var bar: String @@ -496,13 +496,13 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """): Example(""" + """: """ struct Foo { var foo: String var bar: String } - """), - Example(""" + """, + """ internal struct Foo { var bar: String @@ -510,12 +510,12 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } - """): Example(""" + """: """ internal struct Foo { var bar: String } - """), - Example(""" + """, + """ struct Foo { var bar: String = "" @@ -524,12 +524,12 @@ enum UnneededSynthesizedInitializerRuleExamples { // when all vars have default values. } } - """): Example(""" + """: """ struct Foo { var bar: String = "" } - """), - Example(""" + """, + """ struct Outer { struct Inner { let prop: Int @@ -539,12 +539,12 @@ enum UnneededSynthesizedInitializerRuleExamples { } } } - """): Example(""" + """: """ struct Outer { struct Inner { let prop: Int } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UntypedErrorInCatchRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UntypedErrorInCatchRule.swift index 029aab762e..0ed83c8b6c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UntypedErrorInCatchRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UntypedErrorInCatchRule.swift @@ -9,31 +9,31 @@ struct UntypedErrorInCatchRule: Rule { name: "Untyped Error in Catch", description: "Catch statements should not declare error variables without type casting", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ do { try foo() } catch {} - """), - Example(""" + """, + """ do { try foo() } catch Error.invalidOperation { } catch {} - """), - Example(""" + """, + """ do { try foo() } catch let error as MyError { } catch {} - """), - Example(""" + """, + """ do { try foo() } catch var error as MyError { } catch {} - """), - Example(""" + """, + """ do { try something() } catch let e where e.code == .fileError { @@ -41,50 +41,50 @@ struct UntypedErrorInCatchRule: Rule { } catch { print(error) } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ do { try foo() } ↓catch var error {} - """), - Example(""" + """, + """ do { try foo() } ↓catch let error {} - """), - Example(""" + """, + """ do { try foo() } ↓catch let someError {} - """), - Example(""" + """, + """ do { try foo() } ↓catch var someError {} - """), - Example(""" + """, + """ do { try foo() } ↓catch let e {} - """), - Example(""" + """, + """ do { try foo() } ↓catch(let error) {} - """), - Example(""" + """, + """ do { try foo() } ↓catch (let error) {} - """), - ], - corrections: [ - Example("do {\n try foo() \n} ↓catch let error {}"): Example("do {\n try foo() \n} catch {}"), - Example("do {\n try foo() \n} ↓catch(let error) {}"): Example("do {\n try foo() \n} catch {}"), - Example("do {\n try foo() \n} ↓catch (let error) {}"): Example("do {\n try foo() \n} catch {}"), - ]) + """, + ]), + corrections: #examplesDictionary([ + "do {\n try foo() \n} ↓catch let error {}": "do {\n try foo() \n} catch {}", + "do {\n try foo() \n} ↓catch(let error) {}": "do {\n try foo() \n} catch {}", + "do {\n try foo() \n} ↓catch (let error) {}": "do {\n try foo() \n} catch {}", + ])) } private extension CatchItemSyntax { diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/VoidFunctionInTernaryConditionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/VoidFunctionInTernaryConditionRule.swift index 27f7c3ad57..5dfb8a9a98 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/VoidFunctionInTernaryConditionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/VoidFunctionInTernaryConditionRule.swift @@ -10,73 +10,73 @@ struct VoidFunctionInTernaryConditionRule: Rule { description: "Using ternary to call Void functions should be avoided", kind: .idiomatic, minSwiftVersion: .fiveDotOne, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ if success { askQuestion() } else { exit() } - """), - Example(""" + """, + """ var price: Double { return hasDiscount ? calculatePriceWithDiscount() : calculateRegularPrice() } - """), - Example("foo(x == 2 ? a() : b())"), - Example(""" + """, + "foo(x == 2 ? a() : b())", + """ chevronView.image = collapsed ? .icon(.mediumChevronDown) : .icon(.mediumChevronUp) - """), - Example(""" + """, + """ array.map { elem in elem.isEmpty() ? .emptyValue() : .number(elem) } - """), - Example(""" + """, + """ func compute(data: [Int]) -> Int { data.isEmpty ? 0 : expensiveComputation(data) } - """), - Example(""" + """, + """ var value: Int { mode == .fast ? fastComputation() : expensiveComputation() } - """), - Example(""" + """, + """ var value: Int { get { mode == .fast ? fastComputation() : expensiveComputation() } } - """), - Example(""" + """, + """ subscript(index: Int) -> Int { get { index == 0 ? defaultValue() : compute(index) } - """), - Example(""" + """, + """ subscript(index: Int) -> Int { index == 0 ? defaultValue() : compute(index) - """), - Example(""" + """, + """ var a = b ? c() : d() a += b ? c() : d() a -= b ? c() : d() a *= b ? c() : d() a &<<= b ? c() : d() a &-= b ? c() : d() - """), - ], - triggeringExamples: [ - Example("success ↓? askQuestion() : exit()"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "success ↓? askQuestion() : exit()", + """ perform { elem in elem.isEmpty() ↓? .emptyValue() : .number(elem) return 1 } - """), - Example(""" + """, + """ DispatchQueue.main.async { self.sectionViewModels[section].collapsed.toggle() self.sectionViewModels[section].collapsed @@ -84,34 +84,34 @@ struct VoidFunctionInTernaryConditionRule: Rule { : self.tableView.insertRows(at: [IndexPath(row: 0, section: section)], with: .automatic) self.tableView.scrollToRow(at: IndexPath(row: NSNotFound, section: section), at: .top, animated: true) } - """), - Example(""" + """, + """ subscript(index: Int) -> Int { index == 0 ↓? something() : somethingElse(index) return index - """), - Example(""" + """, + """ var value: Int { mode == .fast ↓? something() : somethingElse() return 0 } - """), - Example(""" + """, + """ var value: Int { get { mode == .fast ↓? something() : somethingElse() return 0 } } - """), - Example(""" + """, + """ subscript(index: Int) -> Int { get { index == 0 ↓? something() : somethingElse(index) return index } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTFailMessageRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTFailMessageRule.swift index 13309b5b44..72dc768835 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTFailMessageRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTFailMessageRule.swift @@ -9,30 +9,30 @@ struct XCTFailMessageRule: Rule { name: "XCTFail Message", description: "An XCTFail call should include a description of the assertion", kind: .idiomatic, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ func testFoo() { XCTFail("bar") } - """), - Example(""" + """, + """ func testFoo() { XCTFail(bar) } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ func testFoo() { ↓XCTFail() } - """), - Example(""" + """, + """ func testFoo() { ↓XCTFail("") } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTSpecificMatcherRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTSpecificMatcherRuleExamples.swift index dc8efdcb0b..0a3a1b37b1 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTSpecificMatcherRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/XCTSpecificMatcherRuleExamples.swift @@ -71,88 +71,88 @@ internal struct XCTSpecificMatcherRuleExamples { Example("XCTAssert(foo.self === bar.self)"), ] - static let triggeringExamples = [ + static let triggeringExamples = #examples([ // Without message - Example("↓XCTAssertEqual(foo, true)"), - Example("↓XCTAssertEqual(foo, false)"), - Example("↓XCTAssertEqual(foo, nil)"), - Example("↓XCTAssertNotEqual(foo, true)"), - Example("↓XCTAssertNotEqual(foo, false)"), - Example("↓XCTAssertNotEqual(foo, nil)"), + "↓XCTAssertEqual(foo, true)", + "↓XCTAssertEqual(foo, false)", + "↓XCTAssertEqual(foo, nil)", + "↓XCTAssertNotEqual(foo, true)", + "↓XCTAssertNotEqual(foo, false)", + "↓XCTAssertNotEqual(foo, nil)", // Inverted logic (just in case...) - Example("↓XCTAssertEqual(true, foo)"), - Example("↓XCTAssertEqual(false, foo)"), - Example("↓XCTAssertEqual(nil, foo)"), - Example("↓XCTAssertNotEqual(true, foo)"), - Example("↓XCTAssertNotEqual(false, foo)"), - Example("↓XCTAssertNotEqual(nil, foo)"), + "↓XCTAssertEqual(true, foo)", + "↓XCTAssertEqual(false, foo)", + "↓XCTAssertEqual(nil, foo)", + "↓XCTAssertNotEqual(true, foo)", + "↓XCTAssertNotEqual(false, foo)", + "↓XCTAssertNotEqual(nil, foo)", // With message - Example("↓XCTAssertEqual(foo, true, \"toto\")"), - Example("↓XCTAssertEqual(foo, false, \"toto\")"), - Example("↓XCTAssertEqual(foo, nil, \"toto\")"), - Example("↓XCTAssertNotEqual(foo, true, \"toto\")"), - Example("↓XCTAssertNotEqual(foo, false, \"toto\")"), - Example("↓XCTAssertNotEqual(foo, nil, \"toto\")"), - Example("↓XCTAssertEqual(true, foo, \"toto\")"), - Example("↓XCTAssertEqual(false, foo, \"toto\")"), - Example("↓XCTAssertEqual(nil, foo, \"toto\")"), - Example("↓XCTAssertNotEqual(true, foo, \"toto\")"), - Example("↓XCTAssertNotEqual(false, foo, \"toto\")"), - Example("↓XCTAssertNotEqual(nil, foo, \"toto\")"), + "↓XCTAssertEqual(foo, true, \"toto\")", + "↓XCTAssertEqual(foo, false, \"toto\")", + "↓XCTAssertEqual(foo, nil, \"toto\")", + "↓XCTAssertNotEqual(foo, true, \"toto\")", + "↓XCTAssertNotEqual(foo, false, \"toto\")", + "↓XCTAssertNotEqual(foo, nil, \"toto\")", + "↓XCTAssertEqual(true, foo, \"toto\")", + "↓XCTAssertEqual(false, foo, \"toto\")", + "↓XCTAssertEqual(nil, foo, \"toto\")", + "↓XCTAssertNotEqual(true, foo, \"toto\")", + "↓XCTAssertNotEqual(false, foo, \"toto\")", + "↓XCTAssertNotEqual(nil, foo, \"toto\")", // Blank spaces - Example("↓XCTAssertEqual(foo,true)"), - Example("↓XCTAssertEqual( foo , false )"), - Example("↓XCTAssertEqual( foo , nil )"), + "↓XCTAssertEqual(foo,true)", + "↓XCTAssertEqual( foo , false )", + "↓XCTAssertEqual( foo , nil )", // Arrays - Example("↓XCTAssertEqual(true, [1, 2, 3, true].hasNumbers())"), - Example("↓XCTAssertEqual([1, 2, 3, true].hasNumbers(), true)"), + "↓XCTAssertEqual(true, [1, 2, 3, true].hasNumbers())", + "↓XCTAssertEqual([1, 2, 3, true].hasNumbers(), true)", // Optionals - Example("↓XCTAssertEqual(foo?.bar, nil)"), - Example("↓XCTAssertNotEqual(foo?.bar, nil)"), + "↓XCTAssertEqual(foo?.bar, nil)", + "↓XCTAssertNotEqual(foo?.bar, nil)", // Weird cases - Example("↓XCTAssertEqual(nil, true)"), - Example("↓XCTAssertEqual(nil, false)"), - Example("↓XCTAssertEqual(true, nil)"), - Example("↓XCTAssertEqual(false, nil)"), - Example("↓XCTAssertEqual(nil, nil)"), - Example("↓XCTAssertEqual(true, true)"), - Example("↓XCTAssertEqual(false, false)"), + "↓XCTAssertEqual(nil, true)", + "↓XCTAssertEqual(nil, false)", + "↓XCTAssertEqual(true, nil)", + "↓XCTAssertEqual(false, nil)", + "↓XCTAssertEqual(nil, nil)", + "↓XCTAssertEqual(true, true)", + "↓XCTAssertEqual(false, false)", // Equality with `==` - Example("↓XCTAssert(foo == bar)"), - Example("↓XCTAssertTrue( foo == bar )"), - Example("↓XCTAssertFalse(1 == foo)"), - Example("↓XCTAssert(foo == bar, \"toto\")"), + "↓XCTAssert(foo == bar)", + "↓XCTAssertTrue( foo == bar )", + "↓XCTAssertFalse(1 == foo)", + "↓XCTAssert(foo == bar, \"toto\")", // Inequality with `!=` - Example("↓XCTAssert(foo != bar)"), - Example("↓XCTAssertTrue( foo != bar )"), - Example("↓XCTAssertFalse(1 != foo)"), - Example("↓XCTAssert(foo != bar, \"toto\")"), + "↓XCTAssert(foo != bar)", + "↓XCTAssertTrue( foo != bar )", + "↓XCTAssertFalse(1 != foo)", + "↓XCTAssert(foo != bar, \"toto\")", // Identity with `===` - Example("↓XCTAssert(foo === bar)"), - Example("↓XCTAssertTrue( foo === bar )"), - Example("↓XCTAssertFalse(bar === foo)"), - Example("↓XCTAssert(foo === bar, \"toto\")"), + "↓XCTAssert(foo === bar)", + "↓XCTAssertTrue( foo === bar )", + "↓XCTAssertFalse(bar === foo)", + "↓XCTAssert(foo === bar, \"toto\")", // Non-identity with `!==` - Example("↓XCTAssert(foo !== bar)"), - Example("↓XCTAssertTrue( foo !== bar )"), - Example("↓XCTAssertFalse(bar !== foo)"), - Example("↓XCTAssert(foo !== bar, \"toto\")"), + "↓XCTAssert(foo !== bar)", + "↓XCTAssertTrue( foo !== bar )", + "↓XCTAssertFalse(bar !== foo)", + "↓XCTAssert(foo !== bar, \"toto\")", // Comparison with `nil` - Example("↓XCTAssert( foo == nil)"), - Example("↓XCTAssert(nil == foo"), - Example("↓XCTAssertTrue( foo != nil)"), - Example("↓XCTAssertFalse(nil != foo"), - Example("↓XCTAssert(foo == nil, \"toto\")"), - ] + "↓XCTAssert( foo == nil)", + "↓XCTAssert(nil == foo", + "↓XCTAssertTrue( foo != nil)", + "↓XCTAssertFalse(nil != foo", + "↓XCTAssert(foo == nil, \"toto\")", + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityLabelForImageRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityLabelForImageRuleExamples.swift index 059ec1062c..43b8a12b1b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityLabelForImageRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityLabelForImageRuleExamples.swift @@ -2,54 +2,54 @@ // swiftlint:disable:next type_body_length internal struct AccessibilityLabelForImageRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ struct MyView: View { var body: some View { Image(decorative: "my-image") } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image("my-image", label: Text("Alt text for my image")) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image("my-image") .accessibility(hidden: true) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image("my-image") .accessibilityHidden(true) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image("my-image") .accessibility(label: Text("Alt text for my image")) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image("my-image") .accessibilityLabel(Text("Alt text for my image")) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image(uiImage: myUiImage) @@ -58,23 +58,23 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityHidden(true) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image(uiImage: myUiImage) .accessibilityLabel(Text("Alt text for my image")) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { SwiftUI.Image(uiImage: "my-image").resizable().accessibilityHidden(true) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { VStack { @@ -86,8 +86,8 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { VStack { @@ -99,8 +99,8 @@ internal struct AccessibilityLabelForImageRuleExamples { }.accessibilityElement() } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { VStack { @@ -112,8 +112,8 @@ internal struct AccessibilityLabelForImageRuleExamples { }.accessibilityHidden(true) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { HStack(spacing: 8) { @@ -125,8 +125,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .padding(16) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { HStack(spacing: 8) { @@ -139,8 +139,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityLabel(Text("Label for my image and text")) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Button(action: { doAction() }) { @@ -151,11 +151,11 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityLabel(Text("Label for my image")) } } - """), + """, // MARK: - SwiftSyntax Migration Regression Tests // These examples would have been false positives with the SourceKit implementation // but now correctly pass with the SwiftSyntax implementation - Example(""" + """ struct MyView: View { var body: some View { NavigationLink("Go to Details") { @@ -168,8 +168,8 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Button("Save Changes") { @@ -179,8 +179,8 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Button(action: performAction) { @@ -192,8 +192,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityLabel("Add to Favorites") } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { VStack { @@ -204,8 +204,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityLabel("Connected to WiFi") } } - """), - Example(""" + """, + """ struct MyView: View { let statusImage: UIImage var body: some View { @@ -217,8 +217,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityLabel("System is operational") } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { NavigationLink(destination: SettingsView()) { @@ -231,8 +231,8 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Button { @@ -244,8 +244,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityLabel(isEnabled ? "Hide content" : "Show content") } } - """), - Example(""" + """, + """ struct CustomCard: View { var body: some View { VStack { @@ -257,10 +257,10 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibilityLabel("Task completed successfully") } } - """), + """, // MARK: - Label icon closure exemptions // Images inside a Label's icon: closure are inherently labeled by the Label's text content. - Example(""" + """ struct MyView: View { var body: some View { Label { @@ -270,18 +270,18 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Label(content: { Text("Download") }, icon: { Image("custom-download-icon") }) } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ struct MyView: View { var body: some View { ↓Image("my-image") @@ -289,22 +289,22 @@ internal struct AccessibilityLabelForImageRuleExamples { .frame(width: 48, height: 48) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Image(uiImage: myUiImage) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓SwiftUI.Image(uiImage: "my-image").resizable().accessibilityHidden(false) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image(uiImage: myUiImage) @@ -314,8 +314,8 @@ internal struct AccessibilityLabelForImageRuleExamples { ↓Image("other image") } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Image(decorative: "image1") @@ -324,8 +324,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .accessibility(label: Text("a pretty picture")) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { VStack { @@ -336,8 +336,8 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { VStack { @@ -349,8 +349,8 @@ internal struct AccessibilityLabelForImageRuleExamples { }.accessibilityElement(children: .contain) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { VStack { @@ -362,8 +362,8 @@ internal struct AccessibilityLabelForImageRuleExamples { }.accessibilityHidden(false) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { HStack(spacing: 8) { @@ -375,8 +375,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .padding(16) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Button(action: { doAction() }) { @@ -386,18 +386,18 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Image(systemName: "circle.plus") } } - """), + """, // MARK: - SwiftSyntax Migration Detection Improvements // These violations would have been missed by the SourceKit implementation // but are now correctly detected by SwiftSyntax - Example(""" + """ struct StatusView: View { let statusIcon: UIImage var body: some View { @@ -408,8 +408,8 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct PreferencesView: View { var body: some View { VStack { @@ -420,8 +420,8 @@ internal struct AccessibilityLabelForImageRuleExamples { } } } - """), - Example(""" + """, + """ struct FaviconView: View { let favicon: UIImage? var body: some View { @@ -430,8 +430,8 @@ internal struct AccessibilityLabelForImageRuleExamples { .frame(width: 16, height: 16) } } - """), - Example(""" + """, + """ struct IconGrid: View { var body: some View { HStack { @@ -442,8 +442,8 @@ internal struct AccessibilityLabelForImageRuleExamples { }.accessibilityElement(children: .combine) } } - """), - Example(""" + """, + """ struct CardView: View { var body: some View { VStack { @@ -454,6 +454,6 @@ internal struct AccessibilityLabelForImageRuleExamples { }.accessibilityElement(children: .contain) } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityTraitForButtonRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityTraitForButtonRuleExamples.swift index 570411695d..232b8042b0 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityTraitForButtonRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/AccessibilityTraitForButtonRuleExamples.swift @@ -1,6 +1,6 @@ internal struct AccessibilityTraitForButtonRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ struct MyView: View { var body: some View { Button { @@ -10,15 +10,15 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Link("Open link", destination: myUrl) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -28,8 +28,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibility(addTraits: .isLink) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -39,8 +39,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -50,8 +50,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -61,8 +61,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibilityAddTraits([.isHeader, .isLink]) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -72,8 +72,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibility(addTraits: .isButton) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -83,8 +83,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibility(addTraits: .isButton) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -96,8 +96,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Label("Learn more", systemImage: "info.circle") @@ -107,8 +107,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibility(addTraits: .isButton) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { HStack { @@ -125,8 +125,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibility(addTraits: .isButton) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -136,8 +136,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibilityAddTraits(.isButton) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -147,8 +147,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibilityAddTraits(.isLink) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -158,8 +158,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { .accessibility(addTraits: [.isButton]) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { Text("Learn more") @@ -168,11 +168,11 @@ internal struct AccessibilityTraitForButtonRuleExamples { }) } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ struct MyView: View { var body: some View { ↓Text("Learn more") @@ -181,8 +181,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Text("Learn more") @@ -192,8 +192,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Text("Learn more") @@ -202,8 +202,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Text("Learn more") @@ -212,8 +212,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { }) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Label("Learn more", systemImage: "info.circle") @@ -222,8 +222,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓HStack { @@ -235,8 +235,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { } } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Text("Learn more") @@ -245,8 +245,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { }) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Text("Learn more") @@ -255,8 +255,8 @@ internal struct AccessibilityTraitForButtonRuleExamples { }) } } - """), - Example(""" + """, + """ struct MyView: View { var body: some View { ↓Text("Learn more") @@ -265,6 +265,6 @@ internal struct AccessibilityTraitForButtonRuleExamples { }) } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/ArrayInitRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/ArrayInitRule.swift index 28ac98b22d..8d7d702b3e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/ArrayInitRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/ArrayInitRule.swift @@ -40,45 +40,45 @@ struct ArrayInitRule: Rule, @unchecked Sendable { consider using the `typesafe_array_init` analyzer rule instead. """, kind: .lint, - nonTriggeringExamples: [ - Example("Array(foo)"), - Example("foo.map { $0.0 }"), - Example("foo.map { $1 }"), - Example("foo.map { $0() }"), - Example("foo.map { ((), $0) }"), - Example("foo.map { $0! }"), - Example("foo.map { $0! /* force unwrap */ }"), - Example("foo.something { RouteMapper.map($0) }"), - Example("foo.map { !$0 }"), - Example("foo.map { /* a comment */ !$0 }"), - ], - triggeringExamples: [ - Example("foo.↓map({ $0 })"), - Example("foo.↓map { $0 }"), - Example("foo.↓map { return $0 }"), - Example(""" + nonTriggeringExamples: #examples([ + "Array(foo)", + "foo.map { $0.0 }", + "foo.map { $1 }", + "foo.map { $0() }", + "foo.map { ((), $0) }", + "foo.map { $0! }", + "foo.map { $0! /* force unwrap */ }", + "foo.something { RouteMapper.map($0) }", + "foo.map { !$0 }", + "foo.map { /* a comment */ !$0 }", + ]), + triggeringExamples: #examples([ + "foo.↓map({ $0 })", + "foo.↓map { $0 }", + "foo.↓map { return $0 }", + """ foo.↓map { elem in elem } - """), - Example(""" + """, + """ foo.↓map { elem in return elem } - """), - Example(""" + """, + """ foo.↓map { (elem: String) in elem } - """), - Example(""" + """, + """ foo.↓map { elem -> String in elem } - """), - Example("foo.↓map { $0 /* a comment */ }"), - Example("foo.↓map { /* a comment */ $0 }"), - ] + """, + "foo.↓map { $0 /* a comment */ }", + "foo.↓map { /* a comment */ $0 }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/AsyncWithoutAwaitRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/AsyncWithoutAwaitRuleExamples.swift index 6a141ae586..0eb8125a6a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/AsyncWithoutAwaitRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/AsyncWithoutAwaitRuleExamples.swift @@ -226,13 +226,13 @@ internal struct AsyncWithoutAwaitRuleExamples { """), ] - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ func test() ↓async { perform() } - """), - Example(""" + """, + """ func test() { func baz() ↓async { qux() @@ -242,74 +242,74 @@ internal struct AsyncWithoutAwaitRuleExamples { qux() } } - """), - Example(""" + """, + """ func test() ↓async { func baz() async { await qux() } } - """), - Example(""" + """, + """ func test() ↓async { func foo() ↓async {} let bar = { await foo() } } - """), - Example(""" + """, + """ func test() ↓async { let bar = { func foo() ↓async {} } } - """), - Example(""" + """, + """ var test: Int { get ↓async throws { foo() } } - """), - Example(""" + """, + """ var test: Int { get ↓async throws { func foo() ↓async {} let bar = { await foo() } } } - """), - Example("init() ↓async {}"), - Example(""" + """, + "init() ↓async {}", + """ init() ↓async { func foo() ↓async {} } - """), - Example(""" + """, + """ subscript(row: Int) -> Double { get ↓async { 1.0 } } - """), - Example(""" + """, + """ func test() ↓async { for foo in bar {} } - """), - Example(""" + """, + """ func test() ↓async { while let foo = bar() {} } - """), - Example("let x: () ↓async -> Void = { }"), - Example("let x: () ↓async -> Void = { test() }"), - Example("let x: (() ↓async -> Void)? = nil"), - ] + """, + "let x: () ↓async -> Void = { }", + "let x: () ↓async -> Void = { test() }", + "let x: (() ↓async -> Void)? = nil", + ]) - static let corrections = [ - Example("func test() ↓async {}"): Example("func test() {}"), - Example("func test() ↓async throws {}"): Example("func test() throws {}"), - Example(""" + static let corrections = #examplesDictionary([ + "func test() ↓async {}": "func test() {}", + "func test() ↓async throws {}": "func test() throws {}", + """ func test() { func baz() ↓async { qux() @@ -319,8 +319,8 @@ internal struct AsyncWithoutAwaitRuleExamples { qux() } } - """): - Example(""" + """: + """ func test() { func baz() { qux() @@ -330,63 +330,63 @@ internal struct AsyncWithoutAwaitRuleExamples { qux() } } - """), - Example(""" + """, + """ func test() ↓async{ func baz() async { await qux() } } - """): - Example(""" + """: + """ func test() { func baz() async { await qux() } } - """), - Example(""" + """, + """ func test() ↓async { func foo() ↓async {} let bar = { await foo() } } - """): - Example(""" + """: + """ func test() { func foo() {} let bar = { await foo() } } - """), - Example(""" + """, + """ var test: Int { get ↓async throws { func foo() ↓async {} let bar = { await foo() } } } - """): - Example(""" + """: + """ var test: Int { get throws { func foo() {} let bar = { await foo() } } } - """), - Example("init() ↓async {}"): Example("init() {}"), - Example(""" + """, + "init() ↓async {}": "init() {}", + """ subscript(row: Int) -> Double { get ↓async { foo() } } - """): - Example(""" + """: + """ subscript(row: Int) -> Double { get { foo() } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/BalancedXCTestLifecycleRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/BalancedXCTestLifecycleRule.swift index 09b912d71a..bd581063a0 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/BalancedXCTestLifecycleRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/BalancedXCTestLifecycleRule.swift @@ -19,26 +19,26 @@ struct BalancedXCTestLifecycleRule: Rule { otherwise have any effects on subsequent tests, and to free up any instance variables. """, kind: .lint, - nonTriggeringExamples: [ - Example(#""" + nonTriggeringExamples: #examples([ + #""" final class FooTests: XCTestCase { override func setUp() {} override func tearDown() {} } - """#), - Example(#""" + """#, + #""" final class FooTests: XCTestCase { override func setUpWithError() throws {} override func tearDown() {} } - """#), - Example(#""" + """#, + #""" final class FooTests: XCTestCase { override func setUp() {} override func tearDownWithError() throws {} } - """#), - Example(#""" + """#, + #""" final class FooTests: XCTestCase { override func setUpWithError() throws {} override func tearDownWithError() throws {} @@ -47,39 +47,39 @@ struct BalancedXCTestLifecycleRule: Rule { override func setUpWithError() throws {} override func tearDownWithError() throws {} } - """#), - Example(#""" + """#, + #""" struct FooTests { override func setUp() {} } class BarTests { override func setUpWithError() throws {} } - """#), - Example(#""" + """#, + #""" final class FooTests: XCTestCase { override func setUpAlLExamples() {} } - """#), - Example(#""" + """#, + #""" final class FooTests: XCTestCase { class func setUp() {} class func tearDown() {} } - """#), - ], - triggeringExamples: [ - Example(#""" + """#, + ]), + triggeringExamples: #examples([ + #""" final class ↓FooTests: XCTestCase { override func setUp() {} } - """#), - Example(#""" + """#, + #""" final class ↓FooTests: XCTestCase { override func setUpWithError() throws {} } - """#), - Example(#""" + """#, + #""" final class FooTests: XCTestCase { override func setUp() {} override func tearDownWithError() throws {} @@ -87,23 +87,23 @@ struct BalancedXCTestLifecycleRule: Rule { final class ↓BarTests: XCTestCase { override func setUpWithError() throws {} } - """#), - Example(#""" + """#, + #""" final class ↓FooTests: XCTestCase { class func tearDown() {} } - """#), - Example(#""" + """#, + #""" final class ↓FooTests: XCTestCase { override func tearDown() {} } - """#), - Example(#""" + """#, + #""" final class ↓FooTests: XCTestCase { override func tearDownWithError() throws {} } - """#), - Example(#""" + """#, + #""" final class FooTests: XCTestCase { override func setUp() {} override func tearDownWithError() throws {} @@ -111,8 +111,8 @@ struct BalancedXCTestLifecycleRule: Rule { final class ↓BarTests: XCTestCase { override func tearDownWithError() throws {} } - """#), - ] + """#, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/BlanketDisableCommandRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/BlanketDisableCommandRule.swift index 9c45c00e0f..e9a80ebfdd 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/BlanketDisableCommandRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/BlanketDisableCommandRule.swift @@ -34,36 +34,36 @@ struct BlanketDisableCommandRule: Rule, SourceKitFreeRule { ``` """, kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ // swiftlint:disable unused_import // swiftlint:enable unused_import - """), - Example(""" + """, + """ // swiftlint:disable unused_import unused_declaration // swiftlint:enable unused_import // swiftlint:enable unused_declaration - """), - Example("// swiftlint:disable:this unused_import"), - Example("// swiftlint:disable:next unused_import"), - Example("// swiftlint:disable:previous unused_import"), - ], - triggeringExamples: [ - Example("// swiftlint:disable ↓unused_import"), - Example(""" + """, + "// swiftlint:disable:this unused_import", + "// swiftlint:disable:next unused_import", + "// swiftlint:disable:previous unused_import", + ]), + triggeringExamples: #examples([ + "// swiftlint:disable ↓unused_import", + """ // swiftlint:disable unused_import ↓unused_declaration // swiftlint:enable unused_import - """), - Example(""" + """, + """ // swiftlint:disable unused_import // swiftlint:disable ↓unused_import // swiftlint:enable unused_import - """), - Example(""" + """, + """ // swiftlint:enable ↓unused_import - """), - Example("// swiftlint:disable all"), - ].skipWrappingInCommentTests().skipDisableCommandTests() + """, + "// swiftlint:disable all", + ]).skipWrappingInCommentTests().skipDisableCommandTests() ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/CaptureVariableRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/CaptureVariableRule.swift index de2699a925..709aee3775 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/CaptureVariableRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/CaptureVariableRule.swift @@ -15,8 +15,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { description: "Non-constant variables should not be listed in a closure's capture list" + " to avoid confusion about closures capturing variables at creation time", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class C { let i: Int init(_ i: Int) { self.i = i } @@ -30,8 +30,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { } closure() - """), - Example(""" + """, + """ let iGlobal: Int = 0 class C { @@ -49,8 +49,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { func test(_ completionHandler: @escaping (Int) -> Void) { } } - """), - Example(""" + """, + """ var j: Int! j = 0 @@ -61,8 +61,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { closure() j = 1 closure() - """), - Example(""" + """, + """ lazy var j: Int = { 0 }() let closure: () -> Void = { [j] in @@ -72,10 +72,10 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { closure() j = 1 closure() - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ var j: Int = 0 let closure: () -> Void = { [j] in @@ -85,8 +85,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { closure() j = 1 closure() - """), - Example(""" + """, + """ class C { let i: Int init(_ i: Int) { self.i = i } @@ -100,8 +100,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { closure() c = C(1) closure() - """), - Example(""" + """, + """ var iGlobal: Int = 0 class C { @@ -114,8 +114,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { func test(_ completionHandler: @escaping (Int) -> Void) { } } - """), - Example(""" + """, + """ class C { static var iStatic: Int = 0 @@ -133,8 +133,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { } C.callTest() - """), - Example(""" + """, + """ class C { var iInstance: Int = 0 @@ -147,8 +147,8 @@ struct CaptureVariableRule: AnalyzerRule, CollectingRule { func test(_ completionHandler: @escaping (Int) -> Void) { } } - """), - ], + """, + ]), requiresFileOnDisk: true ) diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/ClassDelegateProtocolRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/ClassDelegateProtocolRule.swift index e2dc375a36..19b8e78496 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/ClassDelegateProtocolRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/ClassDelegateProtocolRule.swift @@ -27,33 +27,33 @@ struct ClassDelegateProtocolRule: Rule { ``` """, kind: .lint, - nonTriggeringExamples: [ - Example("protocol FooDelegate: class {}"), - Example("protocol FooDelegate: class, BarDelegate {}"), - Example("protocol Foo {}"), - Example("class FooDelegate {}"), - Example("@objc protocol FooDelegate {}"), - Example("@objc(MyFooDelegate)\n protocol FooDelegate {}"), - Example("protocol FooDelegate: BarDelegate {}"), - Example("protocol FooDelegate: AnyObject {}"), - Example("protocol FooDelegate: AnyObject & Foo {}"), - Example("protocol FooDelegate: Foo, AnyObject & Foo {}"), - Example("protocol FooDelegate: Foo & AnyObject & Bar {}"), - Example("protocol FooDelegate: NSObjectProtocol {}"), - Example("protocol FooDelegate where Self: BarDelegate {}"), - Example("protocol FooDelegate where Self: BarDelegate & Bar {}"), - Example("protocol FooDelegate where Self: Foo & BarDelegate & Bar {}"), - Example("protocol FooDelegate where Self: AnyObject {}"), - Example("protocol FooDelegate where Self: NSObjectProtocol {}"), - Example("protocol FooDelegate: Actor {}"), - ], - triggeringExamples: [ - Example("↓protocol FooDelegate {}"), - Example("↓protocol FooDelegate: Bar {}"), - Example("↓protocol FooDelegate: Foo & Bar {}"), - Example("↓protocol FooDelegate where Self: StringProtocol {}"), - Example("↓protocol FooDelegate where Self: A & B {}"), - ] + nonTriggeringExamples: #examples([ + "protocol FooDelegate: class {}", + "protocol FooDelegate: class, BarDelegate {}", + "protocol Foo {}", + "class FooDelegate {}", + "@objc protocol FooDelegate {}", + "@objc(MyFooDelegate)\n protocol FooDelegate {}", + "protocol FooDelegate: BarDelegate {}", + "protocol FooDelegate: AnyObject {}", + "protocol FooDelegate: AnyObject & Foo {}", + "protocol FooDelegate: Foo, AnyObject & Foo {}", + "protocol FooDelegate: Foo & AnyObject & Bar {}", + "protocol FooDelegate: NSObjectProtocol {}", + "protocol FooDelegate where Self: BarDelegate {}", + "protocol FooDelegate where Self: BarDelegate & Bar {}", + "protocol FooDelegate where Self: Foo & BarDelegate & Bar {}", + "protocol FooDelegate where Self: AnyObject {}", + "protocol FooDelegate where Self: NSObjectProtocol {}", + "protocol FooDelegate: Actor {}", + ]), + triggeringExamples: #examples([ + "↓protocol FooDelegate {}", + "↓protocol FooDelegate: Bar {}", + "↓protocol FooDelegate: Foo & Bar {}", + "↓protocol FooDelegate where Self: StringProtocol {}", + "↓protocol FooDelegate where Self: A & B {}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/CommentSpacingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/CommentSpacingRule.swift index d28237ff97..4c9500e5ca 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/CommentSpacingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/CommentSpacingRule.swift @@ -10,111 +10,111 @@ struct CommentSpacingRule: SourceKitFreeRule, SubstitutionCorrectableRule { name: "Comment Spacing", description: "Prefer at least one space after slashes for comments", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ // This is a comment - """), - Example(""" + """, + """ /// Triple slash comment - """), - Example(""" + """, + """ // Multiline double-slash // comment - """), - Example(""" + """, + """ /// Multiline triple-slash /// comment - """), - Example(""" + """, + """ /// Multiline triple-slash /// - This is indented - """), - Example(""" + """, + """ // - MARK: Mark comment - """), - Example(""" + """, + """ //: Swift Playground prose section - """), - Example(""" + """, + """ /////////////////////////////////////////////// // Comment with some lines of slashes boxing it /////////////////////////////////////////////// - """), - Example(""" + """, + """ //:#localized(key: "SwiftPlaygroundLocalizedProse") - """), - Example(""" + """, + """ /* Asterisk comment */ - """), - Example(""" + """, + """ /* Multiline asterisk comment */ - """), - Example(""" + """, + """ /*: Multiline Swift Playground prose section */ - """), - Example(""" + """, + """ /*#-editable-code Swift Playground editable area*/default/*#-end-editable-code*/ - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ //↓Something - """), - Example(""" + """, + """ //↓MARK - """), - Example(""" + """, + """ //↓👨‍👨‍👦‍👦Something - """), - Example(""" + """, + """ func a() { //↓This needs refactoring print("Something") } //↓We should improve above function - """), - Example(""" + """, + """ ///↓This is a comment - """), - Example(""" + """, + """ /// Multiline triple-slash ///↓This line is incorrect, though - """), - Example(""" + """, + """ //↓- MARK: Mark comment - """), - Example(""" + """, + """ //:↓Swift Playground prose section - """), - ], - corrections: [ - Example("//↓Something"): Example("// Something"), - Example("//↓- MARK: Mark comment"): Example("// - MARK: Mark comment"), - Example(""" + """, + ]), + corrections: #examplesDictionary([ + "//↓Something": "// Something", + "//↓- MARK: Mark comment": "// - MARK: Mark comment", + """ /// Multiline triple-slash ///↓This line is incorrect, though - """): Example(""" + """: """ /// Multiline triple-slash /// This line is incorrect, though - """), - Example(""" + """, + """ func a() { //↓This needs refactoring print("Something") } //↓We should improve above function - """): Example(""" + """: """ func a() { // This needs refactoring print("Something") } // We should improve above function - """), - ] + """, + ]) ) func violationRanges(in file: SwiftLintFile) -> [NSRange] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/CompilerProtocolInitRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/CompilerProtocolInitRule.swift index b74f089317..7052bca61f 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/CompilerProtocolInitRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/CompilerProtocolInitRule.swift @@ -10,16 +10,16 @@ struct CompilerProtocolInitRule: Rule { description: "The initializers declared in compiler protocols such as `ExpressibleByArrayLiteral` " + "shouldn't be called directly.", kind: .lint, - nonTriggeringExamples: [ - Example("let set: Set = [1, 2]"), - Example("let set = Set(array)"), - ], - triggeringExamples: [ - Example("let set = ↓Set(arrayLiteral: 1, 2)"), - Example("let set = ↓Set (arrayLiteral: 1, 2)"), - Example("let set = ↓Set.init(arrayLiteral: 1, 2)"), - Example("let set = ↓Set.init(arrayLiteral : 1, 2)"), - ] + nonTriggeringExamples: #examples([ + "let set: Set = [1, 2]", + "let set = Set(array)", + ]), + triggeringExamples: #examples([ + "let set = ↓Set(arrayLiteral: 1, 2)", + "let set = ↓Set (arrayLiteral: 1, 2)", + "let set = ↓Set.init(arrayLiteral: 1, 2)", + "let set = ↓Set.init(arrayLiteral : 1, 2)", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/DeploymentTargetRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/DeploymentTargetRuleExamples.swift index 3d85368f6f..e26e239881 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/DeploymentTargetRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/DeploymentTargetRuleExamples.swift @@ -1,37 +1,37 @@ internal enum DeploymentTargetRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example("@available(iOS 12.0, *)\nclass A {}"), - Example("@available(iOSApplicationExtension 13.0, *)\nclass A {}"), - Example("@available(watchOS 4.0, *)\nclass A {}"), - Example("@available(watchOSApplicationExtension 4.0, *)\nclass A {}"), - Example("@available(swift 3.0.2)\nclass A {}"), - Example("class A {}"), - Example("if #available(iOS 10.0, *) {}"), - Example("if #available(iOS 10, *) {}"), - Example("guard #available(iOS 12.0, *) else { return }"), - Example("#if #unavailable(iOS 15.0) {}"), - Example("#guard #unavailable(iOS 15.0) {} else { return }"), - ] + static let nonTriggeringExamples: [Example] = #examples([ + "@available(iOS 12.0, *)\nclass A {}", + "@available(iOSApplicationExtension 13.0, *)\nclass A {}", + "@available(watchOS 4.0, *)\nclass A {}", + "@available(watchOSApplicationExtension 4.0, *)\nclass A {}", + "@available(swift 3.0.2)\nclass A {}", + "class A {}", + "if #available(iOS 10.0, *) {}", + "if #available(iOS 10, *) {}", + "guard #available(iOS 12.0, *) else { return }", + "#if #unavailable(iOS 15.0) {}", + "#guard #unavailable(iOS 15.0) {} else { return }", + ]) - static let triggeringExamples: [Example] = [ - Example("↓@available(iOS 6.0, *)\nclass A {}"), - Example("↓@available(iOSApplicationExtension 6.0, *)\nclass A {}"), - Example("↓@available(iOS 7.0, *)\nclass A {}"), - Example("↓@available(iOS 6, *)\nclass A {}"), - Example("↓@available(iOS 6.0, macOS 10.12, *)\n class A {}"), - Example("↓@available(macOS 10.12, iOS 6.0, *)\n class A {}"), - Example("↓@available(macOS 10.7, *)\nclass A {}"), - Example("↓@available(macOSApplicationExtension 10.7, *)\nclass A {}"), - Example("↓@available(OSX 10.7, *)\nclass A {}"), - Example("↓@available(watchOS 0.9, *)\nclass A {}"), - Example("↓@available(watchOSApplicationExtension 0.9, *)\nclass A {}"), - Example("↓@available(tvOS 8, *)\nclass A {}"), - Example("↓@available(tvOSApplicationExtension 8, *)\nclass A {}"), - Example("if ↓#available(iOS 6.0, *) {}"), - Example("if ↓#available(iOS 6, *) {}"), - Example("guard ↓#available(iOS 6.0, *) else { return }"), - Example("if ↓#unavailable(iOS 7.0) {}"), - Example("if ↓#unavailable(iOS 6.9) {}"), - Example("guard ↓#unavailable(iOS 7.0) {} else { return }"), - ] + static let triggeringExamples: [Example] = #examples([ + "↓@available(iOS 6.0, *)\nclass A {}", + "↓@available(iOSApplicationExtension 6.0, *)\nclass A {}", + "↓@available(iOS 7.0, *)\nclass A {}", + "↓@available(iOS 6, *)\nclass A {}", + "↓@available(iOS 6.0, macOS 10.12, *)\n class A {}", + "↓@available(macOS 10.12, iOS 6.0, *)\n class A {}", + "↓@available(macOS 10.7, *)\nclass A {}", + "↓@available(macOSApplicationExtension 10.7, *)\nclass A {}", + "↓@available(OSX 10.7, *)\nclass A {}", + "↓@available(watchOS 0.9, *)\nclass A {}", + "↓@available(watchOSApplicationExtension 0.9, *)\nclass A {}", + "↓@available(tvOS 8, *)\nclass A {}", + "↓@available(tvOSApplicationExtension 8, *)\nclass A {}", + "if ↓#available(iOS 6.0, *) {}", + "if ↓#available(iOS 6, *) {}", + "guard ↓#available(iOS 6.0, *) else { return }", + "if ↓#unavailable(iOS 7.0) {}", + "if ↓#unavailable(iOS 6.9) {}", + "guard ↓#unavailable(iOS 7.0) {} else { return }", + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/DiscardedNotificationCenterObserverRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/DiscardedNotificationCenterObserverRule.swift index d6a8db978b..4e583f3663 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/DiscardedNotificationCenterObserverRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/DiscardedNotificationCenterObserverRule.swift @@ -10,62 +10,62 @@ struct DiscardedNotificationCenterObserverRule: Rule { description: "When registering for a notification using a block, the opaque observer that is " + "returned should be stored so it can be removed later", kind: .lint, - nonTriggeringExamples: [ - Example("let foo = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }"), - Example(""" + nonTriggeringExamples: #examples([ + "let foo = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }", + """ let foo = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }) - """), - Example(""" + """, + """ func foo() -> Any { return nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }) } - """), - Example(""" + """, + """ func foo() -> Any { nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }) } - """), - Example(""" + """, + """ var obs: [Any?] = [] obs.append(nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })) - """), - Example(""" + """, + """ var obs: [String: Any?] = [] obs["foo"] = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }) - """), - Example(""" + """, + """ var obs: [Any?] = [] obs.append(nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })) - """), - Example(""" + """, + """ func foo(_ notify: Any) { obs.append(notify) } foo(nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })) - """), - Example(""" + """, + """ var obs: [NSObjectProtocol] = [ nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }), nc.addObserver(forName: .CKAccountChanged, object: nil, queue: nil, using: { }) ] - """), - Example(""" + """, + """ names.map { self.notificationCenter.addObserver(forName: $0, object: object, queue: queue, using: block) } - """), - Example(""" + """, + """ f { return nc.addObserver(forName: $0, object: object, queue: queue, using: block) } - """), - ], - triggeringExamples: [ - Example("↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }"), - Example("_ = ↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }"), - Example("↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }", + "_ = ↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }", + "↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })", + """ @discardableResult func foo() -> Any { return ↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }) } - """), - Example(""" + """, + """ class C { var i: Int { set { ↓notificationCenter.addObserver(forName: $0, object: object, queue: queue, using: block) } @@ -75,21 +75,21 @@ struct DiscardedNotificationCenterObserverRule: Rule { } } } - """), - Example(""" + """, + """ f { ↓nc.addObserver(forName: $0, object: object, queue: queue) {} return 2 } - """), - Example(""" + """, + """ func foo() -> Any { if cond { ↓nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { }) } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/DiscouragedDirectInitRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/DiscouragedDirectInitRule.swift index 4ae0db9ac8..a00d44f34c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/DiscouragedDirectInitRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/DiscouragedDirectInitRule.swift @@ -9,31 +9,31 @@ struct DiscouragedDirectInitRule: Rule { name: "Discouraged Direct Initialization", description: "Discouraged direct initialization of types that can be harmful", kind: .lint, - nonTriggeringExamples: [ - Example("let foo = UIDevice.current"), - Example("let foo = Bundle.main"), - Example("let foo = Bundle(path: \"bar\")"), - Example("let foo = Bundle(identifier: \"bar\")"), - Example("let foo = Bundle.init(path: \"bar\")"), - Example("let foo = Bundle.init(identifier: \"bar\")"), - Example("let foo = NSError(domain: \"bar\", code: 0)"), - Example("let foo = NSError.init(domain: \"bar\", code: 0)"), - Example("func testNSError()"), - ], - triggeringExamples: [ - Example("↓UIDevice()"), - Example("↓Bundle()"), - Example("let foo = ↓UIDevice()"), - Example("let foo = ↓Bundle()"), - Example("let foo = ↓NSError()"), - Example("let foo = bar(bundle: ↓Bundle(), device: ↓UIDevice(), error: ↓NSError())"), - Example("↓UIDevice.init()"), - Example("↓Bundle.init()"), - Example("↓NSError.init()"), - Example("let foo = ↓UIDevice.init()"), - Example("let foo = ↓Bundle.init()"), - Example("let foo = bar(bundle: ↓Bundle.init(), device: ↓UIDevice.init(), error: ↓NSError.init())"), - ] + nonTriggeringExamples: #examples([ + "let foo = UIDevice.current", + "let foo = Bundle.main", + "let foo = Bundle(path: \"bar\")", + "let foo = Bundle(identifier: \"bar\")", + "let foo = Bundle.init(path: \"bar\")", + "let foo = Bundle.init(identifier: \"bar\")", + "let foo = NSError(domain: \"bar\", code: 0)", + "let foo = NSError.init(domain: \"bar\", code: 0)", + "func testNSError()", + ]), + triggeringExamples: #examples([ + "↓UIDevice()", + "↓Bundle()", + "let foo = ↓UIDevice()", + "let foo = ↓Bundle()", + "let foo = ↓NSError()", + "let foo = bar(bundle: ↓Bundle(), device: ↓UIDevice(), error: ↓NSError())", + "↓UIDevice.init()", + "↓Bundle.init()", + "↓NSError.init()", + "let foo = ↓UIDevice.init()", + "let foo = ↓Bundle.init()", + "let foo = bar(bundle: ↓Bundle.init(), device: ↓UIDevice.init(), error: ↓NSError.init())", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateConditionsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateConditionsRule.swift index 71d08d14a8..218bd8b0f7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateConditionsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateConditionsRule.swift @@ -9,73 +9,73 @@ struct DuplicateConditionsRule: Rule { name: "Duplicate Conditions", description: "Duplicate sets of conditions in the same branch instruction should be avoided", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ if x < 5 { foo() } else if y == "s" { bar() } - """), - Example(""" + """, + """ if x < 5 { foo() } if x < 5 { bar() } - """), - Example(""" + """, + """ if x < 5, y == "s" { foo() } else if x < 5 { bar() } - """), - Example(""" + """, + """ switch x { case \"a\": foo() bar() } - """), - Example(""" + """, + """ switch x { case \"a\" where y == "s": foo() case \"a\" where y == "t": bar() } - """), - Example(""" + """, + """ if let x = maybeAbc { foo() } else if let x = maybePqr { bar() } - """), - Example(""" + """, + """ if let x = maybeAbc, let z = x.maybeY { foo() } else if let x = maybePqr, let z = x.maybeY { bar() } - """), - Example(""" + """, + """ if case .p = x { foo() } else if case .q = x { bar() } - """), - Example(""" + """, + """ if true { if true { foo() } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ if ↓x < 5 { foo() } else if y == "s" { @@ -83,8 +83,8 @@ struct DuplicateConditionsRule: Rule { } else if ↓x < 5 { baz() } - """), - Example(""" + """, + """ if z { if ↓x < 5 { foo() @@ -94,8 +94,8 @@ struct DuplicateConditionsRule: Rule { baz() } } - """), - Example(""" + """, + """ if ↓x < 5, y == "s" { foo() } else if x < 10 { @@ -103,57 +103,57 @@ struct DuplicateConditionsRule: Rule { } else if ↓y == "s", x < 5 { baz() } - """), - Example(""" + """, + """ switch x { case ↓\"a\", \"b\": foo() case \"c\", ↓\"a\": bar() } - """), - Example(""" + """, + """ switch x { case ↓\"a\" where y == "s": foo() case ↓\"a\" where y == "s": bar() } - """), - Example(""" + """, + """ if ↓let xyz = maybeXyz { foo() } else if ↓let xyz = maybeXyz { bar() } - """), - Example(""" + """, + """ if ↓let x = maybeAbc, let z = x.maybeY { foo() } else if ↓let x = maybeAbc, let z = x.maybeY { bar() } - """), - Example(""" + """, + """ if ↓#available(macOS 10.15, *) { foo() } else if ↓#available(macOS 10.15, *) { bar() } - """), - Example(""" + """, + """ if ↓case .p = x { foo() } else if ↓case .p = x { bar() } - """), - Example(""" + """, + """ if ↓x < 5 {} else if ↓x < 5 {} else if ↓x < 5 {} - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateEnumCasesRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateEnumCasesRule.swift index 616db6f70c..61fb6edeba 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateEnumCasesRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicateEnumCasesRule.swift @@ -9,22 +9,22 @@ struct DuplicateEnumCasesRule: Rule { name: "Duplicate Enum Cases", description: "Enum shouldn't contain multiple cases with the same name", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum PictureImport { case addImage(image: UIImage) case addData(data: Data) } - """), - Example(""" + """, + """ enum A { case add(image: UIImage) } enum B { case add(image: UIImage) } - """), - Example(""" + """, + """ enum Tag: String { #if CONFIG_A case value = "CONFIG_A" @@ -34,8 +34,8 @@ struct DuplicateEnumCasesRule: Rule { case value = "CONFIG_DEFAULT" #endif } - """), - Example(""" + """, + """ enum Target { #if os(iOS) case file @@ -43,17 +43,17 @@ struct DuplicateEnumCasesRule: Rule { case file(URL) #endif } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ enum PictureImport { case ↓add(image: UIImage) case addURL(url: URL) case ↓add(data: Data) } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicatedKeyInDictionaryLiteralRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicatedKeyInDictionaryLiteralRule.swift index 9fcdc322ba..3c5011756a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicatedKeyInDictionaryLiteralRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/DuplicatedKeyInDictionaryLiteralRule.swift @@ -9,54 +9,54 @@ struct DuplicatedKeyInDictionaryLiteralRule: Rule { name: "Duplicated Key in Dictionary Literal", description: "Dictionary literals with duplicated keys will crash at runtime", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ [ 1: "1", 2: "2" ] - """), - Example(""" + """, + """ [ "1": 1, "2": 2 ] - """), - Example(""" + """, + """ [ foo: "1", bar: "2" ] - """), - Example(""" + """, + """ [ UUID(): "1", UUID(): "2" ] - """), - Example(""" + """, + """ [ #line: "1", #line: "2" ] - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ [ 1: "1", 2: "2", ↓1: "one" ] - """), - Example(""" + """, + """ [ "1": 1, "2": 2, ↓"2": 2 ] - """), - Example(""" + """, + """ [ foo: "1", bar: "2", @@ -64,8 +64,8 @@ struct DuplicatedKeyInDictionaryLiteralRule: Rule { ↓foo: "4", zaz: "5" ] - """), - Example(""" + """, + """ [ .one: "1", .two: "2", @@ -74,8 +74,8 @@ struct DuplicatedKeyInDictionaryLiteralRule: Rule { .four: "4", .five: "5" ] - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/DynamicInlineRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/DynamicInlineRule.swift index 232cb208cb..69cccab2bc 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/DynamicInlineRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/DynamicInlineRule.swift @@ -9,18 +9,18 @@ struct DynamicInlineRule: Rule { name: "Dynamic Inline", description: "Avoid using 'dynamic' and '@inline(__always)' together", kind: .lint, - nonTriggeringExamples: [ - Example("class C {\ndynamic func f() {}}"), - Example("class C {\n@inline(__always) func f() {}}"), - Example("class C {\n@inline(never) dynamic func f() {}}"), - ], - triggeringExamples: [ - Example("class C {\n@inline(__always) dynamic ↓func f() {}\n}"), - Example("class C {\n@inline(__always) public dynamic ↓func f() {}\n}"), - Example("class C {\n@inline(__always) dynamic internal ↓func f() {}\n}"), - Example("class C {\n@inline(__always)\ndynamic ↓func f() {}\n}"), - Example("class C {\n@inline(__always)\ndynamic\n↓func f() {}\n}"), - ] + nonTriggeringExamples: #examples([ + "class C {\ndynamic func f() {}}", + "class C {\n@inline(__always) func f() {}}", + "class C {\n@inline(never) dynamic func f() {}}", + ]), + triggeringExamples: #examples([ + "class C {\n@inline(__always) dynamic ↓func f() {}\n}", + "class C {\n@inline(__always) public dynamic ↓func f() {}\n}", + "class C {\n@inline(__always) dynamic internal ↓func f() {}\n}", + "class C {\n@inline(__always)\ndynamic ↓func f() {}\n}", + "class C {\n@inline(__always)\ndynamic\n↓func f() {}\n}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/EmptyXCTestMethodRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/EmptyXCTestMethodRuleExamples.swift index ee5fcdaaec..4f88b30a67 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/EmptyXCTestMethodRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/EmptyXCTestMethodRuleExamples.swift @@ -101,10 +101,10 @@ internal struct EmptyXCTestMethodRuleExamples { """, excludeFromDocumentation: true), ] - static let triggeringExamples = [ + static let triggeringExamples = #examples([ // XCTestCase class with empty methods - Example(""" + """ class TotoTests: XCTestCase { override ↓func setUp() { } @@ -127,9 +127,9 @@ internal struct EmptyXCTestMethodRuleExamples { func helperFunction() { } } - """), + """, - Example(""" + """ class TotoTests: XCTestCase { override ↓func setUp() {} @@ -139,11 +139,11 @@ internal struct EmptyXCTestMethodRuleExamples { func helperFunction() {} } - """), + """, // XCTestCase class with comments (and blank lines) - Example(""" + """ class TotoTests: XCTestCase { override ↓func setUp() { // comment... @@ -175,11 +175,11 @@ internal struct EmptyXCTestMethodRuleExamples { func helperFunction() { } } - """), + """, // Two XCTestCase classes on the same file - Example(""" + """ class FooTests: XCTestCase { override ↓func setUp() {} } @@ -187,6 +187,6 @@ internal struct EmptyXCTestMethodRuleExamples { class BarTests: XCTestCase { ↓func testFoo() {} } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/ExpiringTodoRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/ExpiringTodoRule.swift index 9cfe264a79..6f646683d3 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/ExpiringTodoRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/ExpiringTodoRule.swift @@ -26,24 +26,24 @@ struct ExpiringTodoRule: Rule { name: "Expiring Todo", description: "TODOs and FIXMEs should be resolved prior to their expiry date.", kind: .lint, - nonTriggeringExamples: [ - Example("// notaTODO:"), - Example("// notaFIXME:"), - Example("// TODO: [12/31/9999]"), - Example("// TODO(note)"), - Example("// FIXME(note)"), - Example("/* FIXME: */"), - Example("/* TODO: */"), - Example("/** FIXME: */"), - Example("/** TODO: */"), - ], - triggeringExamples: [ - Example("// TODO: [↓10/14/2019]"), - Example("// FIXME: [↓10/14/2019]"), - Example("// FIXME: [↓1/14/2019]"), - Example("// FIXME: [↓10/14/2019]"), - Example("// TODO: [↓9999/14/10]"), - ].skipWrappingInCommentTests() + nonTriggeringExamples: #examples([ + "// notaTODO:", + "// notaFIXME:", + "// TODO: [12/31/9999]", + "// TODO(note)", + "// FIXME(note)", + "/* FIXME: */", + "/* TODO: */", + "/** FIXME: */", + "/** TODO: */", + ]), + triggeringExamples: #examples([ + "// TODO: [↓10/14/2019]", + "// FIXME: [↓10/14/2019]", + "// FIXME: [↓1/14/2019]", + "// FIXME: [↓10/14/2019]", + "// TODO: [↓9999/14/10]", + ]).skipWrappingInCommentTests() ) var configuration = ExpiringTodoConfiguration() diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/IBInspectableInExtensionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/IBInspectableInExtensionRule.swift index 759e254175..0068aa461d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/IBInspectableInExtensionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/IBInspectableInExtensionRule.swift @@ -9,20 +9,20 @@ struct IBInspectableInExtensionRule: Rule { name: "IBInspectable in Extension", description: "Extensions shouldn't add @IBInspectable properties", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class Foo { @IBInspectable private var x: Int } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ extension Foo { ↓@IBInspectable private var x: Int } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/IdenticalOperandsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/IdenticalOperandsRule.swift index b3497155e3..3b115f0173 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/IdenticalOperandsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/IdenticalOperandsRule.swift @@ -12,62 +12,62 @@ struct IdenticalOperandsRule: Rule { description: "Comparing two identical operands is likely a mistake", kind: .lint, nonTriggeringExamples: operators.flatMap { operation in - [ - Example("1 \(operation) 2"), - Example("foo \(operation) bar"), - Example("prefixedFoo \(operation) foo"), - Example("foo.aProperty \(operation) foo.anotherProperty"), - Example("self.aProperty \(operation) self.anotherProperty"), - Example("\"1 \(operation) 1\""), - Example("self.aProperty \(operation) aProperty"), - Example("lhs.aProperty \(operation) rhs.aProperty"), - Example("lhs.identifier \(operation) rhs.identifier"), - Example("i \(operation) index"), - Example("$0 \(operation) 0"), - Example("keyValues?.count ?? 0 \(operation) 0"), - Example("string \(operation) string.lowercased()"), - Example(""" + #examples([ + "1 \(operation) 2", + "foo \(operation) bar", + "prefixedFoo \(operation) foo", + "foo.aProperty \(operation) foo.anotherProperty", + "self.aProperty \(operation) self.anotherProperty", + "\"1 \(operation) 1\"", + "self.aProperty \(operation) aProperty", + "lhs.aProperty \(operation) rhs.aProperty", + "lhs.identifier \(operation) rhs.identifier", + "i \(operation) index", + "$0 \(operation) 0", + "keyValues?.count ?? 0 \(operation) 0", + "string \(operation) string.lowercased()", + """ let num: Int? = 0 _ = num != nil && num \(operation) num?.byteSwapped - """), - Example("num \(operation) num!.byteSwapped"), - Example("1 + 1 \(operation) 1 + 2"), - Example("f( i : 2) \(operation) f (i: 3 )"), - ] - } + [ - Example("func evaluate(_ mode: CommandMode) -> Result>>"), - Example("let array = Array>()"), - Example("guard Set(identifiers).count != identifiers.count else { return }"), - Example(#"expect("foo") == "foo""#), - Example("type(of: model).cachePrefix == cachePrefix"), - Example("histogram[156].0 == 0x003B8D96 && histogram[156].1 == 1"), - Example(#"[Wrapper(type: .three), Wrapper(type: .one)].sorted { "\($0.type)" > "\($1.type)"}"#), - Example(#"array.sorted { "\($0)" < "\($1)" }"#), - ], + """, + "num \(operation) num!.byteSwapped", + "1 + 1 \(operation) 1 + 2", + "f( i : 2) \(operation) f (i: 3 )", + ]) + } + #examples([ + "func evaluate(_ mode: CommandMode) -> Result>>", + "let array = Array>()", + "guard Set(identifiers).count != identifiers.count else { return }", + #"expect("foo") == "foo""#, + "type(of: model).cachePrefix == cachePrefix", + "histogram[156].0 == 0x003B8D96 && histogram[156].1 == 1", + #"[Wrapper(type: .three), Wrapper(type: .one)].sorted { "\($0.type)" > "\($1.type)"}"#, + #"array.sorted { "\($0)" < "\($1)" }"#, + ]), triggeringExamples: operators.flatMap { operation in - [ - Example("↓1 \(operation) 1"), - Example("↓foo \(operation) foo"), - Example("↓foo.aProperty \(operation) foo.aProperty"), - Example("↓self.aProperty \(operation) self.aProperty"), - Example("↓$0 \(operation) $0"), - Example("↓a?.b \(operation) a?.b"), - Example("if (↓elem \(operation) elem) {}"), - Example("XCTAssertTrue(↓s3 \(operation) s3)"), - Example("if let tab = tabManager.selectedTab, ↓tab.webView \(operation) tab.webView"), - Example("↓1 + 1 \(operation) 1 + 1"), - Example(" ↓f( i : 2) \(operation) f (i: \n 2 )"), - ] - } + [ - Example(""" + #examples([ + "↓1 \(operation) 1", + "↓foo \(operation) foo", + "↓foo.aProperty \(operation) foo.aProperty", + "↓self.aProperty \(operation) self.aProperty", + "↓$0 \(operation) $0", + "↓a?.b \(operation) a?.b", + "if (↓elem \(operation) elem) {}", + "XCTAssertTrue(↓s3 \(operation) s3)", + "if let tab = tabManager.selectedTab, ↓tab.webView \(operation) tab.webView", + "↓1 + 1 \(operation) 1 + 1", + " ↓f( i : 2) \(operation) f (i: \n 2 )", + ]) + } + #examples([ + """ return ↓lhs.foo == lhs.foo && lhs.bar == rhs.bar - """), - Example(""" + """, + """ return lhs.foo == rhs.foo && ↓lhs.bar == lhs.bar - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/IncompatibleConcurrencyAnnotationRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/IncompatibleConcurrencyAnnotationRuleExamples.swift index d51097d159..9503dbd21e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/IncompatibleConcurrencyAnnotationRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/IncompatibleConcurrencyAnnotationRuleExamples.swift @@ -1,60 +1,58 @@ // swiftlint:disable:next type_name struct IncompatibleConcurrencyAnnotationRuleExamples { - static let nonTriggeringExamples = [ + static let nonTriggeringExamples = #examples([ // Sendable conformance is fine - Example("public struct S: Sendable {}"), - Example("public class C: Sendable {}"), - Example("public actor A {}"), + "public struct S: Sendable {}", + "public class C: Sendable {}", + "public actor A {}", // Non-public declarations are fine - Example("private @MainActor struct S { }"), - Example("@MainActor struct S { }"), - Example("internal @MainActor func globalActor()"), - Example("private @MainActor init() {}"), - Example("internal subscript(index: Int) -> String where String: Sendable { get }"), + "private @MainActor struct S { }", + "@MainActor struct S { }", + "internal @MainActor func globalActor()", + "private @MainActor init() {}", + "internal subscript(index: Int) -> String where String: Sendable { get }", // @preconcurrency makes it compatible - Example("@preconcurrency @MainActor public struct S {}"), - Example("@preconcurrency @MainActor public class C {}"), - Example("@preconcurrency @MainActor public enum E { case a }"), - Example("@preconcurrency @MainActor public protocol P {}"), - Example("@preconcurrency @MainActor public func globalActor()"), - Example("@preconcurrency public func sendableClosure(_ block: @Sendable () -> Void)"), - Example("@preconcurrency public func globalActorClosure(_ block: @MainActor () -> Void)"), - Example("@preconcurrency public init(_ block: @Sendable () -> Void)"), - Example( - "@preconcurrency public subscript(index: Int) -> String where String: Sendable { get }"), - Example("@preconcurrency public func sendableReturningClosure() -> @Sendable () -> Void"), - Example( - "@preconcurrency public func globalActorReturningClosure() -> @MainActor () -> Void"), - Example("@preconcurrency public func sendingParameter(_ value: sending MyClass)"), - Example(""" + "@preconcurrency @MainActor public struct S {}", + "@preconcurrency @MainActor public class C {}", + "@preconcurrency @MainActor public enum E { case a }", + "@preconcurrency @MainActor public protocol P {}", + "@preconcurrency @MainActor public func globalActor()", + "@preconcurrency public func sendableClosure(_ block: @Sendable () -> Void)", + "@preconcurrency public func globalActorClosure(_ block: @MainActor () -> Void)", + "@preconcurrency public init(_ block: @Sendable () -> Void)", + "@preconcurrency public subscript(index: Int) -> String where String: Sendable { get }", + "@preconcurrency public func sendableReturningClosure() -> @Sendable () -> Void", + "@preconcurrency public func globalActorReturningClosure() -> @MainActor () -> Void", + "@preconcurrency public func sendingParameter(_ value: sending MyClass)", + """ @preconcurrency public func tupleParameterClosures( _ handlers: (@Sendable () -> Void, @MainActor () -> Void) ) - """), - Example(""" + """, + """ @preconcurrency public func tupleReturningClosures() -> ( @Sendable () -> Void, @MainActor () -> Void ) - """), - Example(""" + """, + """ @preconcurrency public func closureWithSendingArgument( _ handler: (_ value: sending MyClass) -> Void ) - """), + """, // Non-concurrency related cases - Example("public func nonSendableClosure(_ block: () -> Void)"), - Example("public func generic() where T: Equatable"), - Example("public func generic()"), - Example("public init()"), + "public func nonSendableClosure(_ block: () -> Void)", + "public func generic() where T: Equatable", + "public func generic()", + "public init()", // Custom global actors without configuration - Example("public @MyActor enum E { case a }"), - Example("public func customActor(_ block: @MyActor () -> Void)"), - ] + "public @MyActor enum E { case a }", + "public func customActor(_ block: @MyActor () -> Void)", + ]) static let triggeringExamples = [ // Global actor on public declarations diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/InvisibleCharacterRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/InvisibleCharacterRule.swift index 0f1a607bbf..3a0fb00242 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/InvisibleCharacterRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/InvisibleCharacterRule.swift @@ -14,22 +14,22 @@ struct InvisibleCharacterRule: Rule { in string literals as they can cause hard-to-debug issues. """, kind: .lint, - nonTriggeringExamples: [ - Example(#"let s = "HelloWorld""#), - Example(#"let s = "Hello World""#), - Example(#"let url = "https://example.com/api""#), - Example(##"let s = #"Hello World"#"##), - Example(""" + nonTriggeringExamples: #examples([ + #"let s = "HelloWorld""#, + #"let s = "Hello World""#, + #"let url = "https://example.com/api""#, + ##"let s = #"Hello World"#"##, + """ let multiline = \"\"\" Hello World \"\"\" - """), - Example(#"let empty = """#), - Example(#"let tab = "Hello\tWorld""#), - Example(#"let newline = "Hello\nWorld""#), - Example(#"let unicode = "Hello 👋 World""#), - ], + """, + #"let empty = """#, + #"let tab = "Hello\tWorld""#, + #"let newline = "Hello\nWorld""#, + #"let unicode = "Hello 👋 World""#, + ]), triggeringExamples: [ Example(#"let s = "Hello↓​World" // U+200B zero-width space"#), Example(#"let s = "Hello↓‌World" // U+200C zero-width non-joiner"#), diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/LocalDocCommentRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/LocalDocCommentRule.swift index 94a3090234..d9a06933fb 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/LocalDocCommentRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/LocalDocCommentRule.swift @@ -9,35 +9,35 @@ struct LocalDocCommentRule: SwiftSyntaxRule, OptInRule { name: "Local Doc Comment", description: "Prefer regular comments over doc comments in local scopes", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ func foo() { // Local scope documentation should use normal comments. print("foo") } - """), - Example(""" + """, + """ /// My great property var myGreatProperty: String! - """), - Example(""" + """, + """ /// Look here for more info: https://github.com. var myGreatProperty: String! - """), - Example(""" + """, + """ /// Look here for more info: /// https://github.com. var myGreatProperty: String! - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ func foo() { ↓/// Docstring inside a function declaration print("foo") } - """), - ] + """, + ]) ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/LowerACLThanParentRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/LowerACLThanParentRule.swift index 3b1c9bf626..206bdd5bfe 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/LowerACLThanParentRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/LowerACLThanParentRule.swift @@ -9,76 +9,76 @@ struct LowerACLThanParentRule: Rule { name: "Lower ACL than Parent", description: "Ensure declarations have a lower access control level than their enclosing parent", kind: .lint, - nonTriggeringExamples: [ - Example("public struct Foo { public func bar() {} }"), - Example("internal struct Foo { func bar() {} }"), - Example("struct Foo { func bar() {} }"), - Example("struct Foo { internal func bar() {} }"), - Example("open class Foo { public func bar() {} }"), - Example("open class Foo { open func bar() {} }"), - Example("fileprivate struct Foo { private func bar() {} }"), - Example("private struct Foo { private func bar(id: String) }"), - Example("extension Foo { public func bar() {} }"), - Example("private struct Foo { fileprivate func bar() {} }"), - Example("private func foo(id: String) {}"), - Example("private class Foo { func bar() {} }"), - Example("public extension Foo { struct Bar { public func baz() {} }}"), - Example("public extension Foo { struct Bar { internal func baz() {} }}"), - Example("internal extension Foo { struct Bar { internal func baz() {} }}"), - Example("extension Foo { struct Bar { internal func baz() {} }}"), - ], - triggeringExamples: [ - Example("struct Foo { ↓public func bar() {} }"), - Example("enum Foo { ↓public func bar() {} }"), - Example("public class Foo { ↓open func bar() }"), - Example("class Foo { ↓public private(set) var bar: String? }"), - Example("private struct Foo { ↓public func bar() {} }"), - Example("private class Foo { ↓public func bar() {} }"), - Example("private actor Foo { ↓public func bar() {} }"), - Example("fileprivate struct Foo { ↓public func bar() {} }"), - Example("class Foo { ↓public func bar() {} }"), - Example("actor Foo { ↓public func bar() {} }"), - Example("private struct Foo { ↓internal func bar() {} }"), - Example("fileprivate struct Foo { ↓internal func bar() {} }"), - Example("extension Foo { struct Bar { ↓public func baz() {} }}"), - Example("internal extension Foo { struct Bar { ↓public func baz() {} }}"), - Example("private extension Foo { struct Bar { ↓public func baz() {} }}"), - Example("fileprivate extension Foo { struct Bar { ↓public func baz() {} }}"), - Example("private extension Foo { struct Bar { ↓internal func baz() {} }}"), - Example("fileprivate extension Foo { struct Bar { ↓internal func baz() {} }}"), - Example("public extension Foo { struct Bar { struct Baz { ↓public func qux() {} }}}"), - Example("final class Foo { ↓public func bar() {} }"), - ], - corrections: [ - Example("struct Foo { ↓public func bar() {} }"): - Example("struct Foo { func bar() {} }"), - Example("enum Foo { ↓public func bar() {} }"): - Example("enum Foo { func bar() {} }"), - Example("public class Foo { ↓open func bar() }"): - Example("public class Foo { public func bar() }"), - Example("class Foo { ↓public private(set) var bar: String? }"): - Example("class Foo { private(set) var bar: String? }"), - Example("private struct Foo { ↓public func bar() {} }"): - Example("private struct Foo { func bar() {} }"), - Example("private class Foo { ↓public func bar() {} }"): - Example("private class Foo { func bar() {} }"), - Example("private actor Foo { ↓public func bar() {} }"): - Example("private actor Foo { func bar() {} }"), - Example("class Foo { ↓public func bar() {} }"): - Example("class Foo { func bar() {} }"), - Example("actor Foo { ↓public func bar() {} }"): - Example("actor Foo { func bar() {} }"), - Example(""" + nonTriggeringExamples: #examples([ + "public struct Foo { public func bar() {} }", + "internal struct Foo { func bar() {} }", + "struct Foo { func bar() {} }", + "struct Foo { internal func bar() {} }", + "open class Foo { public func bar() {} }", + "open class Foo { open func bar() {} }", + "fileprivate struct Foo { private func bar() {} }", + "private struct Foo { private func bar(id: String) }", + "extension Foo { public func bar() {} }", + "private struct Foo { fileprivate func bar() {} }", + "private func foo(id: String) {}", + "private class Foo { func bar() {} }", + "public extension Foo { struct Bar { public func baz() {} }}", + "public extension Foo { struct Bar { internal func baz() {} }}", + "internal extension Foo { struct Bar { internal func baz() {} }}", + "extension Foo { struct Bar { internal func baz() {} }}", + ]), + triggeringExamples: #examples([ + "struct Foo { ↓public func bar() {} }", + "enum Foo { ↓public func bar() {} }", + "public class Foo { ↓open func bar() }", + "class Foo { ↓public private(set) var bar: String? }", + "private struct Foo { ↓public func bar() {} }", + "private class Foo { ↓public func bar() {} }", + "private actor Foo { ↓public func bar() {} }", + "fileprivate struct Foo { ↓public func bar() {} }", + "class Foo { ↓public func bar() {} }", + "actor Foo { ↓public func bar() {} }", + "private struct Foo { ↓internal func bar() {} }", + "fileprivate struct Foo { ↓internal func bar() {} }", + "extension Foo { struct Bar { ↓public func baz() {} }}", + "internal extension Foo { struct Bar { ↓public func baz() {} }}", + "private extension Foo { struct Bar { ↓public func baz() {} }}", + "fileprivate extension Foo { struct Bar { ↓public func baz() {} }}", + "private extension Foo { struct Bar { ↓internal func baz() {} }}", + "fileprivate extension Foo { struct Bar { ↓internal func baz() {} }}", + "public extension Foo { struct Bar { struct Baz { ↓public func qux() {} }}}", + "final class Foo { ↓public func bar() {} }", + ]), + corrections: #examplesDictionary([ + "struct Foo { ↓public func bar() {} }": + "struct Foo { func bar() {} }", + "enum Foo { ↓public func bar() {} }": + "enum Foo { func bar() {} }", + "public class Foo { ↓open func bar() }": + "public class Foo { public func bar() }", + "class Foo { ↓public private(set) var bar: String? }": + "class Foo { private(set) var bar: String? }", + "private struct Foo { ↓public func bar() {} }": + "private struct Foo { func bar() {} }", + "private class Foo { ↓public func bar() {} }": + "private class Foo { func bar() {} }", + "private actor Foo { ↓public func bar() {} }": + "private actor Foo { func bar() {} }", + "class Foo { ↓public func bar() {} }": + "class Foo { func bar() {} }", + "actor Foo { ↓public func bar() {} }": + "actor Foo { func bar() {} }", + """ struct Foo { ↓public func bar() {} } - """): - Example(""" + """: + """ struct Foo { func bar() {} } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringKeyRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringKeyRule.swift index 625794f023..7eeeaf4ee7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringKeyRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringKeyRule.swift @@ -10,26 +10,26 @@ struct NSLocalizedStringKeyRule: Rule { description: "Static strings should be used as key/comment" + " in NSLocalizedString in order for genstrings to work", kind: .lint, - nonTriggeringExamples: [ - Example("NSLocalizedString(\"key\", comment: \"\")"), - Example("NSLocalizedString(\"key\" + \"2\", comment: \"\")"), - Example("NSLocalizedString(\"key\", comment: \"comment\")"), - Example(""" + nonTriggeringExamples: #examples([ + "NSLocalizedString(\"key\", comment: \"\")", + "NSLocalizedString(\"key\" + \"2\", comment: \"\")", + "NSLocalizedString(\"key\", comment: \"comment\")", + """ NSLocalizedString("This is a multi-" + "line string", comment: "") - """), - Example(""" + """, + """ let format = NSLocalizedString("%@, %@.", comment: "Accessibility label for a post in the post list." + " The parameters are the title, and date respectively." + " For example, \"Let it Go, 1 hour ago.\"") - """), - ], - triggeringExamples: [ - Example("NSLocalizedString(↓method(), comment: \"\")"), - Example("NSLocalizedString(↓\"key_\\(param)\", comment: \"\")"), - Example("NSLocalizedString(\"key\", comment: ↓\"comment with \\(param)\")"), - Example("NSLocalizedString(↓\"key_\\(param)\", comment: ↓method())"), - ] + """, + ]), + triggeringExamples: #examples([ + "NSLocalizedString(↓method(), comment: \"\")", + "NSLocalizedString(↓\"key_\\(param)\", comment: \"\")", + "NSLocalizedString(\"key\", comment: ↓\"comment with \\(param)\")", + "NSLocalizedString(↓\"key_\\(param)\", comment: ↓method())", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringRequireBundleRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringRequireBundleRule.swift index 21ab2bb3bb..ea3d871aac 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringRequireBundleRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/NSLocalizedStringRequireBundleRule.swift @@ -9,36 +9,36 @@ struct NSLocalizedStringRequireBundleRule: Rule { name: "NSLocalizedString Require Bundle", description: "Calls to NSLocalizedString should specify the bundle which contains the strings file", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ NSLocalizedString("someKey", bundle: .main, comment: "test") - """), - Example(""" + """, + """ NSLocalizedString("someKey", tableName: "a", bundle: Bundle(for: A.self), comment: "test") - """), - Example(""" + """, + """ NSLocalizedString("someKey", tableName: "xyz", bundle: someBundle, value: "test" comment: "test") - """), - Example(""" + """, + """ arbitraryFunctionCall("something") - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓NSLocalizedString("someKey", comment: "test") - """), - Example(""" + """, + """ ↓NSLocalizedString("someKey", tableName: "a", comment: "test") - """), - Example(""" + """, + """ ↓NSLocalizedString("someKey", tableName: "xyz", value: "test", comment: "test") - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/NSNumberInitAsFunctionReferenceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/NSNumberInitAsFunctionReferenceRule.swift index bc600d0601..2f79df6f4d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/NSNumberInitAsFunctionReferenceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/NSNumberInitAsFunctionReferenceRule.swift @@ -11,17 +11,17 @@ struct NSNumberInitAsFunctionReferenceRule: Rule { description: "Passing `NSNumber.init` or `NSDecimalNumber.init` as a function reference is dangerous " + "as it can cause the wrong initializer to be used, causing crashes; use `.init(value:)` instead", kind: .lint, - nonTriggeringExamples: [ - Example("[0, 0.2].map(NSNumber.init(value:))"), - Example("let value = NSNumber.init(value: 0.0)"), - Example("[0, 0.2].map { NSNumber(value: $0) }"), - Example("[0, 0.2].map(NSDecimalNumber.init(value:))"), - Example("[0, 0.2].map { NSDecimalNumber(value: $0) }"), - ], - triggeringExamples: [ - Example("[0, 0.2].map(↓NSNumber.init)"), - Example("[0, 0.2].map(↓NSDecimalNumber.init)"), - ] + nonTriggeringExamples: #examples([ + "[0, 0.2].map(NSNumber.init(value:))", + "let value = NSNumber.init(value: 0.0)", + "[0, 0.2].map { NSNumber(value: $0) }", + "[0, 0.2].map(NSDecimalNumber.init(value:))", + "[0, 0.2].map { NSDecimalNumber(value: $0) }", + ]), + triggeringExamples: #examples([ + "[0, 0.2].map(↓NSNumber.init)", + "[0, 0.2].map(↓NSDecimalNumber.init)", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/NotificationCenterDetachmentRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/NotificationCenterDetachmentRuleExamples.swift index 7aa9c683aa..bb78e6ee81 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/NotificationCenterDetachmentRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/NotificationCenterDetachmentRuleExamples.swift @@ -1,28 +1,28 @@ internal struct NotificationCenterDetachmentRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ class Foo { deinit { NotificationCenter.default.removeObserver(self) } } - """), - Example(""" + """, + """ class Foo { func bar() { NotificationCenter.default.removeObserver(otherObject) } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class Foo { func bar() { ↓NotificationCenter.default.removeObserver(self) } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/OptionalDataStringConversionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/OptionalDataStringConversionRule.swift index 316e199391..342cf06049 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/OptionalDataStringConversionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/OptionalDataStringConversionRule.swift @@ -10,26 +10,26 @@ struct OptionalDataStringConversionRule: Rule { name: "Optional Data -> String Conversion", description: "Prefer failable `String(bytes:encoding:)` initializer when converting `Data` to `String`", kind: .lint, - nonTriggeringExamples: [ - Example("String(data: data, encoding: .utf8)"), - Example("String(bytes: data, encoding: .utf8)"), - Example("String(UTF8.self)"), - Example("String(a, b, c, UTF8.self)"), - Example("String(decoding: data, encoding: UTF8.self)"), + nonTriggeringExamples: #examples([ + "String(data: data, encoding: .utf8)", + "String(bytes: data, encoding: .utf8)", + "String(UTF8.self)", + "String(a, b, c, UTF8.self)", + "String(decoding: data, encoding: UTF8.self)", // Additional non-triggering examples to maximize coverage: - Example("String(data: data, encoding: .ascii)"), - Example("String(bytes: data, encoding: .utf16LittleEndian)"), - Example("String(decoding: data, as: UTF16.self)"), - Example("String.init(bytes: data, encoding: .utf8)"), - Example("let text: String = .init(bytes: data, encoding: .utf8)"), - Example("let text: String = .init(data)"), - Example("let text: Int = .init(decoding: data, as: UTF8.self)"), - Example("let n: Int = .init(0)"), - Example("String(repeating: \"a\", count: 3)"), - Example("String(format: \"%d\", 3)"), + "String(data: data, encoding: .ascii)", + "String(bytes: data, encoding: .utf16LittleEndian)", + "String(decoding: data, as: UTF16.self)", + "String.init(bytes: data, encoding: .utf8)", + "let text: String = .init(bytes: data, encoding: .utf8)", + "let text: String = .init(data)", + "let text: Int = .init(decoding: data, as: UTF8.self)", + "let n: Int = .init(0)", + "String(repeating: \"a\", count: 3)", + "String(format: \"%d\", 3)", // Default behavior (include_implicit_init == false): implicit leading-dot init without type - Example("let text = .init(decoding: data, as: UTF8.self)"), - ], + "let text = .init(decoding: data, as: UTF8.self)", + ]), triggeringExamples: [ Example("↓String(decoding: data, as: UTF8.self)"), Example("↓String.init(decoding: data, as: UTF8.self)"), diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/OrphanedDocCommentRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/OrphanedDocCommentRule.swift index d67dbfb0ae..8aa62c076c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/OrphanedDocCommentRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/OrphanedDocCommentRule.swift @@ -9,54 +9,54 @@ struct OrphanedDocCommentRule: Rule { name: "Orphaned Doc Comment", description: "A doc comment should be attached to a declaration", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ /// My great property var myGreatProperty: String! - """), - Example(""" + """, + """ ////////////////////////////////////// // // Copyright header. // ////////////////////////////////////// - """), - Example(""" + """, + """ /// Look here for more info: https://github.com. var myGreatProperty: String! - """), - Example(""" + """, + """ /// Look here for more info: /// https://github.com. var myGreatProperty: String! - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓/// My great property // Not a doc string var myGreatProperty: String! - """), - Example(""" + """, + """ ↓/// Look here for more info: https://github.com. // Not a doc string var myGreatProperty: String! - """), - Example(""" + """, + """ ↓/// Look here for more info: https://github.com. // Not a doc string var myGreatProperty: String! - """), - Example(""" + """, + """ ↓/// Look here for more info: https://github.com. // Not a doc string ↓/// My great property // Not a doc string var myGreatProperty: String! - """), - Example(""" + """, + """ extension Nested { ↓/// /// Look here for more info: https://github.com. @@ -64,8 +64,8 @@ struct OrphanedDocCommentRule: Rule { // Not a doc string var myGreatProperty: String! } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/OverriddenSuperCallRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/OverriddenSuperCallRule.swift index 9844311b37..12ad1138e5 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/OverriddenSuperCallRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/OverriddenSuperCallRule.swift @@ -9,15 +9,15 @@ struct OverriddenSuperCallRule: Rule { name: "Overridden Method Calls Super", description: "Some overridden methods should always call super.", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class VC: UIViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } } - """), - Example(""" + """, + """ class VC: UIViewController { override func viewWillAppear(_ animated: Bool) { self.method1() @@ -25,20 +25,20 @@ struct OverriddenSuperCallRule: Rule { self.method2() } } - """), - Example(""" + """, + """ class VC: UIViewController { override func loadView() { } } - """), - Example(""" + """, + """ class Some { func viewWillAppear(_ animated: Bool) { } } - """), - Example(""" + """, + """ class VC: UIViewController { override func viewDidLoad() { defer { @@ -46,18 +46,18 @@ struct OverriddenSuperCallRule: Rule { } } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ class VC: UIViewController { override func viewWillAppear(_ animated: Bool) {↓ //Not calling to super self.method() } } - """), - Example(""" + """, + """ class VC: UIViewController { override func viewWillAppear(_ animated: Bool) {↓ super.viewWillAppear(animated) @@ -65,14 +65,14 @@ struct OverriddenSuperCallRule: Rule { super.viewWillAppear(animated) } } - """), - Example(""" + """, + """ class VC: UIViewController { override func didReceiveMemoryWarning() {↓ } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/OverrideInExtensionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/OverrideInExtensionRule.swift index 8241df3a62..e355d17399 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/OverrideInExtensionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/OverrideInExtensionRule.swift @@ -8,36 +8,36 @@ struct OverrideInExtensionRule: OptInRule, SwiftSyntaxRule { name: "Override in Extension", description: "Extensions shouldn't override declarations", kind: .lint, - nonTriggeringExamples: [ - Example("extension Person {\n var age: Int { return 42 }\n}"), - Example("extension Person {\n func celebrateBirthday() {}\n}"), - Example("class Employee: Person {\n override func celebrateBirthday() {}\n}"), - Example(""" + nonTriggeringExamples: #examples([ + "extension Person {\n var age: Int { return 42 }\n}", + "extension Person {\n func celebrateBirthday() {}\n}", + "class Employee: Person {\n override func celebrateBirthday() {}\n}", + """ class Foo: NSObject {} extension Foo { override var description: String { return "" } } - """), - Example(""" + """, + """ struct Foo { class Bar: NSObject {} } extension Foo.Bar { override var description: String { return "" } } - """), - Example(""" + """, + """ @objc @implementation extension Person { override func celebrateBirthday() {} } - """), - ], - triggeringExamples: [ - Example("extension Person {\n override ↓var age: Int { return 42 }\n}"), - Example("extension Person {\n override ↓func celebrateBirthday() {}\n}"), - ] + """, + ]), + triggeringExamples: #examples([ + "extension Person {\n override ↓var age: Int { return 42 }\n}", + "extension Person {\n override ↓func celebrateBirthday() {}\n}", + ]) ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/PeriodSpacingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/PeriodSpacingRule.swift index ca9e989553..eccbc8afe6 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/PeriodSpacingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/PeriodSpacingRule.swift @@ -10,25 +10,25 @@ struct PeriodSpacingRule: SourceKitFreeRule, OptInRule, SubstitutionCorrectableR name: "Period Spacing", description: "Periods should not be followed by more than one space", kind: .style, - nonTriggeringExamples: [ - Example("let pi = 3.2"), - Example("let pi = Double.pi"), - Example("let pi = Double. pi"), - Example("let pi = Double. pi"), - Example("// A. Single."), - Example("/// - code: Identifier of the error. Integer."), - Example(""" + nonTriggeringExamples: #examples([ + "let pi = 3.2", + "let pi = Double.pi", + "let pi = Double. pi", + "let pi = Double. pi", + "// A. Single.", + "/// - code: Identifier of the error. Integer.", + """ // value: Multiline. // Comment. - """), - Example(""" + """, + """ /** Sentence ended in period. - Sentence 2 new line characters after. **/ - """), - ], + """, + ]), triggeringExamples: [ Example("/* Only god knows why. ↓ This symbol does nothing. */", testWrappingInComment: false), Example("// Only god knows why. ↓ This symbol does nothing.", testWrappingInComment: false), @@ -37,14 +37,14 @@ struct PeriodSpacingRule: SourceKitFreeRule, OptInRule, SubstitutionCorrectableR Example("// Triple. ↓ Quad. ↓ End.", testWrappingInComment: false), Example("/// - code: Identifier of the error. ↓ Integer.", testWrappingInComment: false), ], - corrections: [ - Example("/* Why. ↓ Symbol does nothing. */"): Example("/* Why. Symbol does nothing. */"), - Example("// Why. ↓ Symbol does nothing."): Example("// Why. Symbol does nothing."), - Example("// Single. Double. ↓ End."): Example("// Single. Double. End."), - Example("// Single. Double. ↓ Triple. ↓ End."): Example("// Single. Double. Triple. End."), - Example("// Triple. ↓ Quad. ↓ End."): Example("// Triple. Quad. End."), - Example("/// - code: Identifier. ↓ Integer."): Example("/// - code: Identifier. Integer."), - ] + corrections: #examplesDictionary([ + "/* Why. ↓ Symbol does nothing. */": "/* Why. Symbol does nothing. */", + "// Why. ↓ Symbol does nothing.": "// Why. Symbol does nothing.", + "// Single. Double. ↓ End.": "// Single. Double. End.", + "// Single. Double. ↓ Triple. ↓ End.": "// Single. Double. Triple. End.", + "// Triple. ↓ Quad. ↓ End.": "// Triple. Quad. End.", + "/// - code: Identifier. ↓ Integer.": "/// - code: Identifier. Integer.", + ]) ) func violationRanges(in file: SwiftLintFile) -> [NSRange] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateActionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateActionRule.swift index 5c132e349e..430081cbb1 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateActionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateActionRule.swift @@ -9,27 +9,27 @@ struct PrivateActionRule: Rule { name: "Private Actions", description: "IBActions should be private", kind: .lint, - nonTriggeringExamples: [ - Example("class Foo {\n\t@IBAction private func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("struct Foo {\n\t@IBAction private func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("class Foo {\n\t@IBAction fileprivate func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("struct Foo {\n\t@IBAction fileprivate func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("private extension Foo {\n\t@IBAction func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("fileprivate extension Foo {\n\t@IBAction func barButtonTapped(_ sender: UIButton) {}\n}"), - ], - triggeringExamples: [ - Example("class Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("struct Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("class Foo {\n\t@IBAction public ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("struct Foo {\n\t@IBAction public ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("class Foo {\n\t@IBAction internal ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("struct Foo {\n\t@IBAction internal ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("extension Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("extension Foo {\n\t@IBAction public ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("extension Foo {\n\t@IBAction internal ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("public extension Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - Example("internal extension Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}"), - ] + nonTriggeringExamples: #examples([ + "class Foo {\n\t@IBAction private func barButtonTapped(_ sender: UIButton) {}\n}", + "struct Foo {\n\t@IBAction private func barButtonTapped(_ sender: UIButton) {}\n}", + "class Foo {\n\t@IBAction fileprivate func barButtonTapped(_ sender: UIButton) {}\n}", + "struct Foo {\n\t@IBAction fileprivate func barButtonTapped(_ sender: UIButton) {}\n}", + "private extension Foo {\n\t@IBAction func barButtonTapped(_ sender: UIButton) {}\n}", + "fileprivate extension Foo {\n\t@IBAction func barButtonTapped(_ sender: UIButton) {}\n}", + ]), + triggeringExamples: #examples([ + "class Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "struct Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "class Foo {\n\t@IBAction public ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "struct Foo {\n\t@IBAction public ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "class Foo {\n\t@IBAction internal ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "struct Foo {\n\t@IBAction internal ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "extension Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "extension Foo {\n\t@IBAction public ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "extension Foo {\n\t@IBAction internal ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "public extension Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}", + "internal extension Foo {\n\t@IBAction ↓func barButtonTapped(_ sender: UIButton) {}\n}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSubjectRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSubjectRuleExamples.swift index 0c2f06a1f4..3e9737d7ac 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSubjectRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSubjectRuleExamples.swift @@ -1,108 +1,79 @@ internal struct PrivateSubjectRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example( - #""" + static let nonTriggeringExamples: [Example] = #examples([ + #""" final class Foobar { private let goodSubject = PassthroughSubject() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: PassthroughSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { fileprivate let goodSubject: PassthroughSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: PassthroughSubject = .init() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject = CurrentValueSubject(false) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: CurrentValueSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { fileprivate let goodSubject: CurrentValueSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: CurrentValueSubject = .init("toto") } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject = PassthroughSubject, Never>() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: PassthroughSubject, Never> = .init() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: CurrentValueSubject, Never> = .init([]) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject = PassthroughSubject() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: PassthroughSubject = .init() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject = CurrentValueSubject(true) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: CurrentValueSubject init() { @@ -110,168 +81,125 @@ internal struct PrivateSubjectRuleExamples { self.goosSubject = goodSubject } } - """# - ), - Example( - """ + """#, + """ func foo() { let goodSubject = PassthroughSubject(true) } - """ - ), - ] + """, + ]) - static let triggeringExamples: [Example] = [ - Example( - #""" + static let triggeringExamples: [Example] = #examples([ + #""" final class Foobar { let ↓badSubject = PassthroughSubject() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject: PassthroughSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private(set) let ↓badSubject: PassthroughSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private(set) let ↓badSubject = PassthroughSubject() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let goodSubject: PassthroughSubject = .init() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: PassthroughSubject private(set) let ↓badSubject = PassthroughSubject() private(set) let ↓anotherBadSubject = PassthroughSubject() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private(set) let ↓badSubject = PassthroughSubject() private let goodSubject: PassthroughSubject private(set) let ↓anotherBadSubject = PassthroughSubject() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject = CurrentValueSubject(true) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject: CurrentValueSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private(set) let ↓badSubject: CurrentValueSubject } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private(set) let ↓badSubject = CurrentValueSubject(false) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let goodSubject: CurrentValueSubject = .init("toto") } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private let goodSubject: CurrentValueSubject private(set) let ↓badSubject = CurrentValueSubject(false) private(set) let ↓anotherBadSubject = CurrentValueSubject(false) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { private(set) let ↓badSubject = CurrentValueSubject(false) private let goodSubject: CurrentValueSubject private(set) let ↓anotherBadSubject = CurrentValueSubject(true) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject = PassthroughSubject, Never>() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject: PassthroughSubject, Never> = .init() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject: CurrentValueSubject, Never> = .init([]) } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject = PassthroughSubject() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject: PassthroughSubject = .init() } - """# - ), - Example( - #""" + """#, + #""" final class Foobar { let ↓badSubject = CurrentValueSubject(true) } - """# - ), - ] + """#, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSwiftUIStatePropertyRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSwiftUIStatePropertyRuleExamples.swift index 5af502b451..b430643e31 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSwiftUIStatePropertyRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateSwiftUIStatePropertyRuleExamples.swift @@ -1,21 +1,21 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example(""" + static let nonTriggeringExamples: [Example] = #examples([ + """ struct MyApp: App { @State private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct MyScene: Scene { @State private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct CofntentView: View { @State private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { @State private var isPlaying: Bool = false @@ -23,15 +23,15 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { @State private var showsIndicator: Bool = false } } - """), - Example(""" + """, + """ struct MyStruct { struct ContentView: View { @State private var isPlaying: Bool = false } } - """), - Example(""" + """, + """ struct MyStruct { struct ContentView: View { @State private var isPlaying: Bool = false @@ -39,8 +39,8 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { @State var nonTriggeringState: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { var s: Int { @State @@ -50,28 +50,28 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { var body: some View { Text("") } } - """), - Example(""" + """, + """ struct ContentView: View { var isPlaying = false } - """), - Example(""" + """, + """ struct MyApp: App { @StateObject private var model = DataModel() } - """), - Example(""" + """, + """ struct MyScene: Scene { @StateObject private var model = DataModel() } - """), - Example(""" + """, + """ struct ContentView: View { @StateObject private var model = DataModel() } - """), - Example(""" + """, + """ struct MyStruct { struct ContentView: View { @StateObject private var dataModel = DataModel() @@ -79,53 +79,53 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { @StateObject var nonTriggeringObject = MyModel() } - """), - Example(""" + """, + """ struct Foo { @State var bar = false } - """), - Example(""" + """, + """ class Foo: ObservableObject { @State var bar = Bar() } - """), - Example(""" + """, + """ extension MyObject { struct ContentView: View { @State private var isPlaying: Bool = false } } - """), - Example(""" + """, + """ actor ContentView: View { @State private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentViewModifier: ViewModifier { @State private var isPlaying = false } - """), - ] + """, + ]) - static let triggeringExamples: [Example] = [ - Example(""" + static let triggeringExamples: [Example] = #examples([ + """ struct MyApp: App { @State ↓var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct MyScene: Scene { @State ↓public var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { @State ↓var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { struct InnerView: View { @State private var showsIndicator: Bool = false @@ -133,15 +133,15 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { @State ↓var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct MyStruct { struct ContentView: View { @State ↓var isPlaying: Bool = false } } - """), - Example(""" + """, + """ struct MyStruct { struct ContentView: View { @State ↓var isPlaying: Bool = false @@ -149,83 +149,83 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { @State var isPlaying: Bool = false } - """), - Example(""" + """, + """ final class ContentView: View { @State ↓var isPlaying: Bool = false } - """), - Example(""" + """, + """ extension MyObject { struct ContentView: View { @State ↓var isPlaying: Bool = false } } - """), - Example(""" + """, + """ actor ContentView: View { @State ↓var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct MyApp: App { @StateObject ↓var model = DataModel() } - """), - Example(""" + """, + """ struct MyScene: Scene { @StateObject ↓var model = DataModel() } - """), - Example(""" + """, + """ struct ContentView: View { @StateObject ↓var model = DataModel() } - """), - Example(""" + """, + """ struct ContentView: View { @State ↓private(set) var isPlaying = false - """), - Example(""" + """, + """ struct ContentView: View { @State ↓fileprivate(set) public var isPlaying = false - """), - Example(""" + """, + """ struct ContentViewModifier: ViewModifier { @State ↓var isPlaying = false } - """), - ] + """, + ]) - static let corrections: [Example: Example] = [ - Example(""" + static let corrections: [Example: Example] = #examplesDictionary([ + """ struct ContentView: View { @State ↓var isPlaying: Bool = false } - """): Example(""" + """: """ struct ContentView: View { @State private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { @State public ↓var isPlaying: Bool = false } - """): Example(""" + """: """ struct ContentView: View { @State private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { @State private(set) ↓var isPlaying: Bool = false } - """): Example(""" + """: """ struct ContentView: View { @State private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { @State /// This will track if the content is currently playing @@ -233,48 +233,48 @@ internal struct PrivateSwiftUIStatePropertyRuleExamples { // This is another comment about this property public ↓var isPlaying: Bool = false } - """): Example(""" + """: """ struct ContentView: View { @State /// This will track if the content is currently playing // This is another comment about this property private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct MyApp: App { @State /// This will track if the content is currently playing ↓var isPlaying: Bool = false } - """): Example(""" + """: """ struct MyApp: App { @State /// This will track if the content is currently playing private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct MyScene: Scene { @State /* This is a comment */ ↓var isPlaying: Bool = false } - """): Example(""" + """: """ struct MyScene: Scene { @State /* This is a comment */ private var isPlaying: Bool = false } - """), - Example(""" + """, + """ struct ContentView: View { @State /// This will track if the content is currently playing ↓var isPlaying: Bool = false } - """): Example(""" + """: """ struct ContentView: View { @State /// This will track if the content is currently playing private var isPlaying: Bool = false } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateUnitTestRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateUnitTestRule.swift index f038b9e394..2b7410b4db 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateUnitTestRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/PrivateUnitTestRule.swift @@ -10,103 +10,103 @@ struct PrivateUnitTestRule: Rule { name: "Private Unit Test", description: "Unit tests marked private are silently skipped", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class FooTest: XCTestCase { func test1() {} internal func test2() {} public func test3() {} } - """), - Example(""" + """, + """ internal class FooTest: XCTestCase { func test1() {} internal func test2() {} public func test3() {} } - """), - Example(""" + """, + """ public class FooTest: XCTestCase { func test1() {} internal func test2() {} public func test3() {} } - """), - Example(""" + """, + """ @objc private class FooTest: XCTestCase { @objc private func test1() {} internal func test2() {} public func test3() {} } - """), + """, // Non-test classes - Example(""" + """ private class Foo: NSObject { func test1() {} internal func test2() {} public func test3() {} } - """), - Example(""" + """, + """ private class Foo { func test1() {} internal func test2() {} public func test3() {} } - """), + """, // Non-test methods - Example(""" + """ public class FooTest: XCTestCase { private func test1(param: Int) {} private func test2() -> String { "" } private func atest() {} private static func test3() {} } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ private ↓class FooTest: XCTestCase { func test1() {} internal func test2() {} public func test3() {} private func test4() {} } - """), - Example(""" + """, + """ class FooTest: XCTestCase { func test1() {} internal func test2() {} public func test3() {} private ↓func test4() {} } - """), - Example(""" + """, + """ internal class FooTest: XCTestCase { func test1() {} internal func test2() {} public func test3() {} private ↓func test4() {} } - """), - Example(""" + """, + """ public class FooTest: XCTestCase { func test1() {} internal func test2() {} public func test3() {} private ↓func test4() {} } - """), - ], - corrections: [ - Example(""" + """, + ]), + corrections: #examplesDictionary([ + """ ↓private class Test: XCTestCase {} - """): Example(""" + """: """ class Test: XCTestCase {} - """), - Example(""" + """, + """ class Test: XCTestCase { ↓private func test1() {} @@ -114,7 +114,7 @@ struct PrivateUnitTestRule: Rule { @objc private func test3() {} internal func test4() {} } - """): Example(""" + """: """ class Test: XCTestCase { func test1() {} @@ -122,8 +122,8 @@ struct PrivateUnitTestRule: Rule { @objc private func test3() {} internal func test4() {} } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/ProhibitedSuperRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/ProhibitedSuperRule.swift index 34bff27379..71d6c67efc 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/ProhibitedSuperRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/ProhibitedSuperRule.swift @@ -9,21 +9,21 @@ struct ProhibitedSuperRule: Rule { name: "Prohibited Calls to Super", description: "Some methods should not call super.", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class VC: UIViewController { override func loadView() { } } - """), - Example(""" + """, + """ class NSView { func updateLayer() { self.method1() } } - """), - Example(""" + """, + """ public class FileProviderExtension: NSFileProviderExtension { override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) { guard let identifier = persistentIdentifierForItem(at: url) else { @@ -32,25 +32,25 @@ struct ProhibitedSuperRule: Rule { } } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ class VC: UIViewController { override func loadView() {↓ super.loadView() } } - """), - Example(""" + """, + """ class VC: NSFileProviderExtension { override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {↓ self.method1() super.providePlaceholder(at:url, completionHandler: completionHandler) } } - """), - Example(""" + """, + """ class VC: NSView { override func updateLayer() {↓ self.method1() @@ -58,8 +58,8 @@ struct ProhibitedSuperRule: Rule { self.method2() } } - """), - Example(""" + """, + """ class VC: NSView { override func updateLayer() {↓ defer { @@ -67,8 +67,8 @@ struct ProhibitedSuperRule: Rule { } } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedCallRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedCallRuleExamples.swift index 1a13a81b6f..a99f87cf2a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedCallRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedCallRuleExamples.swift @@ -1,6 +1,6 @@ internal struct QuickDiscouragedCallRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example(""" + static let nonTriggeringExamples: [Example] = #examples([ + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -14,8 +14,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests { override func spec() { describe("foo") { @@ -23,8 +23,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -35,8 +35,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -59,8 +59,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -71,8 +71,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -83,8 +83,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -92,8 +92,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -104,8 +104,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { context("foo") { @@ -113,8 +113,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { xcontext("foo") { @@ -122,8 +122,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { xdescribe("foo") { @@ -131,8 +131,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -143,8 +143,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { fcontext("foo") { @@ -152,8 +152,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { fdescribe("foo") { @@ -161,8 +161,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -172,25 +172,25 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { fitBehavesLike("foo") } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { xitBehavesLike("foo") } } - """), - ] + """, + ]) - static let triggeringExamples: [Example] = [ - Example(""" + static let triggeringExamples: [Example] = #examples([ + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -198,8 +198,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override static func spec() { describe("foo") { @@ -207,8 +207,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -216,8 +216,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -235,8 +235,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -256,8 +256,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { context("foo") { @@ -265,8 +265,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { sharedExamples("foo") { @@ -274,8 +274,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -285,8 +285,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { context("foo") { @@ -294,8 +294,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { sharedExamples("foo") { @@ -303,8 +303,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ #if os(macOS) class TotoTests: QuickSpec { override func spec() { @@ -314,8 +314,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } #endif - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { sharedExamples("foo") { @@ -323,8 +323,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { xdescribe("foo") { @@ -335,8 +335,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { xcontext("foo") { @@ -347,8 +347,8 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpecSubclass { override func spec() { xcontext("foo") { @@ -359,6 +359,6 @@ internal struct QuickDiscouragedCallRuleExamples { } } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedFocusedTestRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedFocusedTestRuleExamples.swift index 3b0e1077bc..dc1435070f 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedFocusedTestRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedFocusedTestRuleExamples.swift @@ -1,6 +1,6 @@ internal struct QuickDiscouragedFocusedTestRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -13,32 +13,32 @@ internal struct QuickDiscouragedFocusedTestRuleExamples { } } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class TotoTests: QuickSpec { override func spec() { ↓fdescribe("foo") { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { ↓fcontext("foo") { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { ↓fit("foo") { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -46,8 +46,8 @@ internal struct QuickDiscouragedFocusedTestRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { context("foo") { @@ -55,8 +55,8 @@ internal struct QuickDiscouragedFocusedTestRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -66,20 +66,20 @@ internal struct QuickDiscouragedFocusedTestRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { ↓fitBehavesLike("foo") } } - """), - Example(""" + """, + """ class TotoTests: QuickSpecSubclass { override func spec() { ↓fitBehavesLike("foo") } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedPendingTestRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedPendingTestRuleExamples.swift index eb8018cd95..0398d3b0f0 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedPendingTestRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/QuickDiscouragedPendingTestRuleExamples.swift @@ -1,6 +1,6 @@ internal struct QuickDiscouragedPendingTestRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -13,32 +13,32 @@ internal struct QuickDiscouragedPendingTestRuleExamples { } } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class TotoTests: QuickSpec { override func spec() { ↓xdescribe("foo") { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { ↓xcontext("foo") { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { ↓xit("foo") { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -46,8 +46,8 @@ internal struct QuickDiscouragedPendingTestRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { context("foo") { @@ -55,8 +55,8 @@ internal struct QuickDiscouragedPendingTestRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { describe("foo") { @@ -66,27 +66,27 @@ internal struct QuickDiscouragedPendingTestRuleExamples { } } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { ↓pending("foo") } } - """), - Example(""" + """, + """ class TotoTests: QuickSpec { override func spec() { ↓xitBehavesLike("foo") } } - """), - Example(""" + """, + """ class TotoTests: QuickSpecSubclass { override func spec() { ↓xitBehavesLike("foo") } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/RawValueForCamelCasedCodableEnumRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/RawValueForCamelCasedCodableEnumRule.swift index c4044d1783..1a022c23e8 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/RawValueForCamelCasedCodableEnumRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/RawValueForCamelCasedCodableEnumRule.swift @@ -9,87 +9,87 @@ struct RawValueForCamelCasedCodableEnumRule: Rule { name: "Raw Value for Camel Cased Codable Enum", description: "Camel cased cases of Codable String enums should have raw values", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum Numbers: Codable { case int(Int) case short(Int16) } - """), - Example(""" + """, + """ enum Numbers: Int, Codable { case one = 1 case two = 2 } - """), - Example(""" + """, + """ enum Numbers: Double, Codable { case one = 1.1 case two = 2.2 } - """), - Example(""" + """, + """ enum Numbers: String, Codable { case one = "one" case two = "two" } - """), - Example(""" + """, + """ enum Status: String, Codable { case OK, ACCEPTABLE } - """), - Example(""" + """, + """ enum Status: String, Codable { case ok case maybeAcceptable = "maybe_acceptable" } - """), - Example(""" + """, + """ enum Status: String { case ok case notAcceptable case maybeAcceptable = "maybe_acceptable" } - """), - Example(""" + """, + """ enum Status: Int, Codable { case ok case notAcceptable case maybeAcceptable = -1 } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ enum Status: String, Codable { case ok case ↓notAcceptable case maybeAcceptable = "maybe_acceptable" } - """), - Example(""" + """, + """ enum Status: String, Decodable { case ok case ↓notAcceptable case maybeAcceptable = "maybe_acceptable" } - """), - Example(""" + """, + """ enum Status: String, Encodable { case ok case ↓notAcceptable case maybeAcceptable = "maybe_acceptable" } - """), - Example(""" + """, + """ enum Status: String, Codable { case ok case ↓notAcceptable case maybeAcceptable = "maybe_acceptable" } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/RedundantSendableRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/RedundantSendableRule.swift index 0a6549fc82..06d19f4ce2 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/RedundantSendableRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/RedundantSendableRule.swift @@ -9,14 +9,14 @@ struct RedundantSendableRule: Rule { name: "Redundant Sendable", description: "Sendable conformance is redundant on an actor-isolated type", kind: .lint, - nonTriggeringExamples: [ - Example("struct S: Sendable {}"), - Example("class C: Sendable {}"), - Example("actor A {}"), - Example("@MainActor struct S {}"), - Example("@MyActor enum E: Sendable { case a }"), - Example("@MainActor protocol P: Sendable {}"), - ], + nonTriggeringExamples: #examples([ + "struct S: Sendable {}", + "class C: Sendable {}", + "actor A {}", + "@MainActor struct S {}", + "@MyActor enum E: Sendable { case a }", + "@MainActor protocol P: Sendable {}", + ]), triggeringExamples: [ Example("@MainActor struct ↓S: Sendable {}"), Example("actor ↓A: Sendable {}"), diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/RequiredDeinitRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/RequiredDeinitRule.swift index 972c325fa2..e479e68a33 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/RequiredDeinitRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/RequiredDeinitRule.swift @@ -15,38 +15,38 @@ struct RequiredDeinitRule: Rule { name: "Required Deinit", description: "Classes should have an explicit deinit method", kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class Apple { deinit { } } - """), - Example("enum Banana { }"), - Example("protocol Cherry { }"), - Example("struct Damson { }"), - Example(""" + """, + "enum Banana { }", + "protocol Cherry { }", + "struct Damson { }", + """ class Outer { deinit { print("Deinit Outer") } class Inner { deinit { print("Deinit Inner") } } } - """), - ], - triggeringExamples: [ - Example("↓class Apple { }"), - Example("↓class Banana: NSObject, Equatable { }"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "↓class Apple { }", + "↓class Banana: NSObject, Equatable { }", + """ ↓class Cherry { // deinit { } } - """), - Example(""" + """, + """ ↓class Damson { func deinitialize() { } } - """), - Example(""" + """, + """ class Outer { func hello() -> String { return "outer" } deinit { } @@ -54,8 +54,8 @@ struct RequiredDeinitRule: Rule { func hello() -> String { return "inner" } } } - """), - Example(""" + """, + """ ↓class Outer { func hello() -> String { return "outer" } class Inner { @@ -63,8 +63,8 @@ struct RequiredDeinitRule: Rule { deinit { } } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/SelfInPropertyInitializationRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/SelfInPropertyInitializationRule.swift index b4f3f66c2a..d8e1ccdd1c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/SelfInPropertyInitializationRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/SelfInPropertyInitializationRule.swift @@ -75,8 +75,8 @@ struct SelfInPropertyInitializationRule: Rule { } """, excludeFromDocumentation: true), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ class View: UIView { ↓var button: UIButton = { let button = UIButton() @@ -84,8 +84,8 @@ struct SelfInPropertyInitializationRule: Rule { return button }() } - """), - Example(""" + """, + """ class View: UIView { ↓let button: UIButton = { let button = UIButton() @@ -93,8 +93,8 @@ struct SelfInPropertyInitializationRule: Rule { return button }() } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/TestCaseAccessibilityRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/TestCaseAccessibilityRuleExamples.swift index 736c9e6031..eb475ba1dc 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/TestCaseAccessibilityRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/TestCaseAccessibilityRuleExamples.swift @@ -77,8 +77,8 @@ internal struct TestCaseAccessibilityRuleExamples { """), ] - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class FooTests: XCTestCase { ↓typealias Bar = Foo.Bar @@ -105,11 +105,11 @@ internal struct TestCaseAccessibilityRuleExamples { final class BarTests: XCTestCase { ↓class Nested {} } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ class TotoTests: XCTestCase { ↓var foo: Bar? @@ -125,8 +125,8 @@ internal struct TestCaseAccessibilityRuleExamples { ↓func helperFunction() {} } - """): - Example(""" + """: + """ class TotoTests: XCTestCase { private var foo: Bar? @@ -142,6 +142,6 @@ internal struct TestCaseAccessibilityRuleExamples { private func helperFunction() {} } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/TodoRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/TodoRule.swift index 6dd9d95fb4..ead5fa20aa 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/TodoRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/TodoRule.swift @@ -11,20 +11,20 @@ struct TodoRule: Rule { name: "Todo", description: "TODOs and FIXMEs should be resolved.", kind: .lint, - nonTriggeringExamples: [ - Example("// notaTODO:"), - Example("// notaFIXME:"), - ], - triggeringExamples: [ - Example("// ↓TODO:"), - Example("// ↓FIXME:"), - Example("// ↓TODO(note)"), - Example("// ↓FIXME(note)"), - Example("/* ↓FIXME: */"), - Example("/* ↓TODO: */"), - Example("/** ↓FIXME: */"), - Example("/** ↓TODO: */"), - ].skipWrappingInCommentTests() + nonTriggeringExamples: #examples([ + "// notaTODO:", + "// notaFIXME:", + ]), + triggeringExamples: #examples([ + "// ↓TODO:", + "// ↓FIXME:", + "// ↓TODO(note)", + "// ↓FIXME(note)", + "/* ↓FIXME: */", + "/* ↓TODO: */", + "/** ↓FIXME: */", + "/** ↓TODO: */", + ]).skipWrappingInCommentTests() ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/TypesafeArrayInitRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/TypesafeArrayInitRule.swift index 1d55d5bc36..84bf981562 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/TypesafeArrayInitRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/TypesafeArrayInitRule.swift @@ -9,13 +9,13 @@ struct TypesafeArrayInitRule: AnalyzerRule { name: "Type-safe Array Init", description: ArrayInitRule.description.description, kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum MyError: Error {} let myResult: Result = .success("") let result: Result = myResult.map { $0 } - """), - Example(""" + """, + """ struct IntArray { let elements = [1, 2, 3] func map(_ transformer: (Int) throws -> T) rethrows -> [T] { @@ -24,29 +24,29 @@ struct TypesafeArrayInitRule: AnalyzerRule { } let ints = IntArray() let intsCopy = ints.map { $0 } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ func f(s: Seq) -> [Seq.Element] { s.↓map({ $0 }) } - """), - Example(""" + """, + """ func f(array: [Int]) -> [Int] { array.↓map { $0 } } - """), - Example(""" + """, + """ let myInts = [1, 2, 3].↓map { return $0 } - """), - Example(""" + """, + """ struct Generator: Sequence, IteratorProtocol { func next() -> Int? { nil } } let array = Generator().↓map { i in i } - """), - ], + """, + ]), requiresFileOnDisk: true ) diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnhandledThrowingTaskRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnhandledThrowingTaskRule.swift index ed63c8653b..6cb6ae7b8c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnhandledThrowingTaskRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnhandledThrowingTaskRule.swift @@ -14,29 +14,29 @@ struct UnhandledThrowingTaskRule: Rule { https://forums.swift.org/t/task-initializer-with-throwing-closure-swallows-error/56066 """, kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ Task { try await myThrowingFunction() } - """), - Example(""" + """, + """ Task { try? await myThrowingFunction() } - """), - Example(""" + """, + """ Task { try! await myThrowingFunction() } - """), - Example(""" + """, + """ Task { let text = try myThrowingFunction() return text } - """), - Example(""" + """, + """ Task { do { try myThrowingFunction() @@ -44,8 +44,8 @@ struct UnhandledThrowingTaskRule: Rule { print(e) } } - """), - Example(""" + """, + """ func someFunction() throws { Task { anotherFunction() @@ -58,75 +58,75 @@ struct UnhandledThrowingTaskRule: Rule { try something() } - """), - Example(""" + """, + """ let task = Task { try await myThrowingFunction() } - """), - Example(""" + """, + """ var task = Task { try await myThrowingFunction() } - """), - Example(""" + """, + """ try await Task { try await myThrowingFunction() }.value - """), - Example(""" + """, + """ executor.task = Task { try await isolatedOpen(.init(executor.asUnownedSerialExecutor())) } - """), - Example(""" + """, + """ let result = await Task { throw CancellationError() }.result - """), - Example(""" + """, + """ func makeTask() -> Task { return Task { try await someThrowingFunction() } } - """), - Example(""" + """, + """ func makeTask() -> Task { // Implicit return Task { try await someThrowingFunction() } } - """), - Example(""" + """, + """ Task { return Result { try someThrowingFunc() } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓Task { try await myThrowingFunction() } - """), - Example(""" + """, + """ ↓Task { let text = try myThrowingFunction() return text } - """), - Example(""" + """, + """ ↓Task { do { try myThrowingFunction() } } - """), - Example(""" + """, + """ ↓Task { do { try myThrowingFunction() @@ -134,30 +134,30 @@ struct UnhandledThrowingTaskRule: Rule { print(e) } } - """), - Example(""" + """, + """ ↓Task { do { throw FooError.bar } } - """), - Example(""" + """, + """ ↓Task { throw FooError.bar } - """), - Example(""" + """, + """ ↓Task<_, _> { throw FooError.bar } - """), - Example(""" + """, + """ ↓Task { throw FooError.bar } - """), - Example(""" + """, + """ ↓Task { do { try foo() @@ -165,8 +165,8 @@ struct UnhandledThrowingTaskRule: Rule { try bar() } } - """), - Example(""" + """, + """ ↓Task { do { try foo() @@ -174,15 +174,15 @@ struct UnhandledThrowingTaskRule: Rule { throw BarError() } } - """), - Example(""" + """, + """ func doTask() { ↓Task { try await someThrowingFunction() } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededEscapingRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededEscapingRuleExamples.swift index 66de6e14ec..1e1db13cb7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededEscapingRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededEscapingRuleExamples.swift @@ -136,99 +136,99 @@ struct UnneededEscapingRuleExamples { """), ] - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ func f(c: ↓@escaping () -> Int) { print(c()) } - """), - Example(""" + """, + """ func forEach(action: ↓@escaping (Int) -> Void) { for i in 0..<10 { action(i) } } - """), - Example(""" + """, + """ func process(completion: ↓@escaping () -> Void) { completion() } - """), - Example(""" + """, + """ func apply(_ transform: ↓@escaping (Int) -> Int) -> Int { return transform(5) } - """), - Example(""" + """, + """ func optional(completion: (↓@escaping () -> Void)?) { completion?() } - """), - Example(""" + """, + """ func multiple(first: ↓@escaping () -> Void, second: ↓@escaping () -> Void) { first() second() } - """), - Example(""" + """, + """ subscript(transform: ↓@escaping (Int) -> String) -> String { transform(42) } - """), - Example(""" + """, + """ func assignToLocal(completion: ↓@escaping () -> Void) { let local = completion local() } - """), - Example(""" + """, + """ func assignToLocal(completion: ↓@escaping () -> Void) { let (local, _) = (completion, 17) local() } - """), - Example(""" + """, + """ func reassignLocal(completion: ↓@escaping () -> Void) { var local = { print(\"initial\") } local = completion local() } - """), - Example(""" + """, + """ func assignToLocal(completion: ↓@escaping () -> Void) { _ = completion } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ func forEach(action: ↓@escaping (Int) -> Void) { for i in 0..<10 { action(i) } } - """): Example(""" + """: """ func forEach(action: (Int) -> Void) { for i in 0..<10 { action(i) } } - """), - Example(""" + """, + """ func process(completion: ↓@escaping () -> Void) { completion() } - """): Example(""" + """: """ func process(completion: () -> Void) { completion() } - """), - Example(""" + """, + """ subscript(transform: ↓@escaping (Int) -> String) -> String { transform(42) } - """): Example(""" + """: """ subscript(transform: (Int) -> String) -> String { transform(42) } - """), - Example(""" + """, + """ func f(c: ↓@escaping() -> Void) { c() } - """): Example(""" + """: """ func f(c: () -> Void) { c() } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededOverrideRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededOverrideRuleExamples.swift index 014f29c00a..c82200cbe5 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededOverrideRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededOverrideRuleExamples.swift @@ -146,82 +146,82 @@ struct UnneededOverrideRuleExamples { """, configuration: ["excluded_methods": ["setUp"]]), ] - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class Foo { ↓override func bar() { super.bar() } } - """), - Example(""" + """, + """ class Foo { ↓override func bar() { return super.bar() } } - """), - Example(""" + """, + """ class Foo { ↓override func bar() { super.bar() // comments don't affect this } } - """), - Example(""" + """, + """ class Foo { ↓override func bar() async { await super.bar() } } - """), - Example(""" + """, + """ class Foo { ↓override func bar() throws { try super.bar() // comments don't affect this } } - """), - Example(""" + """, + """ class Foo { ↓override func bar(arg: Bool) throws { try super.bar(arg: arg) } } - """), - Example(""" + """, + """ class Foo { ↓override func bar(animated: Bool, completion: () -> Void) { super.bar(animated: animated, completion: completion) } } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ class Foo { ↓override func bar(animated: Bool, completion: () -> Void) { super.bar(animated: animated, completion: completion) } } - """): Example(""" + """: """ class Foo { } - """), - Example(""" + """, + """ class Foo { ↓override func bar() { super.bar() } } - """): Example(""" + """: """ class Foo { } - """), - Example(""" + """, + """ class Foo { ↓override func bar() { super.bar() @@ -230,27 +230,27 @@ struct UnneededOverrideRuleExamples { // This is another function func baz() {} } - """): Example(""" + """: """ class Foo { // This is another function func baz() {} } - """), + """, // Nothing happens to initializers by default. - Example(""" + """ class Foo { ↓override func foo() { super.foo() } override init(i: Int) { super.init(i: i) } } - """): Example(""" + """: """ class Foo { override init(i: Int) { super.init(i: i) } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededThrowsRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededThrowsRuleExamples.swift index 1d6b6461e0..de47e098f5 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededThrowsRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnneededThrowsRuleExamples.swift @@ -1,64 +1,64 @@ // swiftlint:disable file_length struct UnneededThrowsRuleExamples { // swiftlint:disable:this type_body_length - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ func foo() throws { try bar() } - """), - Example(""" + """, + """ func foo() throws { throw Example.failure } - """), - Example(""" + """, + """ func foo() throws(Example) { throw Example.failure } - """), - Example(""" + """, + """ func foo(_ bar: () throws -> T) rethrows -> Int { try items.map { try bar() } } - """), - Example(""" + """, + """ func foo() { func bar() throws { try baz() } try? bar() } - """), - Example(""" + """, + """ protocol Foo { func bar() throws } - """), - Example(""" + """, + """ func foo() throws { guard false else { throw Example.failure } } - """), - Example(""" + """, + """ func foo() throws { do { try bar() } catch { throw Example.failure } } - """), - Example(""" + """, + """ func foo() throws { do { try bar() } catch { try baz() } } - """), - Example(""" + """, + """ func foo() throws { do { throw Example.failure @@ -70,23 +70,23 @@ struct UnneededThrowsRuleExamples { // swiftlint:disable:this type_body_length } } } - """), - Example(""" + """, + """ func foo() throws { switch bar { case 1: break default: try bar() } } - """), - Example(""" + """, + """ var foo: Int { get throws { try bar } } - """), - Example(""" + """, + """ func foo() throws { let bar = Bar() @@ -94,39 +94,39 @@ struct UnneededThrowsRuleExamples { // swiftlint:disable:this type_body_length throw Example.failure } } - """), - Example(""" + """, + """ func foo() throws -> Bar? { Bar(try baz()) } - """), - Example(""" + """, + """ typealias Foo = () throws -> Void - """), - Example(""" + """, + """ enum Foo { case foo case bar(() throws -> Void) } - """), - Example(""" + """, + """ func foo() async throws { for try await item in items {} } - """), - Example(""" + """, + """ let foo: () throws -> Void - """), - Example(""" + """, + """ let foo: @Sendable () throws -> Void - """), - Example(""" + """, + """ let foo: (() throws -> Void)? - """), - Example(""" + """, + """ func foo(_ bar: () throws -> Void = {}) {} - """), - Example(""" + """, + """ func foo() async throws { func foo() {} for _ in 0.. Void> = S()"), - Example("let foo: (() throws -> Void, Int) = ({}, 1)"), - Example("let foo: (Int, () throws -> Void) = (1, {})"), - Example("let foo: (Int, Int, () throws -> Void) = (1, 1, {})"), - Example("let foo: () throws -> Void = { try bar() }"), - Example("let foo: () throws -> Void = bar"), - Example("var foo: () throws -> Void = {}"), - Example("let x = { () throws -> Void in try baz() }"), - Example(""" + """, + "let s: S<() throws -> Void> = S()", + "let foo: (() throws -> Void, Int) = ({}, 1)", + "let foo: (Int, () throws -> Void) = (1, {})", + "let foo: (Int, Int, () throws -> Void) = (1, 1, {})", + "let foo: () throws -> Void = { try bar() }", + "let foo: () throws -> Void = bar", + "var foo: () throws -> Void = {}", + "let x = { () throws -> Void in try baz() }", + """ func c() throws { b(text: try a()) { print("") } } - """), - Example(""" + """, + """ func c() throws { b(text: try a()) } - """), - Example(""" + """, + """ func c() throws { [try f()].map { $0 } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example("func foo() ↓throws {}"), - Example("let foo: () ↓throws -> Void = {}"), - Example("let foo: (() ↓throws -> Void) = {}"), - Example("let foo: (() ↓throws -> Void)? = {}"), - Example("let foo: @Sendable () ↓throws -> Void = {}"), - Example("func foo(bar: () throws -> Void) ↓rethrows {}"), - Example("init() ↓throws {}"), - Example(""" + static let triggeringExamples = #examples([ + "func foo() ↓throws {}", + "let foo: () ↓throws -> Void = {}", + "let foo: (() ↓throws -> Void) = {}", + "let foo: (() ↓throws -> Void)? = {}", + "let foo: @Sendable () ↓throws -> Void = {}", + "func foo(bar: () throws -> Void) ↓rethrows {}", + "init() ↓throws {}", + """ func foo() ↓throws { bar() } - """), - Example(""" + """, + """ func foo() ↓throws(Example) { bar() } - """), - Example(""" + """, + """ func foo() { func bar() ↓throws {} bar() } - """), - Example(""" + """, + """ func foo() { func bar() ↓throws { baz() } bar() } - """), - Example(""" + """, + """ func foo() { func bar() ↓throws { baz() } try? bar() } - """), - Example(""" + """, + """ func foo() ↓throws { func bar() ↓throws { baz() } } - """), - Example(""" + """, + """ func foo() ↓throws { do { try bar() } catch {} } - """), - Example(""" + """, + """ func foo() ↓throws { do {} catch {} } - """), - Example(""" + """, + """ func foo() ↓throws(Example) { do {} catch {} } - """), - Example(""" + """, + """ func foo() { do { func bar() ↓throws {} try bar() } catch {} } - """), - Example(""" + """, + """ func foo() ↓throws { do { try bar() @@ -254,8 +254,8 @@ struct UnneededThrowsRuleExamples { // swiftlint:disable:this type_body_length try baz() } catch {} } - """), - Example(""" + """, + """ func foo() ↓throws { do { try bar() @@ -265,8 +265,8 @@ struct UnneededThrowsRuleExamples { // swiftlint:disable:this type_body_length } catch {} } } - """), - Example(""" + """, + """ func foo() ↓throws { do { try bar() @@ -278,140 +278,140 @@ struct UnneededThrowsRuleExamples { // swiftlint:disable:this type_body_length } catch {} } } - """), - Example(""" + """, + """ func foo() ↓throws { switch bar { case 1: break default: break } } - """), - Example(""" + """, + """ func foo() ↓throws { _ = try? bar() } - """), - Example(""" + """, + """ func foo() ↓throws { Task { try bar() } } - """), - Example(""" + """, + """ func foo() throws { try bar() Task { func baz() ↓throws {} } } - """), - Example(""" + """, + """ var foo: Int { get ↓throws { 0 } } - """), - Example(""" + """, + """ func foo() ↓throws { do { try bar() } catch Example.failure {} catch is SomeError {} catch {} } - """), - Example(""" + """, + """ func foo() ↓throws { bar(1) { try baz() } } - """), - Example("let x = { () ↓throws -> Void in baz() }"), - Example(""" + """, + "let x = { () ↓throws -> Void in baz() }", + """ func c() { b { (n: String) ↓throws -> String in n } d: { try foo() } } - """), - ] + """, + ]) - static let corrections = [ - Example("func foo() ↓throws {}"): Example("func foo() {}"), - Example("init() ↓throws {}"): Example("init() {}"), - Example(""" + static let corrections = #examplesDictionary([ + "func foo() ↓throws {}": "func foo() {}", + "init() ↓throws {}": "init() {}", + """ func foo() { func bar() ↓throws {} bar() } - """): Example(""" + """: """ func foo() { func bar() {} bar() } - """), - Example(""" + """, + """ var foo: Int { get ↓throws { 0 } } - """): Example(""" + """: """ var foo: Int { get { 0 } } - """), - Example(""" + """, + """ var foo: Int { get ↓throws(Example) { 0 } } - """): Example(""" + """: """ var foo: Int { get { 0 } } - """), - Example(""" + """, + """ let foo: () ↓throws -> Void = {} - """): Example(""" + """: """ let foo: () -> Void = {} - """), - Example(""" + """, + """ let foo: () ↓throws(Example) -> Void = {} - """): Example(""" + """: """ let foo: () -> Void = {} - """), - Example(""" + """, + """ func foo() ↓throws { do {} catch {} } - """): Example(""" + """: """ func foo() { do {} catch {} } - """), - Example(""" + """, + """ func foo() ↓throws(Example) { do {} catch {} } - """): Example(""" + """: """ func foo() { do {} catch {} } - """), - Example("func f() ↓throws /* comment */ {}"): Example("func f() /* comment */ {}"), - Example("func f() /* comment */ ↓throws /* comment */ {}"): Example("func f() /* comment */ /* comment */ {}"), - Example("let foo: @Sendable () ↓throws -> Void = {}"): Example("let foo: @Sendable () -> Void = {}"), - ] + """, + "func f() ↓throws /* comment */ {}": "func f() /* comment */ {}", + "func f() /* comment */ ↓throws /* comment */ {}": "func f() /* comment */ /* comment */ {}", + "let foo: @Sendable () ↓throws -> Void = {}": "let foo: @Sendable () -> Void = {}", + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnownedVariableCaptureRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnownedVariableCaptureRule.swift index f66ce298cc..6e91146208 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnownedVariableCaptureRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnownedVariableCaptureRule.swift @@ -9,14 +9,14 @@ struct UnownedVariableCaptureRule: Rule { name: "Unowned Variable Capture", description: "Prefer capturing references as weak to avoid potential crashes", kind: .lint, - nonTriggeringExamples: [ - Example("foo { [weak self] in _ }"), - Example("foo { [weak self] param in _ }"), - Example("foo { [weak bar] in _ }"), - Example("foo { [weak bar] param in _ }"), - Example("foo { bar in _ }"), - Example("foo { $0 }"), - Example(""" + nonTriggeringExamples: #examples([ + "foo { [weak self] in _ }", + "foo { [weak self] param in _ }", + "foo { [weak bar] in _ }", + "foo { [weak bar] param in _ }", + "foo { bar in _ }", + "foo { $0 }", + """ final class First {} final class Second { unowned var value: First @@ -24,13 +24,13 @@ struct UnownedVariableCaptureRule: Rule { self.value = value } } - """), - ], - triggeringExamples: [ - Example("foo { [↓unowned self] in _ }"), - Example("foo { [↓unowned bar] in _ }"), - Example("foo { [bar, ↓unowned self] in _ }"), - ] + """, + ]), + triggeringExamples: #examples([ + "foo { [↓unowned self] in _ }", + "foo { [↓unowned bar] in _ }", + "foo { [bar, ↓unowned self] in _ }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedClosureParameterRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedClosureParameterRuleExamples.swift index cd76a55d37..214d567071 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedClosureParameterRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedClosureParameterRuleExamples.swift @@ -1,141 +1,141 @@ enum UnusedClosureParameterRuleExamples { - static let nonTriggering = [ - Example("[1, 2].map { $0 + 1 }"), - Example("[1, 2].map({ $0 + 1 })"), - Example("[1, 2].map { number in\n number + 1 \n}"), - Example("[1, 2].map { _ in\n 3 \n}"), - Example("[1, 2].something { number, idx in\n return number * idx\n}"), - Example("let isEmpty = [1, 2].isEmpty()"), - Example("violations.sorted(by: { lhs, rhs in \n return lhs.location > rhs.location\n})"), - Example(""" + static let nonTriggering = #examples([ + "[1, 2].map { $0 + 1 }", + "[1, 2].map({ $0 + 1 })", + "[1, 2].map { number in\n number + 1 \n}", + "[1, 2].map { _ in\n 3 \n}", + "[1, 2].something { number, idx in\n return number * idx\n}", + "let isEmpty = [1, 2].isEmpty()", + "violations.sorted(by: { lhs, rhs in \n return lhs.location > rhs.location\n})", + """ rlmConfiguration.migrationBlock.map { rlmMigration in return { migration, schemaVersion in rlmMigration(migration.rlmMigration, schemaVersion) } } - """), - Example(""" + """, + """ genericsFunc { (a: Type, b) in a + b } - """), - Example(""" + """, + """ var label: UILabel = { (lbl: UILabel) -> UILabel in lbl.backgroundColor = .red return lbl }(UILabel()) - """), - Example(""" + """, + """ hoge(arg: num) { num in return num } - """), - Example(""" + """, + """ ({ (manager: FileManager) in print(manager) })(FileManager.default) - """), - Example(""" + """, + """ withPostSideEffect { input in if true { print("\\(input)") } } - """), - Example(""" + """, + """ viewModel?.profileImage.didSet(weak: self) { (self, profileImage) in self.profileImageView.image = profileImage } - """), - Example(""" + """, + """ let failure: Failure = { task, error in observer.sendFailed(error, task) } - """), - Example(""" + """, + """ List($names) { $name in Text(name) } - """), - Example(""" + """, + """ List($names) { $name in TextField($name) } - """), - Example(#"_ = ["a"].filter { `class` in `class`.hasPrefix("a") }"#), - Example("let closure: (Int) -> Void = { `foo` in _ = foo }"), - Example("let closure: (Int) -> Void = { foo in _ = `foo` }"), - ] + """, + #"_ = ["a"].filter { `class` in `class`.hasPrefix("a") }"#, + "let closure: (Int) -> Void = { `foo` in _ = foo }", + "let closure: (Int) -> Void = { foo in _ = `foo` }", + ]) - static let triggering = [ - Example("[1, 2].map { ↓number in\n return 3 }"), - Example("[1, 2].map { ↓number in\n return numberWithSuffix }"), - Example("[1, 2].map { ↓number in\n return 3 // number }"), - Example("[1, 2].map { ↓number in\n return 3 \"number\" }"), - Example("[1, 2].something { number, ↓idx in\n return number }"), - Example("genericsFunc { (↓number: TypeA, idx: TypeB) in return idx }"), - Example("let c: (Int) -> Void = { foo in _ = .foo }"), - Example(""" + static let triggering = #examples([ + "[1, 2].map { ↓number in\n return 3 }", + "[1, 2].map { ↓number in\n return numberWithSuffix }", + "[1, 2].map { ↓number in\n return 3 // number }", + "[1, 2].map { ↓number in\n return 3 \"number\" }", + "[1, 2].something { number, ↓idx in\n return number }", + "genericsFunc { (↓number: TypeA, idx: TypeB) in return idx }", + "let c: (Int) -> Void = { foo in _ = .foo }", + """ hoge(arg: num) { ↓num in } - """), - Example("fooFunc { ↓아 in }"), - Example("func foo () {\n bar { ↓number in return 3 }"), - Example(""" + """, + "fooFunc { ↓아 in }", + "func foo () {\n bar { ↓number in return 3 }", + """ viewModel?.profileImage.didSet(weak: self) { (↓self, profileImage) in profileImageView.image = profileImage } - """), - Example(""" + """, + """ let failure: Failure = { ↓task, error in observer.sendFailed(error) } - """), - Example(""" + """, + """ List($names) { ↓$name in Text("Foo") } - """), - Example(""" + """, + """ let class1 = "a" _ = ["a"].filter { ↓`class` in `class1`.hasPrefix("a") } - """), - ] + """, + ]) - static let corrections = [ - Example("[1, 2].map { ↓number in return 3 }"): - Example("[1, 2].map { _ in return 3 }"), - Example("[1, 2].map { ↓number in return numberWithSuffix }"): - Example("[1, 2].map { _ in return numberWithSuffix }"), - Example("[1, 2].map { ↓number in return 3 // number }"): - Example("[1, 2].map { _ in return 3 // number }"), - Example("[1, 2].something { number, ↓idx in return number }"): - Example("[1, 2].something { number, _ in return number }"), - Example("genericsFunc(closure: { (↓int: Int) -> Void in // do something })"): - Example("genericsFunc(closure: { (_: Int) -> Void in // do something })"), - Example("genericsFunc { (↓a, ↓b: Type) -> Void in }"): - Example("genericsFunc { (_, _: Type) -> Void in }"), - Example("genericsFunc { (↓a: Type, ↓b: Type) -> Void in }"): - Example("genericsFunc { (_: Type, _: Type) -> Void in }"), - Example("genericsFunc { (↓a: Type, ↓b) -> Void in }"): - Example("genericsFunc { (_: Type, _) -> Void in }"), - Example("genericsFunc { (a: Type, ↓b) -> Void in return a }"): - Example("genericsFunc { (a: Type, _) -> Void in return a }"), - Example("hoge(arg: num) { ↓num in }"): - Example("hoge(arg: num) { _ in }"), - Example(""" + static let corrections = #examplesDictionary([ + "[1, 2].map { ↓number in return 3 }": + "[1, 2].map { _ in return 3 }", + "[1, 2].map { ↓number in return numberWithSuffix }": + "[1, 2].map { _ in return numberWithSuffix }", + "[1, 2].map { ↓number in return 3 // number }": + "[1, 2].map { _ in return 3 // number }", + "[1, 2].something { number, ↓idx in return number }": + "[1, 2].something { number, _ in return number }", + "genericsFunc(closure: { (↓int: Int) -> Void in // do something })": + "genericsFunc(closure: { (_: Int) -> Void in // do something })", + "genericsFunc { (↓a, ↓b: Type) -> Void in }": + "genericsFunc { (_, _: Type) -> Void in }", + "genericsFunc { (↓a: Type, ↓b: Type) -> Void in }": + "genericsFunc { (_: Type, _: Type) -> Void in }", + "genericsFunc { (↓a: Type, ↓b) -> Void in }": + "genericsFunc { (_: Type, _) -> Void in }", + "genericsFunc { (a: Type, ↓b) -> Void in return a }": + "genericsFunc { (a: Type, _) -> Void in return a }", + "hoge(arg: num) { ↓num in }": + "hoge(arg: num) { _ in }", + """ func foo () { bar { ↓number in return 3 } } - """): - Example(""" + """: + """ func foo () { bar { _ in return 3 } } - """), - Example(""" + """, + """ class C { #if true func f() { @@ -145,8 +145,8 @@ enum UnusedClosureParameterRuleExamples { } #endif } - """): - Example(""" + """: + """ class C { #if true func f() { @@ -156,16 +156,16 @@ enum UnusedClosureParameterRuleExamples { } #endif } - """), - Example(""" + """, + """ let failure: Failure = { ↓task, error in observer.sendFailed(error) } - """): - Example(""" + """: + """ let failure: Failure = { _, error in observer.sendFailed(error) } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedControlFlowLabelRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedControlFlowLabelRule.swift index 90e6b03ab3..1d53132999 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedControlFlowLabelRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedControlFlowLabelRule.swift @@ -9,79 +9,79 @@ struct UnusedControlFlowLabelRule: Rule { name: "Unused Control Flow Label", description: "Unused control flow label should be removed", kind: .lint, - nonTriggeringExamples: [ - Example("loop: while true { break loop }"), - Example("loop: while true { continue loop }"), - Example("loop:\n while true { break loop }"), - Example("while true { break }"), - Example("loop: for x in array { break loop }"), - Example(""" + nonTriggeringExamples: #examples([ + "loop: while true { break loop }", + "loop: while true { continue loop }", + "loop:\n while true { break loop }", + "while true { break }", + "loop: for x in array { break loop }", + """ label: switch number { case 1: print("1") case 2: print("2") default: break label } - """), - Example(""" + """, + """ loop: repeat { if x == 10 { break loop } } while true - """), - ], - triggeringExamples: [ - Example("↓loop: while true { break }"), - Example("↓loop: while true { break loop1 }"), - Example("↓loop: while true { break outerLoop }"), - Example("↓loop: for x in array { break }"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "↓loop: while true { break }", + "↓loop: while true { break loop1 }", + "↓loop: while true { break outerLoop }", + "↓loop: for x in array { break }", + """ ↓label: switch number { case 1: print("1") case 2: print("2") default: break } - """), - Example(""" + """, + """ ↓loop: repeat { if x == 10 { break } } while true - """), - ], - corrections: [ - Example("↓loop: while true { break }"): Example("while true { break }"), - Example("↓loop: while true { break loop1 }"): Example("while true { break loop1 }"), - Example("↓loop: while true { break outerLoop }"): Example("while true { break outerLoop }"), - Example("↓loop: for x in array { break }"): Example("for x in array { break }"), - Example(""" + """, + ]), + corrections: #examplesDictionary([ + "↓loop: while true { break }": "while true { break }", + "↓loop: while true { break loop1 }": "while true { break loop1 }", + "↓loop: while true { break outerLoop }": "while true { break outerLoop }", + "↓loop: for x in array { break }": "for x in array { break }", + """ ↓label: switch number { case 1: print("1") case 2: print("2") default: break } - """): Example(""" + """: """ switch number { case 1: print("1") case 2: print("2") default: break } - """), - Example(""" + """, + """ ↓loop: repeat { if x == 10 { break } } while true - """): Example(""" + """: """ repeat { if x == 10 { break } } while true - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedDeclarationRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedDeclarationRuleExamples.swift index 393aee95f6..eaf979c639 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedDeclarationRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedDeclarationRuleExamples.swift @@ -1,10 +1,10 @@ struct UnusedDeclarationRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ let kConstant = 0 _ = kConstant - """), - Example(""" + """, + """ enum Change { case insert(T) case delete(T) @@ -24,8 +24,8 @@ struct UnusedDeclarationRuleExamples { let changes = [Change.insert(0), .delete(0)] _ = changes.deletes() - """), - Example(""" + """, + """ struct Item: Codable {} struct ResponseModel: Codable { let items: [Item] @@ -36,18 +36,18 @@ struct UnusedDeclarationRuleExamples { } _ = ResponseModel(items: [Item()]).items - """), - Example(""" + """, + """ class ResponseModel { @objc func foo() { } } _ = ResponseModel() - """), - Example(""" + """, + """ public func foo() {} - """), - Example(""" + """, + """ protocol Foo {} extension Foo { @@ -56,21 +56,21 @@ struct UnusedDeclarationRuleExamples { struct MyStruct: Foo {} MyStruct().bar() - """), - Example(""" + """, + """ import XCTest class MyTests: XCTestCase { func testExample() {} } - """), - Example(""" + """, + """ import XCTest open class BestTestCase: XCTestCase {} class MyTests: BestTestCase { func testExample() {} } - """), - Example(""" + """, + """ struct S { var i: Int? = nil func f() { @@ -78,8 +78,8 @@ struct UnusedDeclarationRuleExamples { } } S().f() - """), - Example(""" + """, + """ enum Component { case string(StaticString) indirect case array([Component]) @@ -136,8 +136,8 @@ struct UnusedDeclarationRuleExamples { acceptComponentBuilder { "hello" } - """), - ] + platformSpecificNonTriggeringExamples + """, + ]) + platformSpecificNonTriggeringExamples static let triggeringExamples = [ Example(""" @@ -226,8 +226,8 @@ struct UnusedDeclarationRuleExamples { } + platformSpecificTriggeringExamples #if os(macOS) - private static let platformSpecificNonTriggeringExamples = [ - Example(""" + private static let platformSpecificNonTriggeringExamples = #examples([ + """ import Cocoa @NSApplicationMain @@ -235,22 +235,22 @@ struct UnusedDeclarationRuleExamples { func applicationWillFinishLaunching(_ notification: Notification) {} func applicationWillBecomeActive(_ notification: Notification) {} } - """), - Example(""" + """, + """ import Foundation public final class Foo: NSObject { @IBAction private func foo() {} } - """), - Example(""" + """, + """ import Foundation public final class Foo: NSObject { @objc func foo() {} } - """), - Example(""" + """, + """ import Foundation public final class Foo: NSObject { @@ -259,8 +259,8 @@ struct UnusedDeclarationRuleExamples { get { return self.backgroundView.innerPaddingWidth } } } - """), - Example(""" + """, + """ import Foundation public final class Foo: NSObject { @@ -277,11 +277,11 @@ struct UnusedDeclarationRuleExamples { didSet { print("didSet") } } } - """), - ] + """, + ]) - private static let platformSpecificTriggeringExamples = [ - Example(""" + private static let platformSpecificTriggeringExamples = #examples([ + """ import Cocoa @NSApplicationMain @@ -289,38 +289,38 @@ struct UnusedDeclarationRuleExamples { func ↓appWillFinishLaunching(_ notification: Notification) {} func applicationWillBecomeActive(_ notification: Notification) {} } - """), - Example(""" + """, + """ import Cocoa final class ↓AppDelegate: NSObject, NSApplicationDelegate { func applicationWillFinishLaunching(_ notification: Notification) {} func applicationWillBecomeActive(_ notification: Notification) {} } - """), - Example(""" + """, + """ import Foundation public final class Foo: NSObject { @IBOutlet var ↓bar: NSObject! } - """), - Example(""" + """, + """ import Foundation public final class Foo: NSObject { @IBInspectable var ↓bar: String! } - """), - Example(""" + """, + """ import Foundation final class Foo: NSObject {} final class ↓Bar { var ↓foo = Foo() } - """), - ] + """, + ]) #else private static let platformSpecificNonTriggeringExamples = [Example]() private static let platformSpecificTriggeringExamples = [Example]() diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedImportRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedImportRuleExamples.swift index 62287de981..0efed16672 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedImportRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedImportRuleExamples.swift @@ -54,15 +54,15 @@ struct UnusedImportRuleExamples { ], excludeFromDocumentation: true), ] - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ ↓import Dispatch struct A { static func dispatchMain() {} } A.dispatchMain() - """), - Example(""" + """, + """ ↓import Foundation // This is unused struct A { static func dispatchMain() {} @@ -70,27 +70,27 @@ struct UnusedImportRuleExamples { A.dispatchMain() ↓import Dispatch - """), - Example(""" + """, + """ ↓import Foundation dispatchMain() - """), - Example(""" + """, + """ ↓import Foundation // @objc class A {} - """), - Example(""" + """, + """ ↓public import Foundation import UnknownModule func foo(error: Swift.Error) {} - """), - Example(""" + """, + """ ↓internal import Swift ↓private import SwiftShims func foo(error: Swift.Error) {} - """), - ] + """, + ]) static let corrections = [ Example(""" diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedParameterRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedParameterRule.swift index f2fd8b5363..363b195677 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedParameterRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedParameterRule.swift @@ -68,24 +68,24 @@ struct UnusedParameterRule: Rule { func f(_a: Int) {} """, configuration: allowUnderscorePrefixedNames), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ func f(↓a: Int) {} - """), - Example(""" + """, + """ func f(↓_a: Int) {} - """), - Example(""" + """, + """ func f(↓a: Int, b ↓c: String) {} - """), - Example(""" + """, + """ func f(↓a: Int, b ↓c: String) { func g(a: Int, ↓b: Double) { _ = a } } - """), - Example(""" + """, + """ struct S { let a: Int @@ -94,16 +94,16 @@ struct UnusedParameterRule: Rule { self.a = f(a: a, b: 0) } } - """), - Example(""" + """, + """ struct S { subscript(a: Int, ↓b: Int) { func f(↓a: Int, b: Int) -> Int { b } return f(a: a, b: 0) } } - """), - Example(""" + """, + """ func f(↓a: Int, ↓b: Int, c: Int) -> Int { struct S { let b = 1 @@ -111,31 +111,31 @@ struct UnusedParameterRule: Rule { } return S().f(a: c) } - """), - Example(""" + """, + """ func f(↓a: Int, c: String) { let a = 1 return a + c } - """), - ], - corrections: [ - Example(""" + """, + ]), + corrections: #examplesDictionary([ + """ func f(a: Int) {} - """): Example(""" + """: """ func f(a _: Int) {} - """), - Example(""" + """, + """ func f(a b: Int) {} - """): Example(""" + """: """ func f(a _: Int) {} - """), - Example(""" + """, + """ func f(_ a: Int) {} - """): Example(""" + """: """ func f(_: Int) {} - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedSetterValueRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedSetterValueRule.swift index c19016d4ea..8eb197815a 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedSetterValueRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/UnusedSetterValueRule.swift @@ -63,8 +63,8 @@ struct UnusedSetterValueRule: Rule { } """, excludeFromDocumentation: true), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ var aValue: String { get { return Persister.shared.aValue @@ -73,8 +73,8 @@ struct UnusedSetterValueRule: Rule { Persister.shared.aValue = aValue } } - """), - Example(""" + """, + """ var aValue: String { ↓set { Persister.shared.aValue = aValue @@ -83,8 +83,8 @@ struct UnusedSetterValueRule: Rule { return Persister.shared.aValue } } - """), - Example(""" + """, + """ var aValue: String { get { return Persister.shared.aValue @@ -93,8 +93,8 @@ struct UnusedSetterValueRule: Rule { Persister.shared.aValue = aValue } } - """), - Example(""" + """, + """ var aValue: String { get { let newValue = Persister.shared.aValue @@ -104,8 +104,8 @@ struct UnusedSetterValueRule: Rule { Persister.shared.aValue = aValue } } - """), - Example(""" + """, + """ var aValue: String { get { return Persister.shared.aValue @@ -114,8 +114,8 @@ struct UnusedSetterValueRule: Rule { Persister.shared.aValue = aValue } } - """), - Example(""" + """, + """ override var aValue: String { get { return Persister.shared.aValue @@ -124,8 +124,8 @@ struct UnusedSetterValueRule: Rule { Persister.shared.aValue = aValue } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/ValidIBInspectableRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/ValidIBInspectableRule.swift index 922d4034af..16450ed756 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/ValidIBInspectableRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/ValidIBInspectableRule.swift @@ -11,43 +11,43 @@ struct ValidIBInspectableRule: Rule { @IBInspectable should be applied to variables only, have its type explicit and be of a supported type """, kind: .lint, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class Foo { @IBInspectable private var x: Int } - """), - Example(""" + """, + """ class Foo { @IBInspectable private var x: String? } - """), - Example(""" + """, + """ class Foo { @IBInspectable private var x: String! } - """), - Example(""" + """, + """ class Foo { @IBInspectable private var count: Int = 0 } - """), - Example(""" + """, + """ class Foo { private var notInspectable = 0 } - """), - Example(""" + """, + """ class Foo { private let notInspectable: Int } - """), - Example(""" + """, + """ class Foo { private let notInspectable: UInt8 } - """), - Example(""" + """, + """ extension Foo { @IBInspectable var color: UIColor { set { @@ -59,8 +59,8 @@ struct ValidIBInspectableRule: Rule { } } } - """), - Example(""" + """, + """ class Foo { @IBInspectable var borderColor: UIColor? = nil { didSet { @@ -68,45 +68,45 @@ struct ValidIBInspectableRule: Rule { } } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ class Foo { @IBInspectable private ↓let count: Int } - """), - Example(""" + """, + """ class Foo { @IBInspectable private ↓var insets: UIEdgeInsets } - """), - Example(""" + """, + """ class Foo { @IBInspectable private ↓var count = 0 } - """), - Example(""" + """, + """ class Foo { @IBInspectable private ↓var count: Int? } - """), - Example(""" + """, + """ class Foo { @IBInspectable private ↓var count: Int! } - """), - Example(""" + """, + """ class Foo { @IBInspectable private ↓var count: Optional } - """), - Example(""" + """, + """ class Foo { @IBInspectable private ↓var x: Optional } - """), - ] + """, + ]) ) fileprivate static let supportedTypes: Set = { diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/WeakDelegateRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/WeakDelegateRule.swift index 2c8c6bd5a2..afa70907c8 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/WeakDelegateRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/WeakDelegateRule.swift @@ -52,18 +52,18 @@ struct WeakDelegateRule: Rule { """, excludeFromDocumentation: true), Example("private var appDelegate: String?", excludeFromDocumentation: true), ], - triggeringExamples: [ - Example("class Foo {\n ↓var delegate: SomeProtocol?\n}"), - Example("class Foo {\n ↓var scrollDelegate: ScrollDelegate?\n}"), - Example(""" + triggeringExamples: #examples([ + "class Foo {\n ↓var delegate: SomeProtocol?\n}", + "class Foo {\n ↓var scrollDelegate: ScrollDelegate?\n}", + """ class Foo { ↓var delegate: SomeProtocol? { didSet { print("Updated delegate") } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Lint/YodaConditionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Lint/YodaConditionRule.swift index 546620edc3..49dd250fa9 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Lint/YodaConditionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Lint/YodaConditionRule.swift @@ -23,17 +23,17 @@ struct YodaConditionRule: Rule { Example("if true {}", excludeFromDocumentation: true), Example("if true == false || b, 2 != 3 {}", excludeFromDocumentation: true), ], - triggeringExamples: [ - Example("if ↓42 == foo {}"), - Example("if ↓42.42 >= foo {}"), - Example("guard ↓42 <= foo else { return }"), - Example("guard ↓\"str str\" != foo else { return }"), - Example("while ↓10 > foo { }"), - Example("while ↓1 < foo { }"), - Example("if ↓nil == foo {}"), - Example("while ↓1 > i + 5 {}"), - Example("if ↓200 <= i && i <= 299 || ↓600 <= i {}"), - ]) + triggeringExamples: #examples([ + "if ↓42 == foo {}", + "if ↓42.42 >= foo {}", + "guard ↓42 <= foo else { return }", + "guard ↓\"str str\" != foo else { return }", + "while ↓10 > foo { }", + "while ↓1 < foo { }", + "if ↓nil == foo {}", + "while ↓1 > i + 5 {}", + "if ↓200 <= i && i <= 299 || ↓600 <= i {}", + ])) } private extension YodaConditionRule { diff --git a/Source/SwiftLintBuiltInRules/Rules/Metrics/CyclomaticComplexityRule.swift b/Source/SwiftLintBuiltInRules/Rules/Metrics/CyclomaticComplexityRule.swift index 7768b05b39..de2b6c20a6 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Metrics/CyclomaticComplexityRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Metrics/CyclomaticComplexityRule.swift @@ -10,16 +10,16 @@ struct CyclomaticComplexityRule: Rule { name: "Cyclomatic Complexity", description: "Complexity of function bodies should be limited.", kind: .metrics, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ func f1() { if true { for _ in 1..5 { } } if false { } } - """), - Example(""" + """, + """ func f(code: Int) -> Int { switch code { case 0: fallthrough @@ -34,18 +34,18 @@ struct CyclomaticComplexityRule: Rule { default: return 1 } } - """), - Example(""" + """, + """ func f1() { if true {}; if true {}; if true {}; if true {}; if true {}; if true {} func f2() { if true {}; if true {}; if true {}; if true {}; if true {} } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ ↓func f1() { if true { if true { @@ -67,8 +67,8 @@ struct CyclomaticComplexityRule: Rule { } } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Metrics/EnumCaseAssociatedValuesLengthRule.swift b/Source/SwiftLintBuiltInRules/Rules/Metrics/EnumCaseAssociatedValuesLengthRule.swift index db3c42d4b7..4bbcf33a46 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Metrics/EnumCaseAssociatedValuesLengthRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Metrics/EnumCaseAssociatedValuesLengthRule.swift @@ -9,32 +9,32 @@ struct EnumCaseAssociatedValuesLengthRule: Rule { name: "Enum Case Associated Values Count", description: "The number of associated values in an enum case should be low.", kind: .metrics, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum Employee { case fullTime(name: String, retirement: Date, designation: String, contactNumber: Int) case partTime(name: String, age: Int, contractEndDate: Date) } - """), - Example(""" + """, + """ enum Barcode { case upc(Int, Int, Int, Int) } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ enum Employee { case ↓fullTime(name: String, retirement: Date, age: Int, designation: String, contactNumber: Int) case ↓partTime(name: String, contractEndDate: Date, age: Int, designation: String, contactNumber: Int) } - """), - Example(""" + """, + """ enum Barcode { case ↓upc(Int, Int, Int, Int, Int, Int) } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Metrics/FunctionParameterCountRule.swift b/Source/SwiftLintBuiltInRules/Rules/Metrics/FunctionParameterCountRule.swift index 27895f1c0c..7c4b9e3dc7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Metrics/FunctionParameterCountRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Metrics/FunctionParameterCountRule.swift @@ -9,31 +9,31 @@ struct FunctionParameterCountRule: Rule { name: "Function Parameter Count", description: "Number of function parameters should be low.", kind: .metrics, - nonTriggeringExamples: [ - Example("init(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("init (a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("`init`(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("init?(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("init?(a: T, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("init?(a: T, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("func f2(p1: Int, p2: Int) { }"), - Example("func f(a: Int, b: Int, c: Int, d: Int, x: Int = 42) {}"), - Example(""" + nonTriggeringExamples: #examples([ + "init(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "init (a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "`init`(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "init?(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "init?(a: T, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "init?(a: T, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "func f2(p1: Int, p2: Int) { }", + "func f(a: Int, b: Int, c: Int, d: Int, x: Int = 42) {}", + """ func f(a: [Int], b: Int, c: Int, d: Int, f: Int) -> [Int] { let s = a.flatMap { $0 as? [String: Int] } ?? []}} - """), - Example("override func f(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - ], - triggeringExamples: [ - Example("↓func f(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("↓func initialValue(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}"), - Example("private ↓func f(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int = 2, g: Int) {}"), - Example(""" + """, + "override func f(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + ]), + triggeringExamples: #examples([ + "↓func f(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "↓func initialValue(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}", + "private ↓func f(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int = 2, g: Int) {}", + """ struct Foo { init(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {} ↓func bar(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {}} - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Metrics/NestingRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Metrics/NestingRuleExamples.swift index 17c2122514..cbf2ac0c50 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Metrics/NestingRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Metrics/NestingRuleExamples.swift @@ -105,21 +105,21 @@ internal struct NestingRuleExamples { private static let nonTriggeringProtocolExamples = detectingTypes.flatMap { type in - [ - Example(""" + #examples([ + """ \(type) Example_0 { protocol Example_1 {} } - """), - Example(""" + """, + """ var example: Int { \(type) Example_0 { protocol Example_1 {} } return 5 } - """), - Example(""" + """, + """ var example: Int = 5 { didSet { \(type) Example_0 { @@ -127,13 +127,13 @@ internal struct NestingRuleExamples { } } } - """), - Example(""" + """, + """ extension Example_0 { protocol Example_1 {} } - """), - ] + """, + ]) } private static let nonTriggeringClosureAndStatementExamples = @@ -425,15 +425,15 @@ extension NestingRuleExamples { private static let triggeringProtocolExamples = detectingTypes.flatMap { type in - [ - Example(""" + #examples([ + """ \(type) Example_0 { \(type) Example_1 { ↓protocol Example_2 {} } } - """), - Example(""" + """, + """ var example: Int { \(type) Example_0 { \(type) Example_1 { @@ -442,8 +442,8 @@ extension NestingRuleExamples { } return 5 } - """), - Example(""" + """, + """ var example: Int = 5 { didSet { \(type) Example_0 { @@ -453,15 +453,15 @@ extension NestingRuleExamples { } } } - """), - Example(""" + """, + """ extension Example_0 { \(type) Example_1 { ↓protocol Example_2 {} } } - """), - ] + """, + ]) } private static let triggeringMixedExamples = @@ -518,8 +518,8 @@ extension NestingRuleExamples { ] } - private static let triggeringExamplesCodingKeys: [Example] = [ - Example(""" + private static let triggeringExamplesCodingKeys: [Example] = #examples([ + """ struct Outer { struct Inner { ↓enum CodingKeys: String, CodingKey { @@ -527,8 +527,8 @@ extension NestingRuleExamples { } } } - """), - ] + """, + ]) private static let triggeringExamplesIgnoreCodingKeys: [Example] = [ Example( diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterCountRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterCountRule.swift index e6970385c4..7bb6a04c54 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterCountRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterCountRule.swift @@ -10,22 +10,22 @@ struct ContainsOverFilterCountRule: Rule { description: "Prefer `contains` over comparing `filter(where:).count` to 0", kind: .performance, nonTriggeringExamples: [">", "==", "!="].flatMap { operation in - [ - Example("let result = myList.filter(where: { $0 % 2 == 0 }).count \(operation) 1"), - Example("let result = myList.filter { $0 % 2 == 0 }.count \(operation) 1"), - Example("let result = myList.filter(where: { $0 % 2 == 0 }).count \(operation) 01"), - ] - } + [ - Example("let result = myList.contains(where: { $0 % 2 == 0 })"), - Example("let result = !myList.contains(where: { $0 % 2 == 0 })"), - Example("let result = myList.contains(10)"), - ], + #examples([ + "let result = myList.filter(where: { $0 % 2 == 0 }).count \(operation) 1", + "let result = myList.filter { $0 % 2 == 0 }.count \(operation) 1", + "let result = myList.filter(where: { $0 % 2 == 0 }).count \(operation) 01", + ]) + } + #examples([ + "let result = myList.contains(where: { $0 % 2 == 0 })", + "let result = !myList.contains(where: { $0 % 2 == 0 })", + "let result = myList.contains(10)", + ]), triggeringExamples: [">", "==", "!="].flatMap { operation in - [ - Example("let result = ↓myList.filter(where: { $0 % 2 == 0 }).count \(operation) 0"), - Example("let result = ↓myList.filter { $0 % 2 == 0 }.count \(operation) 0"), - Example("let result = ↓myList.filter(where: someFunction).count \(operation) 0"), - ] + #examples([ + "let result = ↓myList.filter(where: { $0 % 2 == 0 }).count \(operation) 0", + "let result = ↓myList.filter { $0 % 2 == 0 }.count \(operation) 0", + "let result = ↓myList.filter(where: someFunction).count \(operation) 0", + ]) } ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterIsEmptyRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterIsEmptyRule.swift index 730196d42c..96751c455b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterIsEmptyRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFilterIsEmptyRule.swift @@ -10,21 +10,21 @@ struct ContainsOverFilterIsEmptyRule: Rule { description: "Prefer `contains` over using `filter(where:).isEmpty`", kind: .performance, nonTriggeringExamples: [">", "==", "!="].flatMap { operation in - [ - Example("let result = myList.filter(where: { $0 % 2 == 0 }).count \(operation) 1"), - Example("let result = myList.filter { $0 % 2 == 0 }.count \(operation) 1"), - ] - } + [ - Example("let result = myList.contains(where: { $0 % 2 == 0 })"), - Example("let result = !myList.contains(where: { $0 % 2 == 0 })"), - Example("let result = myList.contains(10)"), - ], - triggeringExamples: [ - Example("let result = ↓myList.filter(where: { $0 % 2 == 0 }).isEmpty"), - Example("let result = !↓myList.filter(where: { $0 % 2 == 0 }).isEmpty"), - Example("let result = ↓myList.filter { $0 % 2 == 0 }.isEmpty"), - Example("let result = ↓myList.filter(where: someFunction).isEmpty"), - ] + #examples([ + "let result = myList.filter(where: { $0 % 2 == 0 }).count \(operation) 1", + "let result = myList.filter { $0 % 2 == 0 }.count \(operation) 1", + ]) + } + #examples([ + "let result = myList.contains(where: { $0 % 2 == 0 })", + "let result = !myList.contains(where: { $0 % 2 == 0 })", + "let result = myList.contains(10)", + ]), + triggeringExamples: #examples([ + "let result = ↓myList.filter(where: { $0 % 2 == 0 }).isEmpty", + "let result = !↓myList.filter(where: { $0 % 2 == 0 }).isEmpty", + "let result = ↓myList.filter { $0 % 2 == 0 }.isEmpty", + "let result = ↓myList.filter(where: someFunction).isEmpty", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFirstNotNilRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFirstNotNilRule.swift index 22d08b3c35..80c813b133 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFirstNotNilRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverFirstNotNilRule.swift @@ -10,21 +10,21 @@ struct ContainsOverFirstNotNilRule: Rule { description: "Prefer `contains` over `first(where:) != nil` and `firstIndex(where:) != nil`.", kind: .performance, nonTriggeringExamples: ["first", "firstIndex"].flatMap { method in - [ - Example("let \(method) = myList.\(method)(where: { $0 % 2 == 0 })"), - Example("let \(method) = myList.\(method) { $0 % 2 == 0 }"), - ] + #examples([ + "let \(method) = myList.\(method)(where: { $0 % 2 == 0 })", + "let \(method) = myList.\(method) { $0 % 2 == 0 }", + ]) }, triggeringExamples: ["first", "firstIndex"].flatMap { method in ["!=", "=="].flatMap { comparison in - [ - Example("↓myList.\(method) { $0 % 2 == 0 } \(comparison) nil"), - Example("↓myList.\(method)(where: { $0 % 2 == 0 }) \(comparison) nil"), - Example("↓myList.map { $0 + 1 }.\(method)(where: { $0 % 2 == 0 }) \(comparison) nil"), - Example("↓myList.\(method)(where: someFunction) \(comparison) nil"), - Example("↓myList.map { $0 + 1 }.\(method) { $0 % 2 == 0 } \(comparison) nil"), - Example("(↓myList.\(method) { $0 % 2 == 0 }) \(comparison) nil"), - ] + #examples([ + "↓myList.\(method) { $0 % 2 == 0 } \(comparison) nil", + "↓myList.\(method)(where: { $0 % 2 == 0 }) \(comparison) nil", + "↓myList.map { $0 + 1 }.\(method)(where: { $0 % 2 == 0 }) \(comparison) nil", + "↓myList.\(method)(where: someFunction) \(comparison) nil", + "↓myList.map { $0 + 1 }.\(method) { $0 % 2 == 0 } \(comparison) nil", + "(↓myList.\(method) { $0 % 2 == 0 }) \(comparison) nil", + ]) } } ) diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverRangeNilComparisonRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverRangeNilComparisonRule.swift index 44ffc9db21..75655e6ea9 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverRangeNilComparisonRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/ContainsOverRangeNilComparisonRule.swift @@ -9,16 +9,16 @@ struct ContainsOverRangeNilComparisonRule: Rule { name: "Contains over Range Comparison to Nil", description: "Prefer `contains` over `range(of:) != nil` and `range(of:) == nil`", kind: .performance, - nonTriggeringExamples: [ - Example("let range = myString.range(of: \"Test\")"), - Example("myString.contains(\"Test\")"), - Example("!myString.contains(\"Test\")"), - Example("resourceString.range(of: rule.regex, options: .regularExpression) != nil"), - ], + nonTriggeringExamples: #examples([ + "let range = myString.range(of: \"Test\")", + "myString.contains(\"Test\")", + "!myString.contains(\"Test\")", + "resourceString.range(of: rule.regex, options: .regularExpression) != nil", + ]), triggeringExamples: ["!=", "=="].flatMap { comparison in - [ - Example("↓myString.range(of: \"Test\") \(comparison) nil") - ] + #examples([ + "↓myString.range(of: \"Test\") \(comparison) nil" + ]) } ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCollectionLiteralRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCollectionLiteralRule.swift index a45100697b..d1ec611a69 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCollectionLiteralRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCollectionLiteralRule.swift @@ -9,22 +9,22 @@ struct EmptyCollectionLiteralRule: Rule { name: "Empty Collection Literal", description: "Prefer checking `isEmpty` over comparing collection to an empty array or dictionary literal", kind: .performance, - nonTriggeringExamples: [ - Example("myArray = []"), - Example("myArray.isEmpty"), - Example("!myArray.isEmpty"), - Example("myDict = [:]"), - ], - triggeringExamples: [ - Example("myArray↓ == []"), - Example("myArray↓ != []"), - Example("myArray↓ == [ ]"), - Example("myDict↓ == [:]"), - Example("myDict↓ != [:]"), - Example("myDict↓ == [: ]"), - Example("myDict↓ == [ :]"), - Example("myDict↓ == [ : ]"), - ] + nonTriggeringExamples: #examples([ + "myArray = []", + "myArray.isEmpty", + "!myArray.isEmpty", + "myDict = [:]", + ]), + triggeringExamples: #examples([ + "myArray↓ == []", + "myArray↓ != []", + "myArray↓ == [ ]", + "myDict↓ == [:]", + "myDict↓ != [:]", + "myDict↓ == [: ]", + "myDict↓ == [ :]", + "myDict↓ == [ : ]", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCountRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCountRule.swift index 0bf68f035a..eec76fb531 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCountRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyCountRule.swift @@ -73,40 +73,40 @@ struct EmptyCountRule: Rule { } """, excludeFromDocumentation: true), ], - corrections: [ - Example("[].↓count == 0"): - Example("[].isEmpty"), - Example("0 == [].↓count"): - Example("[].isEmpty"), - Example("[Int]().↓count == 0"): - Example("[Int]().isEmpty"), - Example("0 == [Int]().↓count"): - Example("[Int]().isEmpty"), - Example("[Int]().↓count==0"): - Example("[Int]().isEmpty"), - Example("[Int]().↓count > 0"): - Example("![Int]().isEmpty"), - Example("[Int]().↓count != 0"): - Example("![Int]().isEmpty"), - Example("[Int]().↓count == 0x0"): - Example("[Int]().isEmpty"), - Example("[Int]().↓count == 0x00_00"): - Example("[Int]().isEmpty"), - Example("[Int]().↓count == 0b00"): - Example("[Int]().isEmpty"), - Example("[Int]().↓count == 0o00"): - Example("[Int]().isEmpty"), - Example("↓count == 0"): - Example("isEmpty"), - Example("↓count == 0 && [Int]().↓count == 0o00"): - Example("isEmpty && [Int]().isEmpty"), - Example("[Int]().count != 3 && [Int]().↓count != 0 || ↓count == 0 && [Int]().count > 2"): - Example("[Int]().count != 3 && ![Int]().isEmpty || isEmpty && [Int]().count > 2"), - Example("#ExampleMacro { $0.list.↓count == 0 }"): - Example("#ExampleMacro { $0.list.isEmpty }"), - Example("#Rule(param1: \"param1\") { return $0.donations.↓count == 0 }"): - Example("#Rule(param1: \"param1\") { return $0.donations.isEmpty }"), - ] + corrections: #examplesDictionary([ + "[].↓count == 0": + "[].isEmpty", + "0 == [].↓count": + "[].isEmpty", + "[Int]().↓count == 0": + "[Int]().isEmpty", + "0 == [Int]().↓count": + "[Int]().isEmpty", + "[Int]().↓count==0": + "[Int]().isEmpty", + "[Int]().↓count > 0": + "![Int]().isEmpty", + "[Int]().↓count != 0": + "![Int]().isEmpty", + "[Int]().↓count == 0x0": + "[Int]().isEmpty", + "[Int]().↓count == 0x00_00": + "[Int]().isEmpty", + "[Int]().↓count == 0b00": + "[Int]().isEmpty", + "[Int]().↓count == 0o00": + "[Int]().isEmpty", + "↓count == 0": + "isEmpty", + "↓count == 0 && [Int]().↓count == 0o00": + "isEmpty && [Int]().isEmpty", + "[Int]().count != 3 && [Int]().↓count != 0 || ↓count == 0 && [Int]().count > 2": + "[Int]().count != 3 && ![Int]().isEmpty || isEmpty && [Int]().count > 2", + "#ExampleMacro { $0.list.↓count == 0 }": + "#ExampleMacro { $0.list.isEmpty }", + "#Rule(param1: \"param1\") { return $0.donations.↓count == 0 }": + "#Rule(param1: \"param1\") { return $0.donations.isEmpty }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyStringRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyStringRule.swift index 0f6576cbc9..c479208095 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyStringRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/EmptyStringRule.swift @@ -9,18 +9,18 @@ struct EmptyStringRule: Rule { name: "Empty String", description: "Prefer checking `isEmpty` over comparing `string` to an empty string literal", kind: .performance, - nonTriggeringExamples: [ - Example("myString.isEmpty"), - Example("!myString.isEmpty"), - Example("\"\"\"\nfoo==\n\"\"\""), - ], - triggeringExamples: [ - Example(#"myString↓ == """#), - Example(#"myString↓ != """#), - Example(#"myString↓=="""#), - Example(##"myString↓ == #""#"##), - Example(###"myString↓ == ##""##"###), - ] + nonTriggeringExamples: #examples([ + "myString.isEmpty", + "!myString.isEmpty", + "\"\"\"\nfoo==\n\"\"\"", + ]), + triggeringExamples: #examples([ + #"myString↓ == """#, + #"myString↓ != """#, + #"myString↓=="""#, + ##"myString↓ == #""#"##, + ###"myString↓ == ##""##"###, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/FinalTestCaseRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/FinalTestCaseRule.swift index be2dd9ebbe..3f821db68c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/FinalTestCaseRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/FinalTestCaseRule.swift @@ -22,12 +22,12 @@ struct FinalTestCaseRule: Rule { Example("public class ↓Test: QuickSpec {}"), Example("class ↓Test: MyTestCase {}", configuration: ["test_parent_classes": "MyTestCase"]), ], - corrections: [ - Example("class ↓Test: XCTestCase {}"): - Example("final class Test: XCTestCase {}"), - Example("internal class ↓Test: XCTestCase {}"): - Example("internal final class Test: XCTestCase {}"), - ] + corrections: #examplesDictionary([ + "class ↓Test: XCTestCase {}": + "final class Test: XCTestCase {}", + "internal class ↓Test: XCTestCase {}": + "internal final class Test: XCTestCase {}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/FirstWhereRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/FirstWhereRule.swift index d05b4d6fcf..32d6d1a772 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/FirstWhereRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/FirstWhereRule.swift @@ -9,26 +9,26 @@ struct FirstWhereRule: Rule { name: "First Where", description: "Prefer using `.first(where:)` over `.filter { }.first` in collections", kind: .performance, - nonTriggeringExamples: [ - Example("kinds.filter(excludingKinds.contains).isEmpty && kinds.first == .identifier"), - Example("myList.first(where: { $0 % 2 == 0 })"), - Example("match(pattern: pattern).filter { $0.first == .identifier }"), - Example("(myList.filter { $0 == 1 }.suffix(2)).first"), - Example(#"collection.filter("stringCol = '3'").first"#), - Example(#"realm?.objects(User.self).filter(NSPredicate(format: "email ==[c] %@", email)).first"#), - Example(#"if let pause = timeTracker.pauses.filter("beginDate < %@", beginDate).first { print(pause) }"#), - ], - triggeringExamples: [ - Example("↓myList.filter { $0 % 2 == 0 }.first"), - Example("↓myList.filter({ $0 % 2 == 0 }).first"), - Example("↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first"), - Example("↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first?.something()"), - Example("↓myList.filter(someFunction).first"), - Example("↓myList.filter({ $0 % 2 == 0 })\n.first"), - Example("(↓myList.filter { $0 == 1 }).first"), - Example(#"↓myListOfDict.filter { dict in dict["1"] }.first"#), - Example(#"↓myListOfDict.filter { $0["someString"] }.first"#), - ] + nonTriggeringExamples: #examples([ + "kinds.filter(excludingKinds.contains).isEmpty && kinds.first == .identifier", + "myList.first(where: { $0 % 2 == 0 })", + "match(pattern: pattern).filter { $0.first == .identifier }", + "(myList.filter { $0 == 1 }.suffix(2)).first", + #"collection.filter("stringCol = '3'").first"#, + #"realm?.objects(User.self).filter(NSPredicate(format: "email ==[c] %@", email)).first"#, + #"if let pause = timeTracker.pauses.filter("beginDate < %@", beginDate).first { print(pause) }"#, + ]), + triggeringExamples: #examples([ + "↓myList.filter { $0 % 2 == 0 }.first", + "↓myList.filter({ $0 % 2 == 0 }).first", + "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first", + "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first?.something()", + "↓myList.filter(someFunction).first", + "↓myList.filter({ $0 % 2 == 0 })\n.first", + "(↓myList.filter { $0 == 1 }).first", + #"↓myListOfDict.filter { dict in dict["1"] }.first"#, + #"↓myListOfDict.filter { $0["someString"] }.first"#, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/FlatMapOverMapReduceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/FlatMapOverMapReduceRule.swift index b45562bcbb..17a598bb86 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/FlatMapOverMapReduceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/FlatMapOverMapReduceRule.swift @@ -9,13 +9,13 @@ struct FlatMapOverMapReduceRule: Rule { 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([], +)") - ] + nonTriggeringExamples: #examples([ + "let foo = bar.map { $0.count }.reduce(0, +)", + "let foo = bar.flatMap { $0.array }", + ]), + triggeringExamples: #examples([ + "let foo = ↓bar.map { $0.array }.reduce([], +)" + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/LastWhereRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/LastWhereRule.swift index 1a3c41fcf8..c6a78b3fda 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/LastWhereRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/LastWhereRule.swift @@ -9,22 +9,22 @@ struct LastWhereRule: Rule { name: "Last Where", description: "Prefer using `.last(where:)` over `.filter { }.last` in collections", kind: .performance, - nonTriggeringExamples: [ - Example("kinds.filter(excludingKinds.contains).isEmpty && kinds.last == .identifier"), - Example("myList.last(where: { $0 % 2 == 0 })"), - Example("match(pattern: pattern).filter { $0.last == .identifier }"), - Example("(myList.filter { $0 == 1 }.suffix(2)).last"), - Example(#"collection.filter("stringCol = '3'").last"#), - ], - triggeringExamples: [ - Example("↓myList.filter { $0 % 2 == 0 }.last"), - Example("↓myList.filter({ $0 % 2 == 0 }).last"), - Example("↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).last"), - Example("↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).last?.something()"), - Example("↓myList.filter(someFunction).last"), - Example("↓myList.filter({ $0 % 2 == 0 })\n.last"), - Example("(↓myList.filter { $0 == 1 }).last"), - ] + nonTriggeringExamples: #examples([ + "kinds.filter(excludingKinds.contains).isEmpty && kinds.last == .identifier", + "myList.last(where: { $0 % 2 == 0 })", + "match(pattern: pattern).filter { $0.last == .identifier }", + "(myList.filter { $0 == 1 }.suffix(2)).last", + #"collection.filter("stringCol = '3'").last"#, + ]), + triggeringExamples: #examples([ + "↓myList.filter { $0 % 2 == 0 }.last", + "↓myList.filter({ $0 % 2 == 0 }).last", + "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).last", + "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).last?.something()", + "↓myList.filter(someFunction).last", + "↓myList.filter({ $0 % 2 == 0 })\n.last", + "(↓myList.filter { $0 == 1 }).last", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceBooleanRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceBooleanRule.swift index 9298eeb441..5bbac1c53c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceBooleanRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceBooleanRule.swift @@ -9,22 +9,22 @@ struct ReduceBooleanRule: Rule { name: "Reduce Boolean", description: "Prefer using `.allSatisfy()` or `.contains()` over `reduce(true)` or `reduce(false)`.", kind: .performance, - nonTriggeringExamples: [ - Example("nums.reduce(0) { $0.0 + $0.1 }"), - Example("nums.reduce(0.0) { $0.0 + $0.1 }"), - Example("nums.reduce(initial: true) { $0.0 && $0.1 == 3 }"), - ], - triggeringExamples: [ - Example("let allNines = nums.↓reduce(true) { $0.0 && $0.1 == 9 }"), - Example("let anyNines = nums.↓reduce(false) { $0.0 || $0.1 == 9 }"), - Example("let allValid = validators.↓reduce(true) { $0 && $1(input) }"), - Example("let anyValid = validators.↓reduce(false) { $0 || $1(input) }"), - Example("let allNines = nums.↓reduce(true, { $0.0 && $0.1 == 9 })"), - Example("let anyNines = nums.↓reduce(false, { $0.0 || $0.1 == 9 })"), - Example("let allValid = validators.↓reduce(true, { $0 && $1(input) })"), - Example("let anyValid = validators.↓reduce(false, { $0 || $1(input) })"), - Example("nums.reduce(into: true) { (r: inout Bool, s) in r = r && (s == 3) }"), - ] + nonTriggeringExamples: #examples([ + "nums.reduce(0) { $0.0 + $0.1 }", + "nums.reduce(0.0) { $0.0 + $0.1 }", + "nums.reduce(initial: true) { $0.0 && $0.1 == 3 }", + ]), + triggeringExamples: #examples([ + "let allNines = nums.↓reduce(true) { $0.0 && $0.1 == 9 }", + "let anyNines = nums.↓reduce(false) { $0.0 || $0.1 == 9 }", + "let allValid = validators.↓reduce(true) { $0 && $1(input) }", + "let anyValid = validators.↓reduce(false) { $0 || $1(input) }", + "let allNines = nums.↓reduce(true, { $0.0 && $0.1 == 9 })", + "let anyNines = nums.↓reduce(false, { $0.0 || $0.1 == 9 })", + "let allValid = validators.↓reduce(true, { $0 && $1(input) })", + "let anyValid = validators.↓reduce(false, { $0 || $1(input) })", + "nums.reduce(into: true) { (r: inout Bool, s) in r = r && (s == 3) }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceIntoRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceIntoRule.swift index 32499318da..5994ec6d07 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceIntoRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/ReduceIntoRule.swift @@ -9,93 +9,93 @@ struct ReduceIntoRule: Rule { name: "Reduce into", description: "Prefer `reduce(into:_:)` over `reduce(_:_:)` for copy-on-write types", kind: .performance, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ let foo = values.reduce(into: "abc") { $0 += "\\($1)" } - """), - Example(""" + """, + """ values.reduce(into: Array()) { result, value in result.append(value) } - """), - Example(""" + """, + """ let rows = violations.enumerated().reduce(into: "") { rows, indexAndViolation in rows.append(generateSingleRow(for: indexAndViolation.1, at: indexAndViolation.0 + 1)) } - """), - Example(""" + """, + """ zip(group, group.dropFirst()).reduce(into: []) { result, pair in result.append(pair.0 + pair.1) } - """), - Example(""" + """, + """ let foo = values.reduce(into: [String: Int]()) { result, value in result["\\(value)"] = value } - """), - Example(""" + """, + """ let foo = values.reduce(into: Dictionary.init()) { result, value in result["\\(value)"] = value } - """), - Example(""" + """, + """ let foo = values.reduce(into: [Int](repeating: 0, count: 10)) { result, value in result.append(value) } - """), - Example(""" + """, + """ let foo = values.reduce(MyClass()) { result, value in result.handleValue(value) return result } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ let bar = values.↓reduce("abc") { $0 + "\\($1)" } - """), - Example(""" + """, + """ values.↓reduce(Array()) { result, value in result += [value] } - """), - Example(""" + """, + """ [1, 2, 3].↓reduce(Set()) { acc, value in var result = acc result.insert(value) return result } - """), - Example(""" + """, + """ let rows = violations.enumerated().↓reduce("") { rows, indexAndViolation in return rows + generateSingleRow(for: indexAndViolation.1, at: indexAndViolation.0 + 1) } - """), - Example(""" + """, + """ zip(group, group.dropFirst()).↓reduce([]) { result, pair in result + [pair.0 + pair.1] } - """), - Example(""" + """, + """ let foo = values.↓reduce([String: Int]()) { result, value in var result = result result["\\(value)"] = value return result } - """), - Example(""" + """, + """ let bar = values.↓reduce(Dictionary.init()) { result, value in var result = result result["\\(value)"] = value return result } - """), - Example(""" + """, + """ let bar = values.↓reduce([Int](repeating: 0, count: 10)) { result, value in return result + [value] } - """), - Example(""" + """, + """ extension Data { var hexString: String { return ↓reduce("") { (output, byte) -> String in @@ -103,8 +103,8 @@ struct ReduceIntoRule: Rule { } } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift index df1b44f3b1..d20689c82b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift @@ -9,40 +9,40 @@ struct SortedFirstLastRule: Rule { name: "Min or Max over Sorted First or Last", description: "Prefer using `min()` or `max()` over `sorted().first` or `sorted().last`", kind: .performance, - nonTriggeringExamples: [ - Example("let min = myList.min()"), - Example("let min = myList.min(by: { $0 < $1 })"), - Example("let min = myList.min(by: >)"), - Example("let max = myList.max()"), - Example("let max = myList.max(by: { $0 < $1 })"), - Example("let message = messages.sorted(byKeyPath: #keyPath(Message.timestamp)).last"), - Example(#"let message = messages.sorted(byKeyPath: "timestamp", ascending: false).first"#), - Example("myList.sorted().firstIndex(of: key)"), - Example("myList.sorted().lastIndex(of: key)"), - Example("myList.sorted().firstIndex(where: someFunction)"), - Example("myList.sorted().lastIndex(where: someFunction)"), - Example("myList.sorted().firstIndex { $0 == key }"), - Example("myList.sorted().lastIndex { $0 == key }"), - Example("myList.sorted().first(where: someFunction)"), - Example("myList.sorted().last(where: someFunction)"), - Example("myList.sorted().first { $0 == key }"), - Example("myList.sorted().last { $0 == key }"), - ], - triggeringExamples: [ - Example("↓myList.sorted().first"), - Example("↓myList.sorted(by: { $0.description < $1.description }).first"), - Example("↓myList.sorted(by: >).first"), - Example("↓myList.map { $0 + 1 }.sorted().first"), - Example("↓myList.sorted(by: someFunction).first"), - Example("↓myList.map { $0 + 1 }.sorted { $0.description < $1.description }.first"), - Example("↓myList.sorted().last"), - Example("↓myList.sorted().last?.something()"), - Example("↓myList.sorted(by: { $0.description < $1.description }).last"), - Example("↓myList.map { $0 + 1 }.sorted().last"), - Example("↓myList.sorted(by: someFunction).last"), - Example("↓myList.map { $0 + 1 }.sorted { $0.description < $1.description }.last"), - Example("↓myList.map { $0 + 1 }.sorted { $0.first < $1.first }.last"), - ] + nonTriggeringExamples: #examples([ + "let min = myList.min()", + "let min = myList.min(by: { $0 < $1 })", + "let min = myList.min(by: >)", + "let max = myList.max()", + "let max = myList.max(by: { $0 < $1 })", + "let message = messages.sorted(byKeyPath: #keyPath(Message.timestamp)).last", + #"let message = messages.sorted(byKeyPath: "timestamp", ascending: false).first"#, + "myList.sorted().firstIndex(of: key)", + "myList.sorted().lastIndex(of: key)", + "myList.sorted().firstIndex(where: someFunction)", + "myList.sorted().lastIndex(where: someFunction)", + "myList.sorted().firstIndex { $0 == key }", + "myList.sorted().lastIndex { $0 == key }", + "myList.sorted().first(where: someFunction)", + "myList.sorted().last(where: someFunction)", + "myList.sorted().first { $0 == key }", + "myList.sorted().last { $0 == key }", + ]), + triggeringExamples: #examples([ + "↓myList.sorted().first", + "↓myList.sorted(by: { $0.description < $1.description }).first", + "↓myList.sorted(by: >).first", + "↓myList.map { $0 + 1 }.sorted().first", + "↓myList.sorted(by: someFunction).first", + "↓myList.map { $0 + 1 }.sorted { $0.description < $1.description }.first", + "↓myList.sorted().last", + "↓myList.sorted().last?.something()", + "↓myList.sorted(by: { $0.description < $1.description }).last", + "↓myList.map { $0 + 1 }.sorted().last", + "↓myList.sorted(by: someFunction).last", + "↓myList.map { $0 + 1 }.sorted { $0.description < $1.description }.last", + "↓myList.map { $0 + 1 }.sorted { $0.first < $1.first }.last", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/AttributeNameSpacingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/AttributeNameSpacingRule.swift index d10931a8a5..acf2afaeae 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/AttributeNameSpacingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/AttributeNameSpacingRule.swift @@ -14,61 +14,61 @@ struct AttributeNameSpacingRule: Rule { results in a compilation error (e.g. `@MyPropertyWrapper ()`, `private (set)`). """, kind: .style, - nonTriggeringExamples: [ - Example("private(set) var foo: Bool = false"), - Example("fileprivate(set) var foo: Bool = false"), - Example("@MainActor class Foo {}"), - Example("func funcWithEscapingClosure(_ x: @escaping () -> Int) {}"), - Example("@available(*, deprecated)"), - Example("@MyPropertyWrapper(param: 2) "), - Example("nonisolated(unsafe) var _value: X?"), - Example("@testable import SwiftLintCore"), - Example("func func_type_attribute_with_space(x: @convention(c) () -> Int) {}"), - Example(""" + nonTriggeringExamples: #examples([ + "private(set) var foo: Bool = false", + "fileprivate(set) var foo: Bool = false", + "@MainActor class Foo {}", + "func funcWithEscapingClosure(_ x: @escaping () -> Int) {}", + "@available(*, deprecated)", + "@MyPropertyWrapper(param: 2) ", + "nonisolated(unsafe) var _value: X?", + "@testable import SwiftLintCore", + "func func_type_attribute_with_space(x: @convention(c) () -> Int) {}", + """ @propertyWrapper struct MyPropertyWrapper { var wrappedValue: Int = 1 init(param: Int) {} } - """), - Example(""" + """, + """ let closure2 = { @MainActor (a: Int, b: Int) in } - """), - Example(""" + """, + """ let closure1 = { @MainActor (a, b) in } - """), - ], - triggeringExamples: [ - Example("private ↓(set) var foo: Bool = false"), - Example("fileprivate ↓(set) var foo: Bool = false"), - Example("public ↓(set) var foo: Bool = false"), - Example(" public ↓(set) var foo: Bool = false"), - Example("@ ↓MainActor class Foo {}"), - Example("func funcWithEscapingClosure(_ x: @ ↓escaping () -> Int) {}"), - Example("func funcWithEscapingClosure(_ x: @escaping↓() -> Int) {}"), - Example("@available ↓(*, deprecated)"), - Example("@MyPropertyWrapper ↓(param: 2) let a = 1"), - Example("nonisolated ↓(unsafe) var _value: X?"), - Example("@MyProperty ↓() class Foo {}"), - ], - corrections: [ - Example("private↓ (set) var foo: Bool = false"): Example("private(set) var foo: Bool = false"), - Example("fileprivate↓ (set) var foo: Bool = false"): Example("fileprivate(set) var foo: Bool = false"), - Example("internal↓ (set) var foo: Bool = false"): Example("internal(set) var foo: Bool = false"), - Example("public↓ (set) var foo: Bool = false"): Example("public(set) var foo: Bool = false"), - Example("public↓ (set) var foo: Bool = false"): Example("public(set) var foo: Bool = false"), - Example("@↓ MainActor"): Example("@MainActor"), - Example("func test(_ x: @↓ escaping () -> Int) {}"): Example("func test(_ x: @escaping () -> Int) {}"), - Example("func test(_ x: @escaping↓() -> Int) {}"): Example("func test(_ x: @escaping () -> Int) {}"), - Example("@available↓ (*, deprecated)"): Example("@available(*, deprecated)"), - Example("@MyPropertyWrapper↓ (param: 2) let a = 1"): Example("@MyPropertyWrapper(param: 2) let a = 1"), - Example("nonisolated↓ (unsafe) var _value: X?"): Example("nonisolated(unsafe) var _value: X?"), - Example("@MyProperty↓ () let a = 1"): Example("@MyProperty() let a = 1"), - ] + """, + ]), + triggeringExamples: #examples([ + "private ↓(set) var foo: Bool = false", + "fileprivate ↓(set) var foo: Bool = false", + "public ↓(set) var foo: Bool = false", + " public ↓(set) var foo: Bool = false", + "@ ↓MainActor class Foo {}", + "func funcWithEscapingClosure(_ x: @ ↓escaping () -> Int) {}", + "func funcWithEscapingClosure(_ x: @escaping↓() -> Int) {}", + "@available ↓(*, deprecated)", + "@MyPropertyWrapper ↓(param: 2) let a = 1", + "nonisolated ↓(unsafe) var _value: X?", + "@MyProperty ↓() class Foo {}", + ]), + corrections: #examplesDictionary([ + "private↓ (set) var foo: Bool = false": "private(set) var foo: Bool = false", + "fileprivate↓ (set) var foo: Bool = false": "fileprivate(set) var foo: Bool = false", + "internal↓ (set) var foo: Bool = false": "internal(set) var foo: Bool = false", + "public↓ (set) var foo: Bool = false": "public(set) var foo: Bool = false", + "public↓ (set) var foo: Bool = false": "public(set) var foo: Bool = false", + "@↓ MainActor": "@MainActor", + "func test(_ x: @↓ escaping () -> Int) {}": "func test(_ x: @escaping () -> Int) {}", + "func test(_ x: @escaping↓() -> Int) {}": "func test(_ x: @escaping () -> Int) {}", + "@available↓ (*, deprecated)": "@available(*, deprecated)", + "@MyPropertyWrapper↓ (param: 2) let a = 1": "@MyPropertyWrapper(param: 2) let a = 1", + "nonisolated↓ (unsafe) var _value: X?": "nonisolated(unsafe) var _value: X?", + "@MyProperty↓ () let a = 1": "@MyProperty() let a = 1", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ClosingBraceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ClosingBraceRule.swift index c31322d3c8..27a7a17a82 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ClosingBraceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ClosingBraceRule.swift @@ -9,17 +9,17 @@ struct ClosingBraceRule: Rule { name: "Closing Brace Spacing", description: "Closing brace with closing parenthesis should not have any whitespaces in the middle", kind: .style, - nonTriggeringExamples: [ - Example("[].map({ })"), - Example("[].map(\n { }\n)"), - ], - triggeringExamples: [ - Example("[].map({ ↓} )"), - Example("[].map({ ↓}\t)"), - ], - corrections: [ - Example("[].map({ ↓} )"): Example("[].map({ })") - ] + nonTriggeringExamples: #examples([ + "[].map({ })", + "[].map(\n { }\n)", + ]), + triggeringExamples: #examples([ + "[].map({ ↓} )", + "[].map({ ↓}\t)", + ]), + corrections: #examplesDictionary([ + "[].map({ ↓} )": "[].map({ })" + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ClosureEndIndentationRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ClosureEndIndentationRuleExamples.swift index 129c28a124..2c26cda5e9 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ClosureEndIndentationRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ClosureEndIndentationRuleExamples.swift @@ -69,21 +69,21 @@ internal struct ClosureEndIndentationRuleExamples { """), ] - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ SignalProducer(values: [1, 2, 3]) .startWithNext { number in print(number) ↓} - """), - Example(""" + """, + """ return match(pattern: pattern, with: [.comment]).flatMap { range in return Command(string: contents, range: range) ↓}.flatMap { command in return command.expand() } - """), - Example(""" + """, + """ function( closure: { x in print(x) @@ -91,22 +91,22 @@ internal struct ClosureEndIndentationRuleExamples { anotherClosure: { y in print(y) ↓}) - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ SignalProducer(values: [1, 2, 3]) .startWithNext { number in print(number) ↓} - """): Example(""" + """: """ SignalProducer(values: [1, 2, 3]) .startWithNext { number in print(number) } - """), - Example(""" + """, + """ SignalProducer(values: [1, 2, 3]) .startWithNext { number in print(number) @@ -115,7 +115,7 @@ internal struct ClosureEndIndentationRuleExamples { ↓}.yetAnother { y in print(y) ↓}) - """): Example(""" + """: """ SignalProducer(values: [1, 2, 3]) .startWithNext { number in print(number) @@ -124,52 +124,52 @@ internal struct ClosureEndIndentationRuleExamples { }.yetAnother { y in print(y) }) - """), - Example(""" + """, + """ return match(pattern: pattern, with: [.comment]).flatMap { range in return Command(string: contents, range: range) ↓ }.flatMap { command in return command.expand() ↓} - """): Example(""" + """: """ return match(pattern: pattern, with: [.comment]).flatMap { range in return Command(string: contents, range: range) }.flatMap { command in return command.expand() } - """), - Example(""" + """, + """ function( closure: { x in print(x) ↓}) - """): Example(""" + """: """ function( closure: { x in print(x) }) - """), - Example(""" + """, + """ function( closure: { x in ↓ print(x) }) - """): Example(""" + """: """ function( closure: { x in print(x) \("") }) - """), - Example(""" + """, + """ function( closure: { x in ↓ab}) - """): Example(""" + """: """ function( closure: { x in ab }) - """), - Example(""" + """, + """ function( closure: { x in print(x) @@ -177,7 +177,7 @@ internal struct ClosureEndIndentationRuleExamples { anotherClosure: { y in print(y) }) - """): Example(""" + """: """ function( closure: { x in print(x) @@ -185,8 +185,8 @@ internal struct ClosureEndIndentationRuleExamples { anotherClosure: { y in print(y) }) - """), - Example(""" + """, + """ function( closure: { x in print(x) // comment @@ -195,7 +195,7 @@ internal struct ClosureEndIndentationRuleExamples { anotherClosure: { y in print(y) /* comment */}) - """): Example(""" + """: """ function( closure: { x in print(x) // comment @@ -205,8 +205,8 @@ internal struct ClosureEndIndentationRuleExamples { print(y) /* comment */ }) - """), - Example(""" + """, + """ function( closure: { x in print(x) @@ -214,7 +214,7 @@ internal struct ClosureEndIndentationRuleExamples { anotherClosure: { y in print(y) }) - """): Example(""" + """: """ function( closure: { x in print(x) @@ -223,15 +223,15 @@ internal struct ClosureEndIndentationRuleExamples { anotherClosure: { y in print(y) }) - """), - Example(""" + """, + """ function( closure: { x in ↓ print(x) }, anotherClosure: { y in print(y) }) - """): Example(""" + """: """ function( closure: { x in print(x) \("") @@ -239,30 +239,30 @@ internal struct ClosureEndIndentationRuleExamples { anotherClosure: { y in print(y) }) - """), - Example(""" + """, + """ function( closure: { x in print(x) ↓}, anotherClosure: { y in print(y) ↓}) - """): Example(""" + """: """ function( closure: { x in print(x) }, anotherClosure: { y in print(y) }) - """), - Example(""" + """, + """ f { // do something ↓} - """): Example(""" + """: """ f { // do something } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ClosureParameterPositionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ClosureParameterPositionRule.swift index 4092b327ef..b659e8ff12 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ClosureParameterPositionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ClosureParameterPositionRule.swift @@ -9,90 +9,90 @@ struct ClosureParameterPositionRule: Rule { name: "Closure Parameter Position", description: "Closure parameters should be on the same line as opening brace", kind: .style, - nonTriggeringExamples: [ - Example("[1, 2].map { $0 + 1 }"), - Example("[1, 2].map({ $0 + 1 })"), - Example("[1, 2].map { number in\n number + 1 \n}"), - Example("[1, 2].map { number -> Int in\n number + 1 \n}"), - Example("[1, 2].map { (number: Int) -> Int in\n number + 1 \n}"), - Example("[1, 2].map { [weak self] number in\n number + 1 \n}"), - Example("[1, 2].something(closure: { number in\n number + 1 \n})"), - Example("let isEmpty = [1, 2].isEmpty()"), - Example(""" + nonTriggeringExamples: #examples([ + "[1, 2].map { $0 + 1 }", + "[1, 2].map({ $0 + 1 })", + "[1, 2].map { number in\n number + 1 \n}", + "[1, 2].map { number -> Int in\n number + 1 \n}", + "[1, 2].map { (number: Int) -> Int in\n number + 1 \n}", + "[1, 2].map { [weak self] number in\n number + 1 \n}", + "[1, 2].something(closure: { number in\n number + 1 \n})", + "let isEmpty = [1, 2].isEmpty()", + """ rlmConfiguration.migrationBlock.map { rlmMigration in return { migration, schemaVersion in rlmMigration(migration.rlmMigration, schemaVersion) } } - """), - Example(""" + """, + """ let mediaView: UIView = { [weak self] index in return UIView() }(index) - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ [1, 2].map { ↓number in number + 1 } - """), - Example(""" + """, + """ [1, 2].map { ↓number -> Int in number + 1 } - """), - Example(""" + """, + """ [1, 2].map { (↓number: Int) -> Int in number + 1 } - """), - Example(""" + """, + """ [1, 2].map { [weak ↓self] ↓number in number + 1 } - """), - Example(""" + """, + """ [1, 2].map { [weak self] ↓number in number + 1 } - """), - Example(""" + """, + """ [1, 2].map({ ↓number in number + 1 }) - """), - Example(""" + """, + """ [1, 2].something(closure: { ↓number in number + 1 }) - """), - Example(""" + """, + """ [1, 2].reduce(0) { ↓sum, ↓number in number + sum }) - """), - Example(""" + """, + """ f.completionHandler = { ↓thing in doStuff() } - """), - Example(""" + """, + """ foo { [weak ↓self] in self?.bar() } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ClosureSpacingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ClosureSpacingRule.swift index 7df46cf426..9485ef6462 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ClosureSpacingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ClosureSpacingRule.swift @@ -33,16 +33,16 @@ struct ClosureSpacingRule: Rule { var tapped: (UITapGestureRecognizer) -> Void = ↓{ _ in /* no-op */ } """, excludeFromDocumentation: true), ], - corrections: [ - Example("[].filter(↓{$0.contains(location) })"): - Example("[].filter({ $0.contains(location) })"), - Example("[].map(↓{$0})"): - Example("[].map({ $0 })"), - Example("filter ↓{sorted ↓{ $0 < $1}}"): - Example("filter { sorted { $0 < $1 } }"), - Example("(↓{each in return result.contains(where: ↓{e in return 0})}).count"): - Example("({ each in return result.contains(where: { e in return 0 }) }).count"), - ] + corrections: #examplesDictionary([ + "[].filter(↓{$0.contains(location) })": + "[].filter({ $0.contains(location) })", + "[].map(↓{$0})": + "[].map({ $0 })", + "filter ↓{sorted ↓{ $0 < $1}}": + "filter { sorted { $0 < $1 } }", + "(↓{each in return result.contains(where: ↓{e in return 0})}).count": + "({ each in return result.contains(where: { e in return 0 }) }).count", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/CollectionAlignmentRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/CollectionAlignmentRule.swift index a4a995bfeb..feea6c5aae 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/CollectionAlignmentRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/CollectionAlignmentRule.swift @@ -93,16 +93,16 @@ extension CollectionAlignmentRule { } private var alignColonsTriggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ doThings(arg: [ "foo": 1, "bar": 2, "fizz"↓: 2, "buzz"↓: 2 ]) - """), - Example(""" + """, + """ let abc = [ "alpha": "a", "beta"↓: "b", @@ -110,28 +110,28 @@ extension CollectionAlignmentRule { "delta": "d", "epsilon"↓: "e" ] - """), - Example(""" + """, + """ var weirdColons = [ "a" : 1, "b" ↓:2, "c" : 3 ] - """), - ] + """, + ]) } private var alignColonsNonTriggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ doThings(arg: [ "foo": 1, "bar": 2, "fizz": 2, "buzz": 2 ]) - """), - Example(""" + """, + """ let abc = [ "alpha": "a", "beta": "b", @@ -139,32 +139,32 @@ extension CollectionAlignmentRule { "delta": "d", "epsilon": "e" ] - """), - Example(""" + """, + """ var weirdColons = [ "a" : 1, "b" :2, "c" : 3 ] - """), - Example(""" + """, + """ NSAttributedString(string: "…", attributes: [.font: UIFont.systemFont(ofSize: 12, weight: .regular), .foregroundColor: UIColor(white: 0, alpha: 0.2)]) - """), - ] + """, + ]) } private var alignLeftTriggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ doThings(arg: [ "foo": 1, "bar": 2, ↓"fizz": 2, ↓"buzz": 2 ]) - """), - Example(""" + """, + """ let abc = [ "alpha": "a", ↓"beta": "b", @@ -172,28 +172,28 @@ extension CollectionAlignmentRule { "delta": "d", ↓"epsilon": "e" ] - """), - Example(""" + """, + """ let meals = [ "breakfast": "oatmeal", "lunch": "sandwich", ↓"dinner": "burger" ] - """), - ] + """, + ]) } private var alignLeftNonTriggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ doThings(arg: [ "foo": 1, "bar": 2, "fizz": 2, "buzz": 2 ]) - """), - Example(""" + """, + """ let abc = [ "alpha": "a", "beta": "b", @@ -201,70 +201,70 @@ extension CollectionAlignmentRule { "delta": "d", "epsilon": "e" ] - """), - Example(""" + """, + """ let meals = [ "breakfast": "oatmeal", "lunch": "sandwich", "dinner": "burger" ] - """), - Example(""" + """, + """ NSAttributedString(string: "…", attributes: [.font: UIFont.systemFont(ofSize: 12, weight: .regular), .foregroundColor: UIColor(white: 0, alpha: 0.2)]) - """), - ] + """, + ]) } private var sharedTriggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ let coordinates = [ CLLocationCoordinate2D(latitude: 0, longitude: 33), ↓CLLocationCoordinate2D(latitude: 0, longitude: 66), CLLocationCoordinate2D(latitude: 0, longitude: 99) ] - """), - Example(""" + """, + """ var evenNumbers: Set = [ 2, ↓4, 6 ] - """), - ] + """, + ]) } private var sharedNonTriggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ let coordinates = [ CLLocationCoordinate2D(latitude: 0, longitude: 33), CLLocationCoordinate2D(latitude: 0, longitude: 66), CLLocationCoordinate2D(latitude: 0, longitude: 99) ] - """), - Example(""" + """, + """ var evenNumbers: Set = [ 2, 4, 6 ] - """), - Example(""" + """, + """ let abc = [1, 2, 3, 4] - """), - Example(""" + """, + """ let abc = [ 1, 2, 3, 4 ] - """), - Example(""" + """, + """ let abc = [ "foo": "bar", "fizz": "buzz" ] - """), - ] + """, + ]) } } } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ColonRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ColonRuleExamples.swift index a963c54181..5f7d68df1b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ColonRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ColonRuleExamples.swift @@ -1,72 +1,72 @@ internal struct ColonRuleExamples { - static let nonTriggeringExamples = [ - Example("let abc: Void"), - Example("let abc: [Void: Void]"), - Example("let abc: (Void, Void)"), - Example("let abc: ([Void], String, Int)"), - Example("let abc: [([Void], String, Int)]"), - Example("let abc: String=\"def\""), - Example("let abc: Int=0"), - Example("let abc: Enum=Enum.Value"), - Example("func abc(def: Void) {}"), - Example("func abc(def: Void, ghi: Void) {}"), - Example("let abc: String = \"abc:\""), - Example("let abc = [Void: Void]()"), - Example("let abc = [1: [3: 2], 3: 4]"), - Example("let abc = [\"string\": \"string\"]"), - Example("let abc = [\"string:string\": \"string\"]"), - Example("let abc: [String: Int]"), - Example("func foo(bar: [String: Int]) {}"), - Example("func foo() -> [String: Int] { return [:] }"), - Example("let abc: Any"), - Example("let abc: [Any: Int]"), - Example("let abc: [String: Any]"), - Example("class Foo: Bar {}"), - Example("class Foo: Bar {}"), - Example("class Foo: Bar {}"), - Example("class Foo: Bar {}"), - Example("class Foo {}"), - Example("object.method(x: /* comment */ 5)"), - Example(""" + static let nonTriggeringExamples = #examples([ + "let abc: Void", + "let abc: [Void: Void]", + "let abc: (Void, Void)", + "let abc: ([Void], String, Int)", + "let abc: [([Void], String, Int)]", + "let abc: String=\"def\"", + "let abc: Int=0", + "let abc: Enum=Enum.Value", + "func abc(def: Void) {}", + "func abc(def: Void, ghi: Void) {}", + "let abc: String = \"abc:\"", + "let abc = [Void: Void]()", + "let abc = [1: [3: 2], 3: 4]", + "let abc = [\"string\": \"string\"]", + "let abc = [\"string:string\": \"string\"]", + "let abc: [String: Int]", + "func foo(bar: [String: Int]) {}", + "func foo() -> [String: Int] { return [:] }", + "let abc: Any", + "let abc: [Any: Int]", + "let abc: [String: Any]", + "class Foo: Bar {}", + "class Foo: Bar {}", + "class Foo: Bar {}", + "class Foo: Bar {}", + "class Foo {}", + "object.method(x: /* comment */ 5)", + """ switch foo { case .bar: _ = something() } - """), - Example("object.method(x: 5, y: \"string\")"), - Example(""" + """, + "object.method(x: 5, y: \"string\")", + """ object.method(x: 5, y: "string") - """), - Example("object.method(5, y: \"string\")"), - Example("func abc() { def(ghi: jkl) }"), - Example("func abc(def: Void) { ghi(jkl: mno) }"), - Example("class ABC { let def = ghi(jkl: mno) } }"), - Example("func foo() { let dict = [1: 1] }"), - Example(""" + """, + "object.method(5, y: \"string\")", + "func abc() { def(ghi: jkl) }", + "func abc(def: Void) { ghi(jkl: mno) }", + "class ABC { let def = ghi(jkl: mno) } }", + "func foo() { let dict = [1: 1] }", + """ let aaa = Self.bbb ? Self.ccc : Self.ddd else { return nil Example("} - """), - Example("range.flatMap(file.syntaxMap.kinds(inByteRange:)) ?? []"), - Example(""" + """, + "range.flatMap(file.syntaxMap.kinds(inByteRange:)) ?? []", + """ @objc(receiveReply:) public class func receiveReply(_ reply: bad_instruction_exception_reply_t) -> CInt { 0 } - """), - Example(#""" + """, + #""" switch str { case "adlm", "adlam": return .adlam case "aghb", "caucasianalbanian": return .caucasianAlbanian default: return nil } - """#), - Example(""" + """#, + """ precedencegroup PipelinePrecedence { associativity: left } infix operator |> : PipelinePrecedence - """), - Example(""" + """, + """ switch scalar { case 0x000A...0x000D /* LF ... CR */: return true case 0x0085 /* NEXT LINE (NEL) */: return true @@ -74,151 +74,151 @@ internal struct ColonRuleExamples { case 0x2029 /* PARAGRAPH SEPARATOR */: return true default: return false } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example("let abc↓:Void"), - Example("let abc↓: Void"), - Example("let abc↓ :Void"), - Example("let abc↓ : Void"), - Example("let abc↓ : [Void: Void]"), - Example("let abc↓ : (Void, String, Int)"), - Example("let abc↓ : ([Void], String, Int)"), - Example("let abc↓ : [([Void], String, Int)]"), - Example("let abc↓: (Void, String, Int)"), - Example("let abc↓: ([Void], String, Int)"), - Example("let abc↓: [([Void], String, Int)]"), - Example("let abc↓ :String=\"def\""), - Example("let abc↓ :Int=0"), - Example("let abc↓ :Int = 0"), - Example("let abc↓:Int=0"), - Example("let abc↓:Int = 0"), - Example("let abc↓:Enum=Enum.Value"), - Example("func abc(def↓:Void) {}"), - Example("func abc(def↓: Void) {}"), - Example("func abc(def↓ :Void) {}"), - Example("func abc(def↓ : Void) {}"), - Example("func abc(def: Void, ghi↓ :Void) {}"), - Example("let abc = [Void↓:Void]()"), - Example("let abc = [Void↓ : Void]()"), - Example("let abc = [Void↓: Void]()"), - Example("let abc = [Void↓ : Void]()"), - Example("let abc = [1: [3↓ : 2], 3: 4]"), - Example("let abc = [1: [3↓ : 2], 3↓: 4]"), - Example("let abc: [String↓ : Int]"), - Example("let abc: [String↓:Int]"), - Example("func foo(bar: [String↓ : Int]) {}"), - Example("func foo(bar: [String↓:Int]) {}"), - Example("func foo() -> [String↓ : Int] { return [:] }"), - Example("func foo() -> [String↓:Int] { return [:] }"), - Example("let abc↓ : Any"), - Example("let abc: [Any↓ : Int]"), - Example("let abc: [String↓ : Any]"), - Example("class Foo↓ : Bar {}"), - Example("class Foo↓:Bar {}"), - Example("class Foo↓ : Bar {}"), - Example("class Foo↓:Bar {}"), - Example("class Foo↓:Bar {}"), - Example("class Foo↓:Bar {}"), - Example("class Foo {}"), - Example("class Foo {}"), - Example("object.method(x: 5, y↓ : \"string\")"), - Example("object.method(x↓:5, y: \"string\")"), - Example("object.method(x↓: 5, y: \"string\")"), - Example("func abc() { def(ghi↓:jkl) }"), - Example("func abc(def: Void) { ghi(jkl↓:mno) }"), - Example("class ABC { let def = ghi(jkl↓:mno) } }"), - Example("func foo() { let dict = [1↓ : 1] }"), - Example(""" + static let triggeringExamples = #examples([ + "let abc↓:Void", + "let abc↓: Void", + "let abc↓ :Void", + "let abc↓ : Void", + "let abc↓ : [Void: Void]", + "let abc↓ : (Void, String, Int)", + "let abc↓ : ([Void], String, Int)", + "let abc↓ : [([Void], String, Int)]", + "let abc↓: (Void, String, Int)", + "let abc↓: ([Void], String, Int)", + "let abc↓: [([Void], String, Int)]", + "let abc↓ :String=\"def\"", + "let abc↓ :Int=0", + "let abc↓ :Int = 0", + "let abc↓:Int=0", + "let abc↓:Int = 0", + "let abc↓:Enum=Enum.Value", + "func abc(def↓:Void) {}", + "func abc(def↓: Void) {}", + "func abc(def↓ :Void) {}", + "func abc(def↓ : Void) {}", + "func abc(def: Void, ghi↓ :Void) {}", + "let abc = [Void↓:Void]()", + "let abc = [Void↓ : Void]()", + "let abc = [Void↓: Void]()", + "let abc = [Void↓ : Void]()", + "let abc = [1: [3↓ : 2], 3: 4]", + "let abc = [1: [3↓ : 2], 3↓: 4]", + "let abc: [String↓ : Int]", + "let abc: [String↓:Int]", + "func foo(bar: [String↓ : Int]) {}", + "func foo(bar: [String↓:Int]) {}", + "func foo() -> [String↓ : Int] { return [:] }", + "func foo() -> [String↓:Int] { return [:] }", + "let abc↓ : Any", + "let abc: [Any↓ : Int]", + "let abc: [String↓ : Any]", + "class Foo↓ : Bar {}", + "class Foo↓:Bar {}", + "class Foo↓ : Bar {}", + "class Foo↓:Bar {}", + "class Foo↓:Bar {}", + "class Foo↓:Bar {}", + "class Foo {}", + "class Foo {}", + "object.method(x: 5, y↓ : \"string\")", + "object.method(x↓:5, y: \"string\")", + "object.method(x↓: 5, y: \"string\")", + "func abc() { def(ghi↓:jkl) }", + "func abc(def: Void) { ghi(jkl↓:mno) }", + "class ABC { let def = ghi(jkl↓:mno) } }", + "func foo() { let dict = [1↓ : 1] }", + """ switch foo { case .bar↓ : return baz } - """), - Example("private var action↓:(() -> Void)?"), - ] + """, + "private var action↓:(() -> Void)?", + ]) - static let corrections = [ - Example("let abc↓:Void"): Example("let abc: Void"), - Example("let abc↓: Void"): Example("let abc: Void"), - Example("let abc↓ :Void"): Example("let abc: Void"), - Example("let abc↓ : Void"): Example("let abc: Void"), - Example("let abc↓ : [Void: Void]"): Example("let abc: [Void: Void]"), - Example("let abc↓ : (Void, String, Int)"): Example("let abc: (Void, String, Int)"), - Example("let abc↓ : ([Void], String, Int)"): Example("let abc: ([Void], String, Int)"), - Example("let abc↓ : [([Void], String, Int)]"): Example("let abc: [([Void], String, Int)]"), - Example("let abc↓: (Void, String, Int)"): Example("let abc: (Void, String, Int)"), - Example("let abc↓: ([Void], String, Int)"): Example("let abc: ([Void], String, Int)"), - Example("let abc↓: [([Void], String, Int)]"): Example("let abc: [([Void], String, Int)]"), - Example("let abc↓ :String=\"def\""): Example("let abc: String=\"def\""), - Example("let abc↓ :Int=0"): Example("let abc: Int=0"), - Example("let abc↓ :Int = 0"): Example("let abc: Int = 0"), - Example("let abc↓:Int=0"): Example("let abc: Int=0"), - Example("let abc↓:Int = 0"): Example("let abc: Int = 0"), - Example("let abc↓:Enum=Enum.Value"): Example("let abc: Enum=Enum.Value"), - Example("func abc(def↓:Void) {}"): Example("func abc(def: Void) {}"), - Example("func abc(def↓: Void) {}"): Example("func abc(def: Void) {}"), - Example("func abc(def↓ :Void) {}"): Example("func abc(def: Void) {}"), - Example("func abc(def↓ : Void) {}"): Example("func abc(def: Void) {}"), - Example("func abc(def: Void, ghi↓ :Void) {}"): Example("func abc(def: Void, ghi: Void) {}"), - Example("let abc = [Void↓:Void]()"): Example("let abc = [Void: Void]()"), - Example("let abc = [Void↓ : Void]()"): Example("let abc = [Void: Void]()"), - Example("let abc = [Void↓: Void]()"): Example("let abc = [Void: Void]()"), - Example("let abc = [Void↓ : Void]()"): Example("let abc = [Void: Void]()"), - Example("let abc = [1: [3↓ : 2], 3: 4]"): Example("let abc = [1: [3: 2], 3: 4]"), - Example("let abc = [1: [3↓ : 2], 3↓: 4]"): Example("let abc = [1: [3: 2], 3: 4]"), - Example("let abc: [String↓ : Int]"): Example("let abc: [String: Int]"), - Example("let abc: [String↓:Int]"): Example("let abc: [String: Int]"), - Example("func foo(bar: [String↓ : Int]) {}"): Example("func foo(bar: [String: Int]) {}"), - Example("func foo(bar: [String↓:Int]) {}"): Example("func foo(bar: [String: Int]) {}"), - Example("func foo() -> [String↓ : Int] { return [:] }"): - Example("func foo() -> [String: Int] { return [:] }"), - Example("func foo() -> [String↓:Int] { return [:] }"): - Example("func foo() -> [String: Int] { return [:] }"), - Example("let abc↓ : Any"): Example("let abc: Any"), - Example("let abc: [Any↓ : Int]"): Example("let abc: [Any: Int]"), - Example("let abc: [String↓ : Any]"): Example("let abc: [String: Any]"), - Example("class Foo↓ : Bar {}"): Example("class Foo: Bar {}"), - Example("class Foo↓:Bar {}"): Example("class Foo: Bar {}"), - Example("class Foo↓ : Bar {}"): Example("class Foo: Bar {}"), - Example("class Foo↓:Bar {}"): Example("class Foo: Bar {}"), - Example("class Foo↓:Bar {}"): Example("class Foo: Bar {}"), - Example("class Foo↓:Bar {}"): Example("class Foo: Bar {}"), - Example("class Foo {}"): Example("class Foo {}"), - Example("class Foo {}"): Example("class Foo {}"), - Example("object.method(x: 5, y↓ : \"string\")"): Example("object.method(x: 5, y: \"string\")"), - Example("object.method(x↓:5, y: \"string\")"): Example("object.method(x: 5, y: \"string\")"), - Example("object.method(x↓: 5, y: \"string\")"): Example("object.method(x: 5, y: \"string\")"), - Example("func abc() { def(ghi↓:jkl) }"): Example("func abc() { def(ghi: jkl) }"), - Example("func abc(def: Void) { ghi(jkl↓:mno) }"): Example("func abc(def: Void) { ghi(jkl: mno) }"), - Example("class ABC { let def = ghi(jkl↓:mno) } }"): Example("class ABC { let def = ghi(jkl: mno) } }"), - Example("func foo() { let dict = [1↓ : 1] }"): Example("func foo() { let dict = [1: 1] }"), - Example(""" + static let corrections = #examplesDictionary([ + "let abc↓:Void": "let abc: Void", + "let abc↓: Void": "let abc: Void", + "let abc↓ :Void": "let abc: Void", + "let abc↓ : Void": "let abc: Void", + "let abc↓ : [Void: Void]": "let abc: [Void: Void]", + "let abc↓ : (Void, String, Int)": "let abc: (Void, String, Int)", + "let abc↓ : ([Void], String, Int)": "let abc: ([Void], String, Int)", + "let abc↓ : [([Void], String, Int)]": "let abc: [([Void], String, Int)]", + "let abc↓: (Void, String, Int)": "let abc: (Void, String, Int)", + "let abc↓: ([Void], String, Int)": "let abc: ([Void], String, Int)", + "let abc↓: [([Void], String, Int)]": "let abc: [([Void], String, Int)]", + "let abc↓ :String=\"def\"": "let abc: String=\"def\"", + "let abc↓ :Int=0": "let abc: Int=0", + "let abc↓ :Int = 0": "let abc: Int = 0", + "let abc↓:Int=0": "let abc: Int=0", + "let abc↓:Int = 0": "let abc: Int = 0", + "let abc↓:Enum=Enum.Value": "let abc: Enum=Enum.Value", + "func abc(def↓:Void) {}": "func abc(def: Void) {}", + "func abc(def↓: Void) {}": "func abc(def: Void) {}", + "func abc(def↓ :Void) {}": "func abc(def: Void) {}", + "func abc(def↓ : Void) {}": "func abc(def: Void) {}", + "func abc(def: Void, ghi↓ :Void) {}": "func abc(def: Void, ghi: Void) {}", + "let abc = [Void↓:Void]()": "let abc = [Void: Void]()", + "let abc = [Void↓ : Void]()": "let abc = [Void: Void]()", + "let abc = [Void↓: Void]()": "let abc = [Void: Void]()", + "let abc = [Void↓ : Void]()": "let abc = [Void: Void]()", + "let abc = [1: [3↓ : 2], 3: 4]": "let abc = [1: [3: 2], 3: 4]", + "let abc = [1: [3↓ : 2], 3↓: 4]": "let abc = [1: [3: 2], 3: 4]", + "let abc: [String↓ : Int]": "let abc: [String: Int]", + "let abc: [String↓:Int]": "let abc: [String: Int]", + "func foo(bar: [String↓ : Int]) {}": "func foo(bar: [String: Int]) {}", + "func foo(bar: [String↓:Int]) {}": "func foo(bar: [String: Int]) {}", + "func foo() -> [String↓ : Int] { return [:] }": + "func foo() -> [String: Int] { return [:] }", + "func foo() -> [String↓:Int] { return [:] }": + "func foo() -> [String: Int] { return [:] }", + "let abc↓ : Any": "let abc: Any", + "let abc: [Any↓ : Int]": "let abc: [Any: Int]", + "let abc: [String↓ : Any]": "let abc: [String: Any]", + "class Foo↓ : Bar {}": "class Foo: Bar {}", + "class Foo↓:Bar {}": "class Foo: Bar {}", + "class Foo↓ : Bar {}": "class Foo: Bar {}", + "class Foo↓:Bar {}": "class Foo: Bar {}", + "class Foo↓:Bar {}": "class Foo: Bar {}", + "class Foo↓:Bar {}": "class Foo: Bar {}", + "class Foo {}": "class Foo {}", + "class Foo {}": "class Foo {}", + "object.method(x: 5, y↓ : \"string\")": "object.method(x: 5, y: \"string\")", + "object.method(x↓:5, y: \"string\")": "object.method(x: 5, y: \"string\")", + "object.method(x↓: 5, y: \"string\")": "object.method(x: 5, y: \"string\")", + "func abc() { def(ghi↓:jkl) }": "func abc() { def(ghi: jkl) }", + "func abc(def: Void) { ghi(jkl↓:mno) }": "func abc(def: Void) { ghi(jkl: mno) }", + "class ABC { let def = ghi(jkl↓:mno) } }": "class ABC { let def = ghi(jkl: mno) } }", + "func foo() { let dict = [1↓ : 1] }": "func foo() { let dict = [1: 1] }", + """ class Foo { #if false #else let bar = [\"key\"↓ : \"value\"] #endif } - """): - Example(""" + """: + """ class Foo { #if false #else let bar = [\"key\": \"value\"] #endif } - """), - Example(""" + """, + """ switch foo { case .bar↓ : return baz } - """): - Example(""" + """: + """ switch foo { case .bar: return baz } - """), - Example("private var action↓:(() -> Void)?"): Example("private var action: (() -> Void)?"), - ] + """, + "private var action↓:(() -> Void)?": "private var action: (() -> Void)?", + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/CommaInheritanceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/CommaInheritanceRule.swift index 03f5967b4f..9e517ce6f9 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/CommaInheritanceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/CommaInheritanceRule.swift @@ -11,51 +11,51 @@ struct CommaInheritanceRule: OptInRule, SubstitutionCorrectableRule, name: "Comma Inheritance Rule", description: "Use commas to separate types in inheritance lists", kind: .style, - nonTriggeringExamples: [ - Example("struct A: Codable, Equatable {}"), - Example("enum B: Codable, Equatable {}"), - Example("class C: Codable, Equatable {}"), - Example("protocol D: Codable, Equatable {}"), - Example("typealias E = Equatable & Codable"), - Example("func foo(_ param: T) {}"), - Example(""" + nonTriggeringExamples: #examples([ + "struct A: Codable, Equatable {}", + "enum B: Codable, Equatable {}", + "class C: Codable, Equatable {}", + "protocol D: Codable, Equatable {}", + "typealias E = Equatable & Codable", + "func foo(_ param: T) {}", + """ protocol G { associatedtype Model: Codable, Equatable } - """), - ], - triggeringExamples: [ - Example("struct A: Codable↓ & Equatable {}"), - Example("struct A: Codable↓ & Equatable {}"), - Example("struct A: Codable↓&Equatable {}"), - Example("struct A: Codable↓& Equatable {}"), - Example("enum B: Codable↓ & Equatable {}"), - Example("class C: Codable↓ & Equatable {}"), - Example("protocol D: Codable↓ & Equatable {}"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "struct A: Codable↓ & Equatable {}", + "struct A: Codable↓ & Equatable {}", + "struct A: Codable↓&Equatable {}", + "struct A: Codable↓& Equatable {}", + "enum B: Codable↓ & Equatable {}", + "class C: Codable↓ & Equatable {}", + "protocol D: Codable↓ & Equatable {}", + """ protocol G { associatedtype Model: Codable↓ & Equatable } - """), - ], - corrections: [ - Example("struct A: Codable↓ & Equatable {}"): Example("struct A: Codable, Equatable {}"), - Example("struct A: Codable↓ & Equatable {}"): Example("struct A: Codable, Equatable {}"), - Example("struct A: Codable↓&Equatable {}"): Example("struct A: Codable, Equatable {}"), - Example("struct A: Codable↓& Equatable {}"): Example("struct A: Codable, Equatable {}"), - Example("enum B: Codable↓ & Equatable {}"): Example("enum B: Codable, Equatable {}"), - Example("class C: Codable↓ & Equatable {}"): Example("class C: Codable, Equatable {}"), - Example("protocol D: Codable↓ & Equatable {}"): Example("protocol D: Codable, Equatable {}"), - Example(""" + """, + ]), + corrections: #examplesDictionary([ + "struct A: Codable↓ & Equatable {}": "struct A: Codable, Equatable {}", + "struct A: Codable↓ & Equatable {}": "struct A: Codable, Equatable {}", + "struct A: Codable↓&Equatable {}": "struct A: Codable, Equatable {}", + "struct A: Codable↓& Equatable {}": "struct A: Codable, Equatable {}", + "enum B: Codable↓ & Equatable {}": "enum B: Codable, Equatable {}", + "class C: Codable↓ & Equatable {}": "class C: Codable, Equatable {}", + "protocol D: Codable↓ & Equatable {}": "protocol D: Codable, Equatable {}", + """ protocol G { associatedtype Model: Codable↓ & Equatable } - """): Example(""" + """: """ protocol G { associatedtype Model: Codable, Equatable } - """), - ] + """, + ]) ) // MARK: - Rule diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/CommaRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/CommaRule.swift index 752396565d..77ac6e7489 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/CommaRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/CommaRule.swift @@ -28,64 +28,64 @@ struct CommaRule: CorrectableRule, SourceKitFreeRule { } """, excludeFromDocumentation: true), ], - triggeringExamples: [ - Example("func abc(a: String↓ ,b: String) { }"), - Example("func abc(a: String↓ ,b: String↓ ,c: String↓ ,d: String) { }"), - Example("abc(a: \"string\"↓,b: \"string\""), - Example("enum a { case a↓ ,b }"), - Example("let result = plus(\n first: 3↓ , // #683\n second: 4\n)"), - Example(""" + triggeringExamples: #examples([ + "func abc(a: String↓ ,b: String) { }", + "func abc(a: String↓ ,b: String↓ ,c: String↓ ,d: String) { }", + "abc(a: \"string\"↓,b: \"string\"", + "enum a { case a↓ ,b }", + "let result = plus(\n first: 3↓ , // #683\n second: 4\n)", + """ Foo( parameter: a.b.c, tag: a.d, value: a.identifier.flatMap { Int64($0) }↓ , reason: Self.abcd() ) - """), - Example(""" + """, + """ return Foo(bar: .baz, title: fuzz, message: My.Custom.message↓ , another: parameter, doIt: true, alignment: .center) - """), - Example(#"Logger.logError("Hat is too large"↓, info: [])"#), - ], - corrections: [ - Example("func abc(a: String↓,b: String) {}"): Example("func abc(a: String, b: String) {}"), - Example("abc(a: \"string\"↓,b: \"string\""): Example("abc(a: \"string\", b: \"string\""), - Example("abc(a: \"string\"↓ , b: \"string\""): Example("abc(a: \"string\", b: \"string\""), - Example("enum a { case a↓ ,b }"): Example("enum a { case a, b }"), - Example("let a = [1↓,1]\nlet b = 1\nf(1, b)"): Example("let a = [1, 1]\nlet b = 1\nf(1, b)"), - Example("let a = [1↓,1↓,1↓,1]"): Example("let a = [1, 1, 1, 1]"), - Example(""" + """, + #"Logger.logError("Hat is too large"↓, info: [])"#, + ]), + corrections: #examplesDictionary([ + "func abc(a: String↓,b: String) {}": "func abc(a: String, b: String) {}", + "abc(a: \"string\"↓,b: \"string\"": "abc(a: \"string\", b: \"string\"", + "abc(a: \"string\"↓ , b: \"string\"": "abc(a: \"string\", b: \"string\"", + "enum a { case a↓ ,b }": "enum a { case a, b }", + "let a = [1↓,1]\nlet b = 1\nf(1, b)": "let a = [1, 1]\nlet b = 1\nf(1, b)", + "let a = [1↓,1↓,1↓,1]": "let a = [1, 1, 1, 1]", + """ Foo( parameter: a.b.c, tag: a.d, value: a.identifier.flatMap { Int64($0) }↓ , reason: Self.abcd() ) - """): Example(""" + """: """ Foo( parameter: a.b.c, tag: a.d, value: a.identifier.flatMap { Int64($0) }, reason: Self.abcd() ) - """), - Example(""" + """, + """ return Foo(bar: .baz, title: fuzz, message: My.Custom.message↓ , another: parameter, doIt: true, alignment: .center) - """): Example(""" + """: """ return Foo(bar: .baz, title: fuzz, message: My.Custom.message, another: parameter, doIt: true, alignment: .center) - """), - Example(#"Logger.logError("Hat is too large"↓, info: [])"#): - Example(#"Logger.logError("Hat is too large", info: [])"#), - ] + """, + #"Logger.logError("Hat is too large"↓, info: [])"#: + #"Logger.logError("Hat is too large", info: [])"#, + ]) ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ComputedAccessorsOrderRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ComputedAccessorsOrderRuleExamples.swift index d2f0be9aa5..3c0378701b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ComputedAccessorsOrderRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ComputedAccessorsOrderRuleExamples.swift @@ -1,69 +1,69 @@ struct ComputedAccessorsOrderRuleExamples { static var nonTriggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ class Foo { var foo: Int { get { return 3 } set { _abc = newValue } } } - """), - Example(""" + """, + """ class Foo { var foo: Int { return 20 } } - """), - Example(""" + """, + """ class Foo { static var foo: Int { return 20 } } - """), - Example(""" + """, + """ class Foo { static var foo: Int { get { return 3 } set { _abc = newValue } } } - """), - Example(""" + """, + """ class Foo { var foo: Int } - """), - Example(""" + """, + """ class Foo { var foo: Int { return getValueFromDisk() } } - """), - Example(""" + """, + """ class Foo { var foo: String { return "get" } } - """), - Example(""" + """, + """ protocol Foo { var foo: Int { get } - """), - Example(""" + """, + """ protocol Foo { var foo: Int { get set } } - """), - Example(""" + """, + """ protocol Foo { var foo: Int { set get } - """), - Example(""" + """, + """ class Foo { var foo: Int { struct Bar { @@ -76,14 +76,14 @@ struct ComputedAccessorsOrderRuleExamples { return Bar().bar } } - """), - Example(""" + """, + """ var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } set { print(newValue) } } - """), - Example(""" + """, + """ var next: Int? { mutating get { defer { self.count += 1 } @@ -93,24 +93,24 @@ struct ComputedAccessorsOrderRuleExamples { self.count = newValue } } - """), - Example(""" + """, + """ extension Foo { var bar: Bool { get { _bar } set { self._bar = newValue } } } - """), - Example(""" + """, + """ extension Foo { var bar: Bool { get { _bar } set(newValue) { self._bar = newValue } } } - """), - Example(""" + """, + """ extension Reactive where Base: UITapGestureRecognizer { var tapped: CocoaAction? { get { @@ -121,8 +121,8 @@ struct ComputedAccessorsOrderRuleExamples { } } } - """), - Example(""" + """, + """ extension Test { var foo: Bool { get { @@ -133,43 +133,43 @@ struct ComputedAccessorsOrderRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { subscript(i: Int) -> Int { return 20 } } - """), - Example(""" + """, + """ class Foo { subscript(i: Int) -> Int { get { return 3 } set { _abc = newValue } } } - """), - Example(""" + """, + """ protocol Foo { subscript(i: Int) -> Int { get } } - """), - Example(""" + """, + """ protocol Foo { subscript(i: Int) -> Int { get set } } - """), - Example(""" + """, + """ protocol Foo { subscript(i: Int) -> Int { set get } } - """), - ] + """, + ]) } static var triggeringExamples: [Example] { - [ - Example(""" + #examples([ + """ class Foo { var foo: Int { ↓set { @@ -180,8 +180,8 @@ struct ComputedAccessorsOrderRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { static var foo: Int { ↓set { @@ -192,22 +192,22 @@ struct ComputedAccessorsOrderRuleExamples { } } } - """), - Example(""" + """, + """ var foo: Int { ↓set { print(newValue) } get { return 20 } } - """), - Example(""" + """, + """ extension Foo { var bar: Bool { ↓set { print(bar) } get { _bar } } } - """), - Example(""" + """, + """ class Foo { var foo: Int { ↓set { @@ -218,8 +218,8 @@ struct ComputedAccessorsOrderRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { subscript(i: Int) -> Int { ↓set { @@ -230,7 +230,7 @@ struct ComputedAccessorsOrderRuleExamples { } } } - """), - ] + """, + ]) } } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ConditionalReturnsOnNewlineRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ConditionalReturnsOnNewlineRule.swift index 92d28780d2..b574c5abd1 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ConditionalReturnsOnNewlineRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ConditionalReturnsOnNewlineRule.swift @@ -9,28 +9,28 @@ struct ConditionalReturnsOnNewlineRule: Rule { name: "Conditional Returns on Newline", description: "Conditional statements should always return on the next line", kind: .style, - nonTriggeringExamples: [ - Example("guard true else {\n return true\n}"), - Example("guard true,\n let x = true else {\n return true\n}"), - Example("if true else {\n return true\n}"), - Example("if true,\n let x = true else {\n return true\n}"), - Example("if textField.returnKeyType == .Next {"), - Example("if true { // return }"), - Example(""" + nonTriggeringExamples: #examples([ + "guard true else {\n return true\n}", + "guard true,\n let x = true else {\n return true\n}", + "if true else {\n return true\n}", + "if true,\n let x = true else {\n return true\n}", + "if textField.returnKeyType == .Next {", + "if true { // return }", + """ guard something else { return } - """), - ], - triggeringExamples: [ - Example("↓guard true else { return }"), - Example("↓if true { return }"), - Example("↓if true { break } else { return }"), - Example("↓if true { break } else { return }"), - Example("↓if true { return \"YES\" } else { return \"NO\" }"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "↓guard true else { return }", + "↓if true { return }", + "↓if true { break } else { return }", + "↓if true { break } else { return }", + "↓if true { return \"YES\" } else { return \"NO\" }", + """ ↓guard condition else { XCTFail(); return } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ContrastedOpeningBraceRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ContrastedOpeningBraceRuleExamples.swift index 5caf1fda74..5e7881eac2 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ContrastedOpeningBraceRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ContrastedOpeningBraceRuleExamples.swift @@ -2,45 +2,45 @@ // swiftlint:disable:next type_body_length struct ContrastedOpeningBraceRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ func abc() { } - """), - Example(""" + """, + """ [].map() { $0 } - """), - Example(""" + """, + """ [].map( { } ) - """), - Example(""" + """, + """ if let a = b { } - """), - Example(""" + """, + """ while a == b { } - """), - Example(""" + """, + """ guard let a = b else { } - """), - Example(""" + """, + """ struct Rule { } - """), - Example(""" + """, + """ struct Parent { struct Child @@ -48,8 +48,8 @@ struct ContrastedOpeningBraceRuleExamples { let foo: Int } } - """), - Example(""" + """, + """ func f(rect: CGRect) { { @@ -57,8 +57,8 @@ struct ContrastedOpeningBraceRuleExamples { print(centre) }() } - """), - Example(""" + """, + """ func f(rect: CGRect) -> () -> Void { { @@ -66,14 +66,14 @@ struct ContrastedOpeningBraceRuleExamples { print(centre) } } - """), - Example(""" + """, + """ func f() -> () -> Void { {} } - """), - Example(""" + """, + """ @MyProperty class Rule: NSObject { @@ -82,29 +82,29 @@ struct ContrastedOpeningBraceRuleExamples { return "" } } - """), - Example(""" + """, + """ self.foo( ( "String parameter", { "Do something here" } ) ) - """), - Example(##"let pattern = #/(\{(?\w+)\})/#"##), - Example(""" + """, + ##"let pattern = #/(\{(?\w+)\})/#"##, + """ if c {} else {} - """), - Example(""" + """, + """ if c /* comment */ { return } - """), - Example(""" + """, + """ if c1 { return @@ -115,14 +115,14 @@ struct ContrastedOpeningBraceRuleExamples { { return } - """), - Example(""" + """, + """ let a = f.map { a in a } - """), - ] + """, + ]) static let triggeringExamples = [ Example(""" @@ -237,20 +237,20 @@ struct ContrastedOpeningBraceRuleExamples { """), ] - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ struct Rule{} - """): Example(""" + """: """ struct Rule {} - """), - Example(""" + """, + """ struct Parent { struct Child { let foo: Int } } - """): Example(""" + """: """ struct Parent { struct Child @@ -258,46 +258,46 @@ struct ContrastedOpeningBraceRuleExamples { let foo: Int } } - """), - Example(""" + """, + """ [].map(){ $0 } - """): Example(""" + """: """ [].map() { $0 } - """), - Example(""" + """, + """ if a == b{ } - """): Example(""" + """: """ if a == b { } - """), - Example(""" + """, + """ @MyProperty actor MyActor { } - """): Example(""" + """: """ @MyProperty actor MyActor { } - """), - Example(""" + """, + """ actor MyActor where T: U { } - """): Example(""" + """: """ actor MyActor where T: U { } - """), - Example(""" + """, + """ do { } catch { } - """): Example(""" + """: """ do { @@ -305,14 +305,14 @@ struct ContrastedOpeningBraceRuleExamples { { } - """), - Example(""" + """, + """ do { } catch MyError.unknown { } - """): Example(""" + """: """ do { @@ -320,42 +320,42 @@ struct ContrastedOpeningBraceRuleExamples { { } - """), - Example(""" + """, + """ defer { } - """): Example(""" + """: """ defer { } - """), - Example(""" + """, + """ for a in b where a == c { } - """): Example(""" + """: """ for a in b where a == c { } - """), - Example(""" + """, + """ if varDecl.parent?.is(CodeBlockItemSyntax.self) == true // Local variable declaration || varDecl.bindings.onlyElement?.accessor != nil // Computed property || !node.type.is(SimpleTypeIdentifierSyntax.self) { // Complex or collection type return .visitChildren } - """): Example(""" + """: """ if varDecl.parent?.is(CodeBlockItemSyntax.self) == true // Local variable declaration || varDecl.bindings.onlyElement?.accessor != nil // Computed property || !node.type.is(SimpleTypeIdentifierSyntax.self) { // Complex or collection type return .visitChildren } - """), - Example(""" + """, + """ @MyProperty class Rule { var a: String { @@ -364,7 +364,7 @@ struct ContrastedOpeningBraceRuleExamples { } } } - """): Example(""" + """: """ @MyProperty class Rule { var a: String @@ -375,28 +375,28 @@ struct ContrastedOpeningBraceRuleExamples { } } } - """), - Example(""" + """, + """ precedencegroup Group{ assignment: true } - """): Example(""" + """: """ precedencegroup Group { assignment: true } - """), - Example(""" + """, + """ if c /* comment */ { return } - """): Example(""" + """: """ if c /* comment */ { return } - """), - Example(""" + """, + """ func foo() { if q1, q2 { do1() @@ -404,7 +404,7 @@ struct ContrastedOpeningBraceRuleExamples { do2() } } - """): Example(""" + """: """ func foo() { if q1, q2 @@ -415,61 +415,61 @@ struct ContrastedOpeningBraceRuleExamples { do2() } } - """), - Example(""" + """, + """ if "test".isEmpty // swiftlint:disable:next contrasted_opening_brace { // code here } - """): Example(""" + """: """ if "test".isEmpty // swiftlint:disable:next contrasted_opening_brace { // code here } - """), - Example(""" + """, + """ private func f() // comment { let a = 1 } - """): Example(""" + """: """ private func f() // comment { let a = 1 } - """), - Example(""" + """, + """ while true /* endless loop */ { // nothing } - """): Example(""" + """: """ while true /* endless loop */ { // nothing } - """), - Example(""" + """, + """ a.b { $0 } .c { $1 } - """): Example(""" + """: """ a.b { $0 } .c { $1 } - """), - Example(""" + """, + """ a { $0 } b: { $1 } - """): Example(""" + """: """ a { $0 @@ -477,6 +477,6 @@ struct ContrastedOpeningBraceRuleExamples { { $1 } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ControlStatementRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ControlStatementRule.swift index 290837dfa7..4d4e174ee7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ControlStatementRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ControlStatementRule.swift @@ -32,45 +32,45 @@ struct ControlStatementRule: Rule { Example("if ({ true }()) {}"), Example("if ({if i < 1 { true } else { false }}()) {}", excludeFromDocumentation: true), ], - triggeringExamples: [ - Example("↓if (condition) {}"), - Example("↓if(condition) {}"), - Example("↓if (condition == endIndex) {}"), - Example("↓if ((a || b) && (c || d)) {}"), - Example("↓if ((min...max).contains(value)) {}"), - Example("↓guard (condition) else {}"), - Example("↓while (condition) {}"), - Example("↓while(condition) {}"), - Example("do { ; } ↓while(condition) {}"), - Example("do { ; } ↓while (condition) {}"), - Example("↓switch (foo) {}"), - Example("do {} ↓catch(let error as NSError) {}"), - Example("↓if (max(a, b) < c) {}"), - ], - corrections: [ - Example("↓if (condition) {}"): Example("if condition {}"), - Example("↓if(condition) {}"): Example("if condition {}"), - Example("↓if (condition == endIndex) {}"): Example("if condition == endIndex {}"), - Example("↓if ((a || b) && (c || d)) {}"): Example("if (a || b) && (c || d) {}"), - Example("↓if ((min...max).contains(value)) {}"): Example("if (min...max).contains(value) {}"), - Example("↓guard (condition) else {}"): Example("guard condition else {}"), - Example("↓while (condition) {}"): Example("while condition {}"), - Example("↓while(condition) {}"): Example("while condition {}"), - Example("do {} ↓while (condition) {}"): Example("do {} while condition {}"), - Example("do {} ↓while(condition) {}"): Example("do {} while condition {}"), - Example("do { ; } ↓while(condition) {}"): Example("do { ; } while condition {}"), - Example("do { ; } ↓while (condition) {}"): Example("do { ; } while condition {}"), - Example("↓switch (foo) {}"): Example("switch foo {}"), - Example("do {} ↓catch(let error as NSError) {}"): Example("do {} catch let error as NSError {}"), - Example("↓if (max(a, b) < c) {}"): Example("if max(a, b) < c {}"), - Example(""" + triggeringExamples: #examples([ + "↓if (condition) {}", + "↓if(condition) {}", + "↓if (condition == endIndex) {}", + "↓if ((a || b) && (c || d)) {}", + "↓if ((min...max).contains(value)) {}", + "↓guard (condition) else {}", + "↓while (condition) {}", + "↓while(condition) {}", + "do { ; } ↓while(condition) {}", + "do { ; } ↓while (condition) {}", + "↓switch (foo) {}", + "do {} ↓catch(let error as NSError) {}", + "↓if (max(a, b) < c) {}", + ]), + corrections: #examplesDictionary([ + "↓if (condition) {}": "if condition {}", + "↓if(condition) {}": "if condition {}", + "↓if (condition == endIndex) {}": "if condition == endIndex {}", + "↓if ((a || b) && (c || d)) {}": "if (a || b) && (c || d) {}", + "↓if ((min...max).contains(value)) {}": "if (min...max).contains(value) {}", + "↓guard (condition) else {}": "guard condition else {}", + "↓while (condition) {}": "while condition {}", + "↓while(condition) {}": "while condition {}", + "do {} ↓while (condition) {}": "do {} while condition {}", + "do {} ↓while(condition) {}": "do {} while condition {}", + "do { ; } ↓while(condition) {}": "do { ; } while condition {}", + "do { ; } ↓while (condition) {}": "do { ; } while condition {}", + "↓switch (foo) {}": "switch foo {}", + "do {} ↓catch(let error as NSError) {}": "do {} catch let error as NSError {}", + "↓if (max(a, b) < c) {}": "if max(a, b) < c {}", + """ if (a), ( b == 1 ) {} - """): Example(""" + """: """ if a, b == 1 {} - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/DirectReturnRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/DirectReturnRule.swift index 6f645252ee..87a58918b5 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/DirectReturnRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/DirectReturnRule.swift @@ -9,15 +9,15 @@ struct DirectReturnRule: Rule { name: "Direct Return", description: "Directly return the expression instead of assigning it to a variable first", kind: .style, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ func f() -> Int { let b = 2 let a = 1 return b } - """), - Example(""" + """, + """ struct S { var a: Int { var b = 1 @@ -25,31 +25,31 @@ struct DirectReturnRule: Rule { return b } } - """), - Example(""" + """, + """ func f() -> Int { let b = 2 f() return b } - """), - Example(""" + """, + """ func f() -> Int { { i in let b = 2 return i }(1) } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ func f() -> Int { let ↓b = 2 return b } - """), - Example(""" + """, + """ struct S { var a: Int { var ↓b = 1 @@ -57,22 +57,22 @@ struct DirectReturnRule: Rule { return b } } - """), - Example(""" + """, + """ func f() -> Bool { let a = 1, ↓b = true return b } - """), - Example(""" + """, + """ func f() -> Int { { _ in let ↓b = 2 return b }(1) } - """), - Example(""" + """, + """ func f(i: Int) -> Int { if i > 1 { let ↓a = 2 @@ -82,20 +82,20 @@ struct DirectReturnRule: Rule { return b } } - """), - ], - corrections: [ - Example(""" + """, + ]), + corrections: #examplesDictionary([ + """ func f() -> Int { let b = 2 return b } - """): Example(""" + """: """ func f() -> Int { return 2 } - """), - Example(""" + """, + """ struct S { var a: Int { var b = 2 > 1 @@ -106,7 +106,7 @@ struct DirectReturnRule: Rule { } func f() -> Int { 1 } } - """): Example(""" + """: """ struct S { var a: Int { // comment @@ -116,19 +116,19 @@ struct DirectReturnRule: Rule { } func f() -> Int { 1 } } - """), - Example(""" + """, + """ func f() -> Bool { let a = 1, b = true return b } - """): Example(""" + """: """ func f() -> Bool { let a = 1 return true } - """), - Example(""" + """, + """ func f() -> Int { { _ in // A comment @@ -137,7 +137,7 @@ struct DirectReturnRule: Rule { return b }(1) } - """): Example(""" + """: """ func f() -> Int { { _ in // A comment @@ -145,38 +145,38 @@ struct DirectReturnRule: Rule { return 2 }(1) } - """), - Example(""" + """, + """ func f() -> UIView { let view = instantiateView() as! UIView // swiftlint:disable:this force_cast return view } - """): Example(""" + """: """ func f() -> UIView { return instantiateView() as! UIView // swiftlint:disable:this force_cast } - """), - Example(""" + """, + """ func f() -> UIView { let view = instantiateView() as! UIView // swiftlint:disable:this force_cast return view // return the view } - """): Example(""" + """: """ func f() -> UIView { return instantiateView() as! UIView // swiftlint:disable:this force_cast // return the view } - """), - Example(""" + """, + """ func f() -> Bool { let b : Bool = true return b } - """): Example(""" + """: """ func f() -> Bool { return true as Bool } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParametersRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParametersRule.swift index 6facb7ecac..668bdc255e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParametersRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParametersRule.swift @@ -9,27 +9,27 @@ struct EmptyParametersRule: Rule { name: "Empty Parameters", description: "Prefer `() -> ` over `Void -> `", kind: .style, - nonTriggeringExamples: [ - Example("let abc: () -> Void = {}"), - Example("func foo(completion: () -> Void)"), - Example("func foo(completion: () throws -> Void)"), - Example("let foo: (ConfigurationTests) -> Void throws -> Void)"), - Example("let foo: (ConfigurationTests) -> Void throws -> Void)"), - Example("let foo: (ConfigurationTests) ->Void throws -> Void)"), - ], - triggeringExamples: [ - Example("let abc: ↓(Void) -> Void = {}"), - Example("func foo(completion: ↓(Void) -> Void)"), - Example("func foo(completion: ↓(Void) throws -> Void)"), - Example("let foo: ↓(Void) -> () throws -> Void)"), - ], - corrections: [ - Example("let abc: ↓(Void) -> Void = {}"): Example("let abc: () -> Void = {}"), - Example("func foo(completion: ↓(Void) -> Void)"): Example("func foo(completion: () -> Void)"), - Example("func foo(completion: ↓(Void) throws -> Void)"): - Example("func foo(completion: () throws -> Void)"), - Example("let foo: ↓(Void) -> () throws -> Void)"): Example("let foo: () -> () throws -> Void)"), - ] + nonTriggeringExamples: #examples([ + "let abc: () -> Void = {}", + "func foo(completion: () -> Void)", + "func foo(completion: () throws -> Void)", + "let foo: (ConfigurationTests) -> Void throws -> Void)", + "let foo: (ConfigurationTests) -> Void throws -> Void)", + "let foo: (ConfigurationTests) ->Void throws -> Void)", + ]), + triggeringExamples: #examples([ + "let abc: ↓(Void) -> Void = {}", + "func foo(completion: ↓(Void) -> Void)", + "func foo(completion: ↓(Void) throws -> Void)", + "let foo: ↓(Void) -> () throws -> Void)", + ]), + corrections: #examplesDictionary([ + "let abc: ↓(Void) -> Void = {}": "let abc: () -> Void = {}", + "func foo(completion: ↓(Void) -> Void)": "func foo(completion: () -> Void)", + "func foo(completion: ↓(Void) throws -> Void)": + "func foo(completion: () throws -> Void)", + "let foo: ↓(Void) -> () throws -> Void)": "let foo: () -> () throws -> Void)", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParenthesesWithTrailingClosureRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParenthesesWithTrailingClosureRule.swift index de7c426950..cb882d7d6b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParenthesesWithTrailingClosureRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/EmptyParenthesesWithTrailingClosureRule.swift @@ -10,39 +10,39 @@ struct EmptyParenthesesWithTrailingClosureRule: Rule { description: "When using trailing closures, empty parentheses should be avoided " + "after the method call", kind: .style, - nonTriggeringExamples: [ - Example("[1, 2].map { $0 + 1 }"), - Example("[1, 2].map({ $0 + 1 })"), - Example("[1, 2].reduce(0) { $0 + $1 }"), - Example("[1, 2].map { number in\n number + 1 \n}"), - Example("let isEmpty = [1, 2].isEmpty()"), - Example(""" + nonTriggeringExamples: #examples([ + "[1, 2].map { $0 + 1 }", + "[1, 2].map({ $0 + 1 })", + "[1, 2].reduce(0) { $0 + $1 }", + "[1, 2].map { number in\n number + 1 \n}", + "let isEmpty = [1, 2].isEmpty()", + """ UIView.animateWithDuration(0.3, animations: { self.disableInteractionRightView.alpha = 0 }, completion: { _ in () }) - """), - ], - triggeringExamples: [ - Example("[1, 2].map↓() { $0 + 1 }"), - Example("[1, 2].map↓( ) { $0 + 1 }"), - Example("[1, 2].map↓() { number in\n number + 1 \n}"), - Example("[1, 2].map↓( ) { number in\n number + 1 \n}"), - Example("func foo() -> [Int] {\n return [1, 2].map↓() { $0 + 1 }\n}"), - ], - corrections: [ - Example("[1, 2].map↓() { $0 + 1 }"): Example("[1, 2].map { $0 + 1 }"), - Example("[1, 2].map↓( ) { $0 + 1 }"): Example("[1, 2].map { $0 + 1 }"), - Example("[1, 2].map↓() { number in\n number + 1 \n}"): - Example("[1, 2].map { number in\n number + 1 \n}"), - Example("[1, 2].map↓( ) { number in\n number + 1 \n}"): - Example("[1, 2].map { number in\n number + 1 \n}"), - Example("func foo() -> [Int] {\n return [1, 2].map↓() { $0 + 1 }\n}"): - Example("func foo() -> [Int] {\n return [1, 2].map { $0 + 1 }\n}"), - Example("class C {\n#if true\nfunc f() {\n[1, 2].map↓() { $0 + 1 }\n}\n#endif\n}"): - Example("class C {\n#if true\nfunc f() {\n[1, 2].map { $0 + 1 }\n}\n#endif\n}"), - ] + """, + ]), + triggeringExamples: #examples([ + "[1, 2].map↓() { $0 + 1 }", + "[1, 2].map↓( ) { $0 + 1 }", + "[1, 2].map↓() { number in\n number + 1 \n}", + "[1, 2].map↓( ) { number in\n number + 1 \n}", + "func foo() -> [Int] {\n return [1, 2].map↓() { $0 + 1 }\n}", + ]), + corrections: #examplesDictionary([ + "[1, 2].map↓() { $0 + 1 }": "[1, 2].map { $0 + 1 }", + "[1, 2].map↓( ) { $0 + 1 }": "[1, 2].map { $0 + 1 }", + "[1, 2].map↓() { number in\n number + 1 \n}": + "[1, 2].map { number in\n number + 1 \n}", + "[1, 2].map↓( ) { number in\n number + 1 \n}": + "[1, 2].map { number in\n number + 1 \n}", + "func foo() -> [Int] {\n return [1, 2].map↓() { $0 + 1 }\n}": + "func foo() -> [Int] {\n return [1, 2].map { $0 + 1 }\n}", + "class C {\n#if true\nfunc f() {\n[1, 2].map↓() { $0 + 1 }\n}\n#endif\n}": + "class C {\n#if true\nfunc f() {\n[1, 2].map { $0 + 1 }\n}\n#endif\n}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/FileHeaderRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/FileHeaderRule.swift index a218d12a8a..441b55e04d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/FileHeaderRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/FileHeaderRule.swift @@ -13,15 +13,15 @@ struct FileHeaderRule: Rule { "The SWIFTLINT_CURRENT_FILENAME placeholder can optionally be used in the " + "required and forbidden patterns. It will be replaced by the real file name.", kind: .style, - nonTriggeringExamples: [ - Example("let foo = \"Copyright\""), - Example("let foo = 2 // Copyright"), - Example("let foo = 2\n // Copyright"), - ], - triggeringExamples: [ - Example("// ↓Copyright"), - Example("//\n// ↓Copyright"), - Example(""" + nonTriggeringExamples: #examples([ + "let foo = \"Copyright\"", + "let foo = 2 // Copyright", + "let foo = 2\n // Copyright", + ]), + triggeringExamples: #examples([ + "// ↓Copyright", + "//\n// ↓Copyright", + """ // // FileHeaderRule.swift // SwiftLint @@ -29,8 +29,8 @@ struct FileHeaderRule: Rule { // Created by Marcelo Fabri on 27/11/16. // ↓Copyright © 2016 Realm. All rights reserved. // - """), - ].skipWrappingInCommentTests() + """, + ]).skipWrappingInCommentTests() ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitGetterRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitGetterRuleExamples.swift index 433ee125e3..75646fae67 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitGetterRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitGetterRuleExamples.swift @@ -1,44 +1,44 @@ struct ImplicitGetterRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example(""" + static let nonTriggeringExamples: [Example] = #examples([ + """ class Foo { var foo: Int { get { return 3 } set { _abc = newValue } } } - """), - Example(""" + """, + """ class Foo { var foo: Int { return 20 } } - """), - Example(""" + """, + """ class Foo { static var foo: Int { return 20 } } - """), - Example(""" + """, + """ class Foo { static var foo: Int { get { return 3 } set { _abc = newValue } } } - """), - Example(""" + """, + """ class Foo { var foo: Int { get { _foo } _modify { yield &_foo } } } - """), - Example(""" + """, + """ class Foo { var _foo: Int var foo: Int { @@ -47,37 +47,37 @@ struct ImplicitGetterRuleExamples { get { _foo } } } - """), - Example(""" + """, + """ class Foo { var foo: Int } - """), - Example(""" + """, + """ class Foo { var foo: Int { return getValueFromDisk() } } - """), - Example(""" + """, + """ class Foo { var foo: String { return "get" } } - """), - Example(""" + """, + """ protocol Foo { var foo: Int { get } } - """), - Example(""" + """, + """ protocol Foo { var foo: Int { get set } } - """), - Example(""" + """, + """ class Foo { var foo: Int { struct Bar { @@ -90,37 +90,37 @@ struct ImplicitGetterRuleExamples { return Bar().bar } } - """), - Example(""" + """, + """ var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } - """), - Example(""" + """, + """ var next: Int? { mutating get { defer { self.count += 1 } return self.count } } - """), - Example(""" + """, + """ extension Foo { var bar: Bool { get { _bar } set { self._bar = newValue } } } - """), - Example(""" + """, + """ extension Foo { var bar: Bool { get { _bar } set(newValue) { self._bar = newValue } } } - """), - Example(""" + """, + """ extension Float { var clamped: Float { set { @@ -131,8 +131,8 @@ struct ImplicitGetterRuleExamples { } } } - """), - Example(""" + """, + """ extension Reactive where Base: UITapGestureRecognizer { var tapped: CocoaAction? { get { @@ -143,8 +143,8 @@ struct ImplicitGetterRuleExamples { } } } - """), - Example(""" + """, + """ extension Test { var foo: Bool { get { @@ -155,33 +155,33 @@ struct ImplicitGetterRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { subscript(i: Int) -> Int { return 20 } } - """), - Example(""" + """, + """ class Foo { subscript(i: Int) -> Int { get { return 3 } set { _abc = newValue } } } - """), - Example(""" + """, + """ protocol Foo { subscript(i: Int) -> Int { get } } - """), - Example(""" + """, + """ protocol Foo { subscript(i: Int) -> Int { get set } } - """), - Example(""" + """, + """ class DatabaseEntity { var isSynced: Bool { get async { @@ -189,8 +189,8 @@ struct ImplicitGetterRuleExamples { } } } - """), - Example(""" + """, + """ struct Test { subscript(value: Int) -> Int { get throws { @@ -202,11 +202,11 @@ struct ImplicitGetterRuleExamples { } } } - """), - ] + """, + ]) - static let triggeringExamples: [Example] = [ - Example(""" + static let triggeringExamples: [Example] = #examples([ + """ class Foo { var foo: Int { ↓get { @@ -214,15 +214,15 @@ struct ImplicitGetterRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { var foo: Int { ↓get{ return 20 } } } - """), - Example(""" + """, + """ class Foo { static var foo: Int { ↓get { @@ -230,13 +230,13 @@ struct ImplicitGetterRuleExamples { } } } - """), - Example(""" + """, + """ var foo: Int { ↓get { return 20 } } - """), - Example(""" + """, + """ class Foo { @objc func bar() {} var foo: Int { @@ -245,15 +245,15 @@ struct ImplicitGetterRuleExamples { } } } - """), - Example(""" + """, + """ extension Foo { var bar: Bool { ↓get { _bar } } } - """), - Example(""" + """, + """ class Foo { subscript(i: Int) -> Int { ↓get { @@ -261,6 +261,6 @@ struct ImplicitGetterRuleExamples { } } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitReturnRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitReturnRuleExamples.swift index df92fb92da..1fbb6eec77 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitReturnRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ImplicitReturnRuleExamples.swift @@ -1,82 +1,82 @@ struct ImplicitReturnRuleExamples { struct ClosureExamples { - static let nonTriggeringExamples = [ - Example("foo.map { $0 + 1 }"), - Example("foo.map({ $0 + 1 })"), - Example("foo.map { value in value + 1 }"), - Example(""" + static let nonTriggeringExamples = #examples([ + "foo.map { $0 + 1 }", + "foo.map({ $0 + 1 })", + "foo.map { value in value + 1 }", + """ [1, 2].first(where: { true }) - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ foo.map { value in ↓return value + 1 } - """), - Example(""" + """, + """ foo.map { ↓return $0 + 1 } - """), - Example("foo.map({ ↓return $0 + 1})"), - Example(""" + """, + "foo.map({ ↓return $0 + 1})", + """ [1, 2].first(where: { ↓return true }) - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ foo.map { value in // Important comment return value + 1 } - """): Example(""" + """: """ foo.map { value in // Important comment value + 1 } - """), - Example(""" + """, + """ foo.map { return $0 + 1 } - """): Example(""" + """: """ foo.map { $0 + 1 } - """), - Example("foo.map({ return $0 + 1 })"): Example("foo.map({ $0 + 1 })"), - Example(""" + """, + "foo.map({ return $0 + 1 })": "foo.map({ $0 + 1 })", + """ [1, 2].first(where: { return true }) - """): Example(""" + """: """ [1, 2].first(where: { true }) - """), - ] + """, + ]) } struct FunctionExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ func foo() -> Int { 0 } - """), - Example(""" + """, + """ class Foo { func foo() -> Int { 0 } } - """), - Example(""" + """, + """ func fetch() -> Data? { do { return try loadData() @@ -84,86 +84,86 @@ struct ImplicitReturnRuleExamples { return nil } } - """), - Example(""" + """, + """ func f() -> Int { let i = 4 return i } - """), - Example(""" + """, + """ func f() -> Int { return 3 let i = 2 } - """), - Example(""" + """, + """ func f() -> Int { return g() func g() -> Int { 4 } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ func foo() -> Int { ↓return 0 } - """), - Example(""" + """, + """ class Foo { func foo() -> Int { ↓return 0 } } - """), - Example(""" + """, + """ func f() { ↓return } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ func foo() -> Int { return 0 } - """): Example(""" + """: """ func foo() -> Int { 0 } - """), - Example(""" + """, + """ class Foo { func foo() -> Int { return 0 } } - """): Example(""" + """: """ class Foo { func foo() -> Int { 0 } } - """), - Example(""" + """, + """ func f() { // Comment ↓return // Another comment } - """): Example(""" + """: """ func f() { // Comment \("") // Another comment } - """), - ] + """, + ]) } struct GetterExamples { - static let nonTriggeringExamples = [ - Example("var foo: Bool { true }"), - Example(""" + static let nonTriggeringExamples = #examples([ + "var foo: Bool { true }", + """ class Foo { var bar: Int { get { @@ -171,19 +171,19 @@ struct ImplicitReturnRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { static var bar: Int { 0 } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example("var foo: Bool { ↓return true }"), - Example(""" + static let triggeringExamples = #examples([ + "var foo: Bool { ↓return true }", + """ class Foo { var bar: Int { get { @@ -191,19 +191,19 @@ struct ImplicitReturnRuleExamples { } } } - """), - Example(""" + """, + """ class Foo { static var bar: Int { ↓return 0 } } - """), - ] + """, + ]) - static let corrections = [ - Example("var foo: Bool { return true }"): Example("var foo: Bool { true }"), - Example(""" + static let corrections = #examplesDictionary([ + "var foo: Bool { return true }": "var foo: Bool { true }", + """ class Foo { var bar: Int { get { @@ -211,7 +211,7 @@ struct ImplicitReturnRuleExamples { } } } - """): Example(""" + """: """ class Foo { var bar: Int { get { @@ -219,13 +219,13 @@ struct ImplicitReturnRuleExamples { } } } - """), - ] + """, + ]) } struct InitializerExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ class C { let i: Int init(i: Int) { @@ -236,119 +236,119 @@ struct ImplicitReturnRuleExamples { self.i = 2 } } - """), - Example(""" + """, + """ class C { init?() { let i = 1 return nil } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class C { init() { ↓return } } - """), - Example(""" + """, + """ class C { init?() { ↓return nil } } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ class C { init() { ↓return } } - """): Example(""" + """: """ class C { init() { \("") } } - """), - Example(""" + """, + """ class C { init?() { ↓return nil } } - """): Example(""" + """: """ class C { init?() { nil } } - """), - ] + """, + ]) } struct SubscriptExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ class C { subscript(i: Int) -> Int { let res = i return res } } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class C { subscript(i: Int) -> Int { ↓return i } } - """), - ] + """, + ]) - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ class C { subscript(i: Int) -> Int { ↓return i } } - """): Example(""" + """: """ class C { subscript(i: Int) -> Int { i } } - """), - ] + """, + ]) } struct MixedExamples { - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ func foo() -> Int { ↓return [1, 2].first(where: { ↓return true }) } - """): Example(""" + """: """ func foo() -> Int { [1, 2].first(where: { true }) } - """), - ] + """, + ]) } static let nonTriggeringExamples = diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/InclusiveLanguageRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/InclusiveLanguageRuleExamples.swift index 39b9eb3b9b..b1b24e067d 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/InclusiveLanguageRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/InclusiveLanguageRuleExamples.swift @@ -1,44 +1,44 @@ internal struct InclusiveLanguageRuleExamples { // MARK: - Default config - static let nonTriggeringExamples: [Example] = [ - Example("let foo = \"abc\""), - Example(""" + static let nonTriggeringExamples: [Example] = #examples([ + "let foo = \"abc\"", + """ enum AllowList { case foo, bar } - """), - Example("func updateAllowList(add: String) {}"), - Example(""" + """, + "func updateAllowList(add: String) {}", + """ enum WalletItemType { case visa case mastercard } - """), - Example("func chargeMasterCard(_ card: Card) {}"), - ] + """, + "func chargeMasterCard(_ card: Card) {}", + ]) - static let triggeringExamples: [Example] = [ - Example("let ↓slave = \"abc\""), - Example(""" + static let triggeringExamples: [Example] = #examples([ + "let ↓slave = \"abc\"", + """ enum ↓BlackList { case foo, bar } - """), - Example("func ↓updateWhiteList(add: String) {}"), - Example(""" + """, + "func ↓updateWhiteList(add: String) {}", + """ enum ListType { case ↓whitelist case ↓blacklist } - """), - Example("init(↓master: String, ↓slave: String) {}"), - Example(""" + """, + "init(↓master: String, ↓slave: String) {}", + """ final class FooBar { func register<↓Master, ↓Slave>(one: Master, two: Slave) {} } - """), - ] + """, + ]) // MARK: - Non-default config diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/IndentationWidthRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/IndentationWidthRule.swift index bc8b11ace0..3552527099 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/IndentationWidthRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/IndentationWidthRule.swift @@ -48,38 +48,38 @@ struct IndentationWidthRule: OptInRule { description: "Indent code using either one tab or the configured amount of spaces, " + "unindent to match previous indentations. Don't indent the first line.", kind: .style, - nonTriggeringExamples: [ - Example("firstLine\nsecondLine"), - Example("firstLine\n secondLine"), - Example("firstLine\n\tsecondLine\n\t\tthirdLine\n\n\t\tfourthLine"), - Example("firstLine\n\tsecondLine\n\t\tthirdLine\n\t//test\n\t\tfourthLine"), - Example("firstLine\n secondLine\n thirdLine\nfourthLine"), - Example(""" + nonTriggeringExamples: #examples([ + "firstLine\nsecondLine", + "firstLine\n secondLine", + "firstLine\n\tsecondLine\n\t\tthirdLine\n\n\t\tfourthLine", + "firstLine\n\tsecondLine\n\t\tthirdLine\n\t//test\n\t\tfourthLine", + "firstLine\n secondLine\n thirdLine\nfourthLine", + """ guard let x = foo(), let y = bar() else { return } - """), - Example(""" + """, + """ if let x = foo(), let y = bar() { doSomething() } - """), - Example(""" + """, + """ while let x = foo(), let y = bar() { doSomething() } - """), - Example(""" + """, + """ if let x = foo(), let y = bar(), let z = baz() { doSomething() } - """), - ], + """, + ]), triggeringExamples: [ Example("↓ firstLine", testMultiByteOffsets: false, testDisableCommand: false), Example("firstLine\n secondLine"), diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/LeadingWhitespaceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/LeadingWhitespaceRule.swift index a269fde54f..c0867044f4 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/LeadingWhitespaceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/LeadingWhitespaceRule.swift @@ -9,13 +9,13 @@ struct LeadingWhitespaceRule: CorrectableRule, SourceKitFreeRule { name: "Leading Whitespace", description: "Files should not contain leading whitespace", kind: .style, - nonTriggeringExamples: [ - Example("//") - ], - triggeringExamples: [ - Example("\n//"), - Example(" //"), - ].skipMultiByteOffsetTests().skipDisableCommandTests(), + nonTriggeringExamples: #examples([ + "//" + ]), + triggeringExamples: #examples([ + "\n//", + " //", + ]).skipMultiByteOffsetTests().skipDisableCommandTests(), corrections: [ Example("\n //", testMultiByteOffsets: false): Example("//") ] diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/LetVarWhitespaceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/LetVarWhitespaceRule.swift index bf3d10f471..742d895183 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/LetVarWhitespaceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/LetVarWhitespaceRule.swift @@ -121,32 +121,32 @@ struct LetVarWhitespaceRule: Rule { @Flag(help: "help") var useAlternativeExcluding = false """#, excludeFromDocumentation: true), - ].map(Self.wrapIntoClass) + [ - Example(""" + ].map(Self.wrapIntoClass) + #examples([ + """ a = 2 - """), - Example(""" + """, + """ a = 2 var b = 3 - """), - Example(""" + """, + """ #warning("message") let a = 2 - """), - Example(""" + """, + """ #if os(macOS) let a = 2 #endif - """), + """, // Don't trigger in closure bodies. - Example(""" + """ f { let a = 1 return a } - """), - Example(""" + """, + """ func f() { #if os(macOS) let a = 2 @@ -155,42 +155,42 @@ struct LetVarWhitespaceRule: Rule { return 1 #endif } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ let a ↓func x() {} - """), - Example(""" + """, + """ var x = 0 ↓@objc func f() {} - """), - Example(""" + """, + """ var x = 0 ↓@objc func f() {} - """), - Example(""" + """, + """ @objc func f() { } ↓var x = 0 - """), - Example(""" + """, + """ func f() {} ↓@Wapper let isNumber = false @Wapper var isEnabled = true ↓func g() {} - """), - Example(""" + """, + """ #if os(macOS) let a = 0 ↓func f() {} #endif - """), - ].map(Self.wrapIntoClass) + [ + """, + ]).map(Self.wrapIntoClass) + [ Example(""" let a = 2 ↓b = 1 diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/LiteralExpressionEndIndentationRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/LiteralExpressionEndIndentationRule.swift index 75405279c2..8d81007a2b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/LiteralExpressionEndIndentationRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/LiteralExpressionEndIndentationRule.swift @@ -10,105 +10,105 @@ struct LiteralExpressionEndIndentationRule: Rule, OptInRule { name: "Literal Expression End Indentation", description: "Array and dictionary literal end should have the same indentation as the line that started it", kind: .style, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ [1, 2, 3] - """), - Example(""" + """, + """ [1, 2 ] - """), - Example(""" + """, + """ [ 1, 2 ] - """), - Example(""" + """, + """ [ 1, 2] - """), - Example(""" + """, + """ let x = [ 1, 2 ] - """), - Example(""" + """, + """ [key: 2, key2: 3] - """), - Example(""" + """, + """ [key: 1, key2: 2 ] - """), - Example(""" + """, + """ [ key: 0, key2: 20 ] - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ let x = [ 1, 2 ↓] - """), - Example(""" + """, + """ let x = [ 1, 2 ↓] - """), - Example(""" + """, + """ let x = [ key: value ↓] - """), - Example(""" + """, + """ let x = [ foo( 1, 2)↓] - """), - ], - corrections: [ - Example(""" + """, + ]), + corrections: #examplesDictionary([ + """ let x = [ key: value ↓ ] - """): Example(""" + """: """ let x = [ key: value ] - """), - Example(""" + """, + """ let x = [ 1, 2 ↓] - """): Example(""" + """: """ let x = [ 1, 2 ] - """), - Example(""" + """, + """ let x = [ 1, 2 ↓ ] - """): Example(""" + """: """ let x = [ 1, 2 ] - """), - Example(""" + """, + """ let x = [ 1, 2 @@ -116,7 +116,7 @@ struct LiteralExpressionEndIndentationRule: Rule, OptInRule { 3, 4 ↓ ] - """): Example(""" + """: """ let x = [ 1, 2 @@ -124,20 +124,20 @@ struct LiteralExpressionEndIndentationRule: Rule, OptInRule { 3, 4 ] - """), - Example(""" + """, + """ let x = [ foo( 1, 2)↓] - """): Example(""" + """: """ let x = [ foo( 1, 2) ] - """), - ] + """, + ]) ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ModifierOrderRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ModifierOrderRuleExamples.swift index fc6ee5d416..bd9908976b 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ModifierOrderRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ModifierOrderRuleExamples.swift @@ -1,30 +1,30 @@ internal struct ModifierOrderRuleExamples { - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ public class Foo { public required convenience init() {} } - """), - Example(""" + """, + """ public class Foo { public static let bar = 42 } - """), - Example(""" + """, + """ public class Foo { public static var bar: Int { return } } - """), - Example(""" + """, + """ public class Foo { public class var bar: Int { return 42 } } - """), - Example(""" + """, + """ public class Bar { public class var foo: String { return "foo" @@ -35,8 +35,8 @@ internal struct ModifierOrderRuleExamples { return "bar" } } - """), - Example(""" + """, + """ open class Bar { public var foo: Int? { return 42 @@ -47,8 +47,8 @@ internal struct ModifierOrderRuleExamples { return 43 } } - """), - Example(""" + """, + """ open class Bar { open class func foo() -> Int { return 42 @@ -59,86 +59,86 @@ internal struct ModifierOrderRuleExamples { return 43 } } - """), - Example(""" + """, + """ protocol Foo: class {} class Bar { public private(set) weak var foo: Foo? } - """), - Example(""" + """, + """ @objc public final class Foo: NSObject {} - """), - Example(""" + """, + """ @objcMembers public final class Foo: NSObject {} - """), - Example(""" + """, + """ @objc override public private(set) weak var foo: Bar? - """), - Example(""" + """, + """ @objc public final class Foo: NSObject {} - """), - Example(""" + """, + """ @objc open final class Foo: NSObject { open weak var weakBar: NSString? = nil } - """), - Example(""" + """, + """ public final class Foo {} - """), - Example(""" + """, + """ class Bar { func bar() {} } - """), - Example(""" + """, + """ internal class Foo: Bar { override internal func bar() {} } - """), - Example(""" + """, + """ public struct Foo { internal weak var weakBar: NSObject? = nil } - """), - Example(""" + """, + """ class Foo { internal lazy var bar: String = "foo" } - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ class Foo { convenience required public init() {} } - """), - Example(""" + """, + """ public class Foo { static public let bar = 42 } - """), - Example(""" + """, + """ public class Foo { static public var bar: Int { return 42 } } - """), - Example(""" + """, + """ public class Foo { class public var bar: Int { return 42 } } - """), - Example(""" + """, + """ public class RootFoo { class public var foo: String { return "foo" @@ -149,8 +149,8 @@ internal struct ModifierOrderRuleExamples { return "bar" } } - """), - Example(""" + """, + """ open class Bar { public var foo: Int? { return 42 @@ -161,14 +161,14 @@ internal struct ModifierOrderRuleExamples { return 43 } } - """), - Example(""" + """, + """ protocol Foo: class {} class Bar { private(set) public weak var foo: Foo? } - """), - Example(""" + """, + """ open class Bar { open class func foo() -> Int { return 42 @@ -179,8 +179,8 @@ internal struct ModifierOrderRuleExamples { return 43 } } - """), - Example(""" + """, + """ open class Bar { open class func foo() -> Int { return 42 @@ -191,38 +191,38 @@ internal struct ModifierOrderRuleExamples { return 43 } } - """), - Example(""" + """, + """ @objc final public class Foo: NSObject {} - """), - Example(""" + """, + """ @objcMembers final public class Foo: NSObject {} - """), - Example(""" + """, + """ @objc final open class Foo: NSObject { weak open var weakBar: NSString? = nil } - """), - Example(""" + """, + """ final public class Foo {} - """), - Example(""" + """, + """ internal class Foo: Bar { internal override func bar() {} } - """), - Example(""" + """, + """ public struct Foo { weak internal var weakBar: NSObjetc? = nil } - """), - Example(""" + """, + """ class Foo { lazy internal var bar: String = "foo" } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineArgumentsRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineArgumentsRuleExamples.swift index 20e4124d41..3e2e548417 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineArgumentsRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineArgumentsRuleExamples.swift @@ -1,48 +1,48 @@ internal struct MultilineArgumentsRuleExamples { - static let nonTriggeringExamples = [ - Example("foo()"), - Example(""" + static let nonTriggeringExamples = #examples([ + "foo()", + """ foo( ) - """), - Example("foo { }"), - Example(""" + """, + "foo { }", + """ foo { } - """), - Example("foo(0)"), - Example("foo(0, 1)"), - Example("foo(0, 1) { }"), - Example("foo(0, param1: 1)"), - Example("foo(0, param1: 1) { }"), - Example("foo(param1: 1)"), - Example("foo(param1: 1) { }"), - Example("foo(param1: 1, param2: true) { }"), - Example("foo(param1: 1, param2: true, param3: [3]) { }"), - Example(""" + """, + "foo(0)", + "foo(0, 1)", + "foo(0, 1) { }", + "foo(0, param1: 1)", + "foo(0, param1: 1) { }", + "foo(param1: 1)", + "foo(param1: 1) { }", + "foo(param1: 1, param2: true) { }", + "foo(param1: 1, param2: true, param3: [3]) { }", + """ foo(param1: 1, param2: true, param3: [3]) { bar() } - """), - Example(""" + """, + """ foo(param1: 1, param2: true, param3: [3]) - """), - Example(""" + """, + """ foo( param1: 1, param2: true, param3: [3] ) - """), - Example(""" + """, + """ foo( param1: 1, param2: true, param3: [3] ) - """), - Example(#""" + """, + #""" Picker(selection: viewStore.binding(\.$someProperty)) { ForEach(SomeEnum.allCases, id: \.rawValue) { someCase in Text(someCase.rawValue) @@ -51,8 +51,8 @@ internal struct MultilineArgumentsRuleExamples { } label: { EmptyView() } - """#), - Example(""" + """#, + """ UIView.animate(withDuration: 1, delay: 0) { // sample @@ -61,40 +61,40 @@ internal struct MultilineArgumentsRuleExamples { // sample print("b") } - """), - Example(""" + """, + """ UIView.animate(withDuration: 1, delay: 0) { print("a") } completion: { _ in print("b") } - """), - Example(""" + """, + """ f( foo: 1, bar: false, ) - """), - ] + """, + ]) - static let triggeringExamples = [ - Example(""" + static let triggeringExamples = #examples([ + """ foo(0, param1: 1, ↓param2: true, ↓param3: [3]) - """), - Example(""" + """, + """ foo(0, ↓param1: 1, param2: true, ↓param3: [3]) - """), - Example(""" + """, + """ foo(0, ↓param1: 1, ↓param2: true, param3: [3]) - """), - Example(""" + """, + """ foo( 0, ↓param1: 1, param2: true, ↓param3: [3] ) - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineFunctionChainsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineFunctionChainsRule.swift index c6a9bbd4f3..c998f777dd 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineFunctionChainsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineFunctionChainsRule.swift @@ -10,41 +10,41 @@ struct MultilineFunctionChainsRule: ASTRule, OptInRule { name: "Multiline Function Chains", description: "Chained function calls should be either on the same line, or one per line", kind: .style, - nonTriggeringExamples: [ - Example("let evenSquaresSum = [20, 17, 35, 4].filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)"), - Example(""" + nonTriggeringExamples: #examples([ + "let evenSquaresSum = [20, 17, 35, 4].filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)", + """ let evenSquaresSum = [20, 17, 35, 4] .filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)", - """), - Example(""" + """, + """ let chain = a .b(1, 2, 3) .c { blah in print(blah) } .d() - """), - Example(""" + """, + """ let chain = a.b(1, 2, 3) .c { blah in print(blah) } .d() - """), - Example(""" + """, + """ let chain = a.b(1, 2, 3) .c { blah in print(blah) } .d() - """), - Example(""" + """, + """ let chain = a.b(1, 2, 3) .c(.init( a: 1, b, 2, c, 3)) .d() - """), - Example(""" + """, + """ self.viewModel.outputs.postContextualNotification .observeForUI() .observeValues { @@ -56,41 +56,41 @@ struct MultilineFunctionChainsRule: ASTRule, OptInRule { ) ) } - """), - Example("let remainingIDs = Array(Set(self.currentIDs).subtracting(Set(response.ids)))"), - Example(""" + """, + "let remainingIDs = Array(Set(self.currentIDs).subtracting(Set(response.ids)))", + """ self.happeningNewsletterOn = self.updateCurrentUser .map { $0.newsletters.happening }.skipNil().skipRepeats() - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ let evenSquaresSum = [20, 17, 35, 4] .filter { $0 % 2 == 0 }↓.map { $0 * $0 } .reduce(0, +) - """), - Example(""" + """, + """ let evenSquaresSum = a.b(1, 2, 3) .c { blah in print(blah) }↓.d() - """), - Example(""" + """, + """ let evenSquaresSum = a.b(1, 2, 3) .c(2, 3, 4)↓.d() - """), - Example(""" + """, + """ let evenSquaresSum = a.b(1, 2, 3)↓.c { blah in print(blah) } .d() - """), - Example(""" + """, + """ a.b { // ““ }↓.e() - """), - ] + """, + ]) ) func validate(file: SwiftLintFile, diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineLiteralBracketsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineLiteralBracketsRule.swift index 0e360e122b..32908d1510 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineLiteralBracketsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineLiteralBracketsRule.swift @@ -10,12 +10,12 @@ struct MultilineLiteralBracketsRule: Rule { name: "Multiline Literal Brackets", description: "Multiline literals should have their surrounding brackets in a new line", kind: .style, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ let trio = ["harry", "ronald", "hermione"] let houseCup = ["gryffindor": 460, "hufflepuff": 370, "ravenclaw": 410, "slytherin": 450] - """), - Example(""" + """, + """ let trio = [ "harry", "ronald", @@ -27,8 +27,8 @@ struct MultilineLiteralBracketsRule: Rule { "ravenclaw": 410, "slytherin": 450 ] - """), - Example(""" + """, + """ let trio = [ "harry", "ronald", "hermione" ] @@ -36,8 +36,8 @@ struct MultilineLiteralBracketsRule: Rule { "gryffindor": 460, "hufflepuff": 370, "ravenclaw": 410, "slytherin": 450 ] - """), - Example(""" + """, + """ _ = [ 1, 2, @@ -46,45 +46,45 @@ struct MultilineLiteralBracketsRule: Rule { 5, 6, 7, 8, 9 ] - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ let trio = [↓"harry", "ronald", "hermione" ] - """), - Example(""" + """, + """ let houseCup = [↓"gryffindor": 460, "hufflepuff": 370, "ravenclaw": 410, "slytherin": 450 ] - """), - Example(""" + """, + """ let houseCup = [↓"gryffindor": 460, "hufflepuff": 370, "ravenclaw": 410, "slytherin": 450↓] - """), - Example(""" + """, + """ let trio = [ "harry", "ronald", "hermione"↓] - """), - Example(""" + """, + """ let houseCup = [ "gryffindor": 460, "hufflepuff": 370, "ravenclaw": 410, "slytherin": 450↓] - """), - Example(""" + """, + """ class Hogwarts { let houseCup = [ "gryffindor": 460, "hufflepuff": 370, "ravenclaw": 410, "slytherin": 450↓] } - """), - Example(""" + """, + """ _ = [ 1, 2, @@ -92,14 +92,14 @@ struct MultilineLiteralBracketsRule: Rule { 4, 5, 6, 7, 8, 9↓] - """), - Example(""" + """, + """ _ = [↓1, 2, 3, 4, 5, 6, 7, 8, 9 ] - """), - Example(""" + """, + """ class Hogwarts { let houseCup = [ "gryffindor": 460, "hufflepuff": 370, @@ -107,8 +107,8 @@ struct MultilineLiteralBracketsRule: Rule { $0.isValid }.sum()↓] } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineParametersBracketsRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineParametersBracketsRule.swift index 84a8d388f4..e4d36dd119 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/MultilineParametersBracketsRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/MultilineParametersBracketsRule.swift @@ -10,35 +10,35 @@ struct MultilineParametersBracketsRule: OptInRule { name: "Multiline Parameters Brackets", description: "Multiline parameters should have their surrounding brackets in a new line", kind: .style, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ func foo(param1: String, param2: String, param3: String) - """), - Example(""" + """, + """ func foo( param1: String, param2: String, param3: String ) - """), - Example(""" + """, + """ func foo( param1: String, param2: String, param3: String ) - """), - Example(""" + """, + """ class SomeType { func foo(param1: String, param2: String, param3: String) } - """), - Example(""" + """, + """ class SomeType { func foo( param1: String, param2: String, param3: String ) } - """), - Example(""" + """, + """ class SomeType { func foo( param1: String, @@ -46,49 +46,49 @@ struct MultilineParametersBracketsRule: OptInRule { param3: String ) } - """), - Example(""" + """, + """ func foo(param1: T, param2: String, param3: String) -> T { /* some code */ } - """), - Example(""" + """, + """ func foo(a: [Int] = [ 1 ]) - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ func foo(↓param1: String, param2: String, param3: String ) - """), - Example(""" + """, + """ func foo( param1: String, param2: String, param3: String↓) - """), - Example(""" + """, + """ class SomeType { func foo(↓param1: String, param2: String, param3: String ) } - """), - Example(""" + """, + """ class SomeType { func foo( param1: String, param2: String, param3: String↓) } - """), - Example(""" + """, + """ func foo(↓param1: T, param2: String, param3: String ) -> T - """), - ] + """, + ]) ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/MultipleClosuresWithTrailingClosureRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/MultipleClosuresWithTrailingClosureRule.swift index 288c3fce40..2500f2a95c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/MultipleClosuresWithTrailingClosureRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/MultipleClosuresWithTrailingClosureRule.swift @@ -9,31 +9,31 @@ struct MultipleClosuresWithTrailingClosureRule: Rule { name: "Multiple Closures with Trailing Closure", description: "Trailing closure syntax should not be used when passing more than one closure argument", kind: .style, - nonTriggeringExamples: [ - Example("foo.map { $0 + 1 }"), - Example("foo.reduce(0) { $0 + $1 }"), - Example("if let foo = bar.map({ $0 + 1 }) {\n\n}"), - Example("foo.something(param1: { $0 }, param2: { $0 + 1 })"), - Example(""" + nonTriggeringExamples: #examples([ + "foo.map { $0 + 1 }", + "foo.reduce(0) { $0 + $1 }", + "if let foo = bar.map({ $0 + 1 }) {\n\n}", + "foo.something(param1: { $0 }, param2: { $0 + 1 })", + """ UIView.animate(withDuration: 1.0) { someView.alpha = 0.0 } - """), - Example("foo.method { print(0) } arg2: { print(1) }"), - Example("foo.methodWithParenArgs((0, 1), arg2: (0, 1, 2)) { $0 } arg4: { $0 }"), - ], - triggeringExamples: [ - Example("foo.something(param1: { $0 }) ↓{ $0 + 1 }"), - Example(""" + """, + "foo.method { print(0) } arg2: { print(1) }", + "foo.methodWithParenArgs((0, 1), arg2: (0, 1, 2)) { $0 } arg4: { $0 }", + ]), + triggeringExamples: #examples([ + "foo.something(param1: { $0 }) ↓{ $0 + 1 }", + """ UIView.animate(withDuration: 1.0, animations: { someView.alpha = 0.0 }) ↓{ _ in someView.removeFromSuperview() } - """), - Example("foo.multipleTrailing(arg1: { $0 }) { $0 } arg3: { $0 }"), - Example("foo.methodWithParenArgs(param1: { $0 }, param2: (0, 1), (0, 1)) { $0 }"), - ] + """, + "foo.multipleTrailing(arg1: { $0 }) { $0 } arg3: { $0 }", + "foo.methodWithParenArgs(param1: { $0 }, param2: (0, 1), (0, 1)) { $0 }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/NoSpaceInMethodCallRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/NoSpaceInMethodCallRule.swift index bb572feaa8..6048e9f62c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/NoSpaceInMethodCallRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/NoSpaceInMethodCallRule.swift @@ -9,39 +9,39 @@ struct NoSpaceInMethodCallRule: Rule { name: "No Space in Method Call", description: "Don't add a space between the method name and the parentheses", kind: .style, - nonTriggeringExamples: [ - Example("foo()"), - Example("object.foo()"), - Example("object.foo(1)"), - Example("object.foo(value: 1)"), - Example("object.foo { print($0 }"), - Example("list.sorted { $0.0 < $1.0 }.map { $0.value }"), - Example("self.init(rgb: (Int) (colorInt))"), - Example(""" + nonTriggeringExamples: #examples([ + "foo()", + "object.foo()", + "object.foo(1)", + "object.foo(value: 1)", + "object.foo { print($0 }", + "list.sorted { $0.0 < $1.0 }.map { $0.value }", + "self.init(rgb: (Int) (colorInt))", + """ Button { print("Button tapped") } label: { Text("Button") } - """), - ], - triggeringExamples: [ - Example("foo↓ ()"), - Example("object.foo↓ ()"), - Example("object.foo↓ (1)"), - Example("object.foo↓ (value: 1)"), - Example("object.foo↓ () {}"), - Example("object.foo↓ ()"), - Example("object.foo↓ (value: 1) { x in print(x) }"), - ], - corrections: [ - Example("foo↓ ()"): Example("foo()"), - Example("object.foo↓ ()"): Example("object.foo()"), - Example("object.foo↓ (1)"): Example("object.foo(1)"), - Example("object.foo↓ (value: 1)"): Example("object.foo(value: 1)"), - Example("object.foo↓ () {}"): Example("object.foo() {}"), - Example("object.foo↓ ()"): Example("object.foo()"), - ] + """, + ]), + triggeringExamples: #examples([ + "foo↓ ()", + "object.foo↓ ()", + "object.foo↓ (1)", + "object.foo↓ (value: 1)", + "object.foo↓ () {}", + "object.foo↓ ()", + "object.foo↓ (value: 1) { x in print(x) }", + ]), + corrections: #examplesDictionary([ + "foo↓ ()": "foo()", + "object.foo↓ ()": "object.foo()", + "object.foo↓ (1)": "object.foo(1)", + "object.foo↓ (value: 1)": "object.foo(value: 1)", + "object.foo↓ () {}": "object.foo() {}", + "object.foo↓ ()": "object.foo()", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/NonOverridableClassDeclarationRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/NonOverridableClassDeclarationRule.swift index ec691bf824..9925821569 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/NonOverridableClassDeclarationRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/NonOverridableClassDeclarationRule.swift @@ -12,68 +12,68 @@ struct NonOverridableClassDeclarationRule: Rule { are private. In both cases, they cannot be overridden. Using `final class` or `static` makes this explicit. """, kind: .style, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ final class C { final class var b: Bool { true } final class func f() {} } - """), - Example(""" + """, + """ class C { final class var b: Bool { true } final class func f() {} } - """), - Example(""" + """, + """ class C { class var b: Bool { true } class func f() {} } - """), - Example(""" + """, + """ class C { static var b: Bool { true } static func f() {} } - """), - Example(""" + """, + """ final class C { static var b: Bool { true } static func f() {} } - """), - Example(""" + """, + """ final class C { class D { class var b: Bool { true } class func f() {} } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ final class C { ↓class var b: Bool { true } ↓class func f() {} } - """), - Example(""" + """, + """ class C { final class D { ↓class var b: Bool { true } ↓class func f() {} } } - """), - Example(""" + """, + """ class C { private ↓class var b: Bool { true } private ↓class func f() {} } - """), - ], + """, + ]), corrections: [ Example(""" final class C { diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/OpeningBraceRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/OpeningBraceRuleExamples.swift index d423c231f2..a4f601aa47 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/OpeningBraceRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/OpeningBraceRuleExamples.swift @@ -2,63 +2,63 @@ // swiftlint:disable:next type_body_length struct OpeningBraceRuleExamples { - static let nonTriggeringExamples = [ - Example("func abc() {\n}"), - Example("[].map() { $0 }"), - Example("[].map({ })"), - Example("if let a = b { }"), - Example("while a == b { }"), - Example("guard let a = b else { }"), - Example("struct Rule {}"), - Example("struct Parent {\n\tstruct Child {\n\t\tlet foo: Int\n\t}\n}"), - Example(""" + static let nonTriggeringExamples = #examples([ + "func abc() {\n}", + "[].map() { $0 }", + "[].map({ })", + "if let a = b { }", + "while a == b { }", + "guard let a = b else { }", + "struct Rule {}", + "struct Parent {\n\tstruct Child {\n\t\tlet foo: Int\n\t}\n}", + """ func f(rect: CGRect) { { let centre = CGPoint(x: rect.midX, y: rect.midY) print(centre) }() } - """), - Example(""" + """, + """ func f(rect: CGRect) -> () -> Void { { let centre = CGPoint(x: rect.midX, y: rect.midY) print(centre) } } - """), - Example(""" + """, + """ func f() -> () -> Void { {} } - """), - Example(""" + """, + """ class Rule: NSObject { var a: String { return "" } } - """), - Example(""" + """, + """ self.foo( ( "String parameter", { "Do something here" } ) ) - """), - Example(##"let pattern = #/(\{(?\w+)\})/#"##), - Example(""" + """, + ##"let pattern = #/(\{(?\w+)\})/#"##, + """ if c {} else {} - """), - Example(""" + """, + """ if c /* comment */ { return } - """), - ] + """, + ]) static let triggeringExamples = [ Example("func abc()↓{\n}"), @@ -219,282 +219,282 @@ struct OpeningBraceRuleExamples { """), ] - static let corrections = [ - Example("struct Rule{}"): Example("struct Rule {}"), - Example("struct Rule\n{\n}"): Example("struct Rule {\n}"), - Example("struct Rule\n\n\t{\n}"): Example("struct Rule {\n}"), - Example("struct Parent {\n\tstruct Child\n\t{\n\t\tlet foo: Int\n\t}\n}"): - Example("struct Parent {\n\tstruct Child {\n\t\tlet foo: Int\n\t}\n}"), - Example("[].map(){ $0 }"): Example("[].map() { $0 }"), - Example("if a == b{ }"): Example("if a == b { }"), - Example("if\n\tlet a = b,\n\tlet c = d{ }"): Example("if\n\tlet a = b,\n\tlet c = d { }"), - Example(""" + static let corrections = #examplesDictionary([ + "struct Rule{}": "struct Rule {}", + "struct Rule\n{\n}": "struct Rule {\n}", + "struct Rule\n\n\t{\n}": "struct Rule {\n}", + "struct Parent {\n\tstruct Child\n\t{\n\t\tlet foo: Int\n\t}\n}": + "struct Parent {\n\tstruct Child {\n\t\tlet foo: Int\n\t}\n}", + "[].map(){ $0 }": "[].map() { $0 }", + "if a == b{ }": "if a == b { }", + "if\n\tlet a = b,\n\tlet c = d{ }": "if\n\tlet a = b,\n\tlet c = d { }", + """ actor MyActor { } - """): Example(""" + """: """ actor MyActor { } - """), - Example(""" + """, + """ actor MyActor { } - """): Example(""" + """: """ actor MyActor { } - """), - Example(""" + """, + """ actor MyActor { } - """): Example(""" + """: """ actor MyActor { } - """), - Example(""" + """, + """ actor MyActor where T: U { } - """): Example(""" + """: """ actor MyActor where T: U { } - """), - Example(""" + """, + """ class Rule { } - """): Example(""" + """: """ class Rule { } - """), - Example(""" + """, + """ class Rule { } - """): Example(""" + """: """ class Rule { } - """), - Example(""" + """, + """ class Rule { } - """): Example(""" + """: """ class Rule { } - """), - Example(""" + """, + """ class Rule: NSObject { } - """): Example(""" + """: """ class Rule: NSObject { } - """), - Example(""" + """, + """ class Rule: NSObject where T: U { } - """): Example(""" + """: """ class Rule: NSObject where T: U { } - """), - Example(""" + """, + """ enum Rule { } - """): Example(""" + """: """ enum Rule { } - """), - Example(""" + """, + """ enum Rule: E { } - """): Example(""" + """: """ enum Rule: E { } - """), - Example(""" + """, + """ extension Rule { } - """): Example(""" + """: """ extension Rule { } - """), - Example(""" + """, + """ protocol Rule { } - """): Example(""" + """: """ protocol Rule { } - """), - Example(""" + """, + """ struct Rule { } - """): Example(""" + """: """ struct Rule { } - """), - Example(""" + """, + """ struct Rule : A { } - """): Example(""" + """: """ struct Rule : A { } - """), - Example(""" + """, + """ do { } catch { } - """): Example(""" + """: """ do { } catch { } - """), - Example(""" + """, + """ do { } catch MyError.unknown { } - """): Example(""" + """: """ do { } catch MyError.unknown { } - """), - Example(""" + """, + """ do { } catch let error { } - """): Example(""" + """: """ do { } catch let error { } - """), - Example(""" + """, + """ defer { } - """): Example(""" + """: """ defer { } - """), - Example(""" + """, + """ do { } - """): Example(""" + """: """ do { } - """), - Example(""" + """, + """ for a in b { } - """): Example(""" + """: """ for a in b { } - """), - Example(""" + """, + """ for a in b where a == c { } - """): Example(""" + """: """ for a in b where a == c { } - """), - Example(""" + """, + """ guard a == b else { return "" } - """): Example(""" + """: """ guard a == b else { return "" } - """), - Example("if\n\tlet a = b,\n\tlet c = d{ }\n"): Example("if\n\tlet a = b,\n\tlet c = d { }\n"), - Example(""" + """, + "if\n\tlet a = b,\n\tlet c = d{ }\n": "if\n\tlet a = b,\n\tlet c = d { }\n", + """ if varDecl.parent?.is(CodeBlockItemSyntax.self) == true // Local variable declaration || varDecl.bindings.onlyElement?.accessor != nil // Computed property || !node.type.is(SimpleTypeIdentifierSyntax.self) { // Complex or collection type return .visitChildren } - """): Example(""" + """: """ if varDecl.parent?.is(CodeBlockItemSyntax.self) == true // Local variable declaration || varDecl.bindings.onlyElement?.accessor != nil // Computed property || !node.type.is(SimpleTypeIdentifierSyntax.self) { // Complex or collection type return .visitChildren } - """), - Example(""" + """, + """ repeat { } while a - """): Example(""" + """: """ repeat { } while a - """), - Example(""" + """, + """ while a { } - """): Example(""" + """: """ while a { } - """), - Example("class Rule{}"): Example("class Rule {}"), - Example("actor Rule{}"): Example("actor Rule {}"), - Example("enum Rule{}"): Example("enum Rule {}"), - Example("protocol Rule{}"): Example("protocol Rule {}"), - Example("extension Rule{}"): Example("extension Rule {}"), - Example(""" + """, + "class Rule{}": "class Rule {}", + "actor Rule{}": "actor Rule {}", + "enum Rule{}": "enum Rule {}", + "protocol Rule{}": "protocol Rule {}", + "extension Rule{}": "extension Rule {}", + """ class Rule { var a: String { willSet{ @@ -502,7 +502,7 @@ struct OpeningBraceRuleExamples { } } } - """): Example(""" + """: """ class Rule { var a: String { willSet { @@ -510,8 +510,8 @@ struct OpeningBraceRuleExamples { } } } - """), - Example(""" + """, + """ class Rule { var a: String { didSet { @@ -519,7 +519,7 @@ struct OpeningBraceRuleExamples { } } } - """): Example(""" + """: """ class Rule { var a: String { didSet { @@ -527,49 +527,49 @@ struct OpeningBraceRuleExamples { } } } - """), - Example(""" + """, + """ precedencegroup Group{ assignment: true } - """): Example(""" + """: """ precedencegroup Group { assignment: true } - """), - Example(""" + """, + """ if c /* comment */ { return } - """): Example(""" + """: """ if c /* comment */ { return } - """), + """, // https://github.com/realm/SwiftLint/issues/5598 - Example(""" + """ if c // A comment { return } - """): Example(""" + """: """ if c { // A comment return } - """), + """, // https://github.com/realm/SwiftLint/issues/5751 - Example(""" + """ if c // A comment { // Another comment return } - """): Example(""" + """: """ if c { // A comment // Another comment return } - """), + """, // https://github.com/realm/SwiftLint/issues/5751 - Example(""" + """ func foo() { if q1, q2 { @@ -579,7 +579,7 @@ struct OpeningBraceRuleExamples { do2() } } - """): Example(""" + """: """ func foo() { if q1, q2 { do1() @@ -587,21 +587,21 @@ struct OpeningBraceRuleExamples { do2() } } - """), - Example(""" + """, + """ if "test".isEmpty // swiftlint:disable:next opening_brace { // code here } - """): Example(""" + """: """ if "test".isEmpty // swiftlint:disable:next opening_brace { // code here } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/OperatorUsageWhitespaceRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/OperatorUsageWhitespaceRuleExamples.swift index e6fd2e39f0..e1e854919e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/OperatorUsageWhitespaceRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/OperatorUsageWhitespaceRuleExamples.swift @@ -93,71 +93,71 @@ internal enum OperatorUsageWhitespaceRuleExamples { ), ] - static let triggeringExamples = [ - Example("let foo = 1↓+2"), - Example("let foo = 1↓ + 2"), - Example("let foo = 1↓ + 2"), - Example("let foo = 1↓ + 2"), - Example("let foo↓=1↓+2"), - Example("let foo↓=1 + 2"), - Example("let foo↓=bar"), - Example("let range = 1↓ ..< 3"), - Example("let foo = bar↓ ?? 0"), - Example("let foo = bar↓ != 0"), - Example("let foo = bar↓ !== bar2"), - Example("let v8 = Int8(1)↓ << 6"), - Example("let v8 = 1↓ << (6)"), - Example("let v8 = 1↓ << (6)\n let foo = 1 > 2"), - Example("let foo↓ = [1]"), - Example("let foo↓ = \"1\""), - Example("let foo↓ = \"1\""), - Example(""" + static let triggeringExamples = #examples([ + "let foo = 1↓+2", + "let foo = 1↓ + 2", + "let foo = 1↓ + 2", + "let foo = 1↓ + 2", + "let foo↓=1↓+2", + "let foo↓=1 + 2", + "let foo↓=bar", + "let range = 1↓ ..< 3", + "let foo = bar↓ ?? 0", + "let foo = bar↓ != 0", + "let foo = bar↓ !== bar2", + "let v8 = Int8(1)↓ << 6", + "let v8 = 1↓ << (6)", + "let v8 = 1↓ << (6)\n let foo = 1 > 2", + "let foo↓ = [1]", + "let foo↓ = \"1\"", + "let foo↓ = \"1\"", + """ enum Enum { case one↓ = 1 case two = 1 } - """), - Example(""" + """, + """ enum Enum { case one = 1 case two↓ = 1 } - """), - Example(""" + """, + """ enum Enum { case one↓ = 1 case two↓ = 1 } - """), - Example("typealias Foo↓ = Bar"), - Example(""" + """, + "typealias Foo↓ = Bar", + """ protocol A { associatedtype B↓ = C } - """), - Example("tabbedViewController.title↓ = nil"), - Example("let foo = bar ? 0↓:1"), - Example("let foo = bar↓ ? 0 : 1"), - ] + """, + "tabbedViewController.title↓ = nil", + "let foo = bar ? 0↓:1", + "let foo = bar↓ ? 0 : 1", + ]) - static let corrections = [ - Example("let foo = 1↓+2"): Example("let foo = 1 + 2"), - Example("let foo = 1↓ + 2"): Example("let foo = 1 + 2"), - Example("let foo = 1↓ + 2"): Example("let foo = 1 + 2"), - Example("let foo = 1↓ + 2"): Example("let foo = 1 + 2"), - Example("let foo↓=1↓+2"): Example("let foo = 1 + 2"), - Example("let foo↓=1 + 2"): Example("let foo = 1 + 2"), - Example("let foo↓=bar"): Example("let foo = bar"), - Example("let range = 1↓ ..< 3"): Example("let range = 1..<3"), - Example("let foo = bar↓ ?? 0"): Example("let foo = bar ?? 0"), - Example("let foo = bar↓ != 0"): Example("let foo = bar != 0"), - Example("let foo = bar↓ !== bar2"): Example("let foo = bar !== bar2"), - Example("let v8 = Int8(1)↓ << 6"): Example("let v8 = Int8(1) << 6"), - Example("let v8 = 1↓ << (6)"): Example("let v8 = 1 << (6)"), - Example("let v8 = 1↓ << (6)\n let foo = 1 > 2"): Example("let v8 = 1 << (6)\n let foo = 1 > 2"), - Example("let foo↓ = \"1\""): Example("let foo = \"1\""), - Example("let foo↓ = \"1\""): Example("let foo = \"1\""), - Example("let foo = bar ? 0↓:1"): Example("let foo = bar ? 0 : 1"), - Example("let foo = bar↓ ? 0 : 1"): Example("let foo = bar ? 0 : 1"), - ] + static let corrections = #examplesDictionary([ + "let foo = 1↓+2": "let foo = 1 + 2", + "let foo = 1↓ + 2": "let foo = 1 + 2", + "let foo = 1↓ + 2": "let foo = 1 + 2", + "let foo = 1↓ + 2": "let foo = 1 + 2", + "let foo↓=1↓+2": "let foo = 1 + 2", + "let foo↓=1 + 2": "let foo = 1 + 2", + "let foo↓=bar": "let foo = bar", + "let range = 1↓ ..< 3": "let range = 1..<3", + "let foo = bar↓ ?? 0": "let foo = bar ?? 0", + "let foo = bar↓ != 0": "let foo = bar != 0", + "let foo = bar↓ !== bar2": "let foo = bar !== bar2", + "let v8 = Int8(1)↓ << 6": "let v8 = Int8(1) << 6", + "let v8 = 1↓ << (6)": "let v8 = 1 << (6)", + "let v8 = 1↓ << (6)\n let foo = 1 > 2": "let v8 = 1 << (6)\n let foo = 1 > 2", + "let foo↓ = \"1\"": "let foo = \"1\"", + "let foo↓ = \"1\"": "let foo = \"1\"", + "let foo = bar ? 0↓:1": "let foo = bar ? 0 : 1", + "let foo = bar↓ ? 0 : 1": "let foo = bar ? 0 : 1", + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/OptionalEnumCaseMatchingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/OptionalEnumCaseMatchingRule.swift index b41f1bf061..5b9db072ae 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/OptionalEnumCaseMatchingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/OptionalEnumCaseMatchingRule.swift @@ -48,125 +48,125 @@ struct OptionalEnumCaseMatchingRule: Rule { } """, excludeFromDocumentation: true), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ switch foo { case .bar↓?: break case .baz: break default: break } - """), - Example(""" + """, + """ switch foo { case Foo.bar↓?: break case .baz: break default: break } - """), - Example(""" + """, + """ switch foo { case .bar↓?, .baz↓?: break default: break } - """), - Example(""" + """, + """ switch foo { case .bar↓? where x > 1: break case .baz: break default: break } - """), - Example(""" + """, + """ switch foo { case (.bar↓?, .baz↓?): break case (.bar↓?, _): break case (_, .bar↓?): break default: break } - """), - ], - corrections: [ - Example(""" + """, + ]), + corrections: #examplesDictionary([ + """ switch foo { case .bar↓?: break case .baz: break default: break } - """): Example(""" + """: """ switch foo { case .bar: break case .baz: break default: break } - """), - Example(""" + """, + """ switch foo { case Foo.bar↓?: break case .baz: break default: break } - """): Example(""" + """: """ switch foo { case Foo.bar: break case .baz: break default: break } - """), - Example(""" + """, + """ switch foo { case .bar↓?, .baz↓?: break default: break } - """): Example(""" + """: """ switch foo { case .bar, .baz: break default: break } - """), - Example(""" + """, + """ switch foo { case .bar↓? where x > 1: break case .baz: break default: break } - """): Example(""" + """: """ switch foo { case .bar where x > 1: break case .baz: break default: break } - """), - Example(""" + """, + """ switch foo { case (.bar↓?, .baz↓?): break case (.bar↓?, _): break case (_, .bar↓?): break default: break } - """): Example(""" + """: """ switch foo { case (.bar, .baz): break case (.bar, _): break case (_, .bar): break default: break } - """), - Example(""" + """, + """ switch foo { case (true?, false?): break case (true?, _): break case (_, false?): break default: break } - """): Example(""" + """: """ switch foo { case (true?, false?): break case (true?, _): break case (_, false?): break default: break } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfInStaticReferencesRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfInStaticReferencesRuleExamples.swift index d94d49db52..8f1e7b5540 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfInStaticReferencesRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfInStaticReferencesRuleExamples.swift @@ -370,8 +370,8 @@ enum PreferSelfInStaticReferencesRuleExamples { """, excludeFromDocumentation: true), ] - static let corrections = [ - Example(""" + static let corrections = #examplesDictionary([ + """ final class CheckCellView: NSTableCellView { @IBOutlet var checkButton: NSButton! @@ -381,8 +381,8 @@ enum PreferSelfInStaticReferencesRuleExamples { @objc func check(_ button: AnyObject?) {} } - """): - Example(""" + """: + """ final class CheckCellView: NSTableCellView { @IBOutlet var checkButton: NSButton! @@ -392,8 +392,8 @@ enum PreferSelfInStaticReferencesRuleExamples { @objc func check(_ button: AnyObject?) {} } - """), - Example(""" + """, + """ struct S { static let i = 1 static let j = ↓S.i @@ -401,7 +401,7 @@ enum PreferSelfInStaticReferencesRuleExamples { static func f(_ l: Int = ↓S.i) -> Int { l*↓S.j } func g() { ↓S.i + ↓S.f() + k } } - """): Example(""" + """: """ struct S { static let i = 1 static let j = Self.i @@ -409,23 +409,23 @@ enum PreferSelfInStaticReferencesRuleExamples { static func f(_ l: Int = Self.i) -> Int { l*Self.j } func g() { Self.i + Self.f() + k } } - """), - Example(""" + """, + """ class C { static let i = 0 } extension C { func f() -> Int { ↓C.i } } - """): Example(""" + """: """ class C { static let i = 0 } extension C { func f() -> Int { Self.i } } - """), - Example(""" + """, + """ class Outer { class Inner { static let i = 0 @@ -434,7 +434,7 @@ enum PreferSelfInStaticReferencesRuleExamples { extension Outer.Inner { func f() -> Int { ↓Outer.Inner.i } } - """): Example(""" + """: """ class Outer { class Inner { static let i = 0 @@ -443,6 +443,6 @@ enum PreferSelfInStaticReferencesRuleExamples { extension Outer.Inner { func f() -> Int { Self.i } } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfTypeOverTypeOfSelfRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfTypeOverTypeOfSelfRule.swift index 312cefda1f..828f17cc06 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfTypeOverTypeOfSelfRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfTypeOverTypeOfSelfRule.swift @@ -11,100 +11,100 @@ struct PreferSelfTypeOverTypeOfSelfRule: Rule { description: "Prefer `Self` over `type(of: self)` when accessing properties or calling methods", kind: .style, minSwiftVersion: .fiveDotOne, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ class Foo { func bar() { Self.baz() } } - """), - Example(""" + """, + """ class Foo { func bar() { print(Self.baz) } } - """), - Example(""" + """, + """ class A { func foo(param: B) { type(of: param).bar() } } - """), - Example(""" + """, + """ class A { func foo() { print(type(of: self)) } } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ class Foo { func bar() { ↓type(of: self).baz() } } - """), - Example(""" + """, + """ class Foo { func bar() { print(↓type(of: self).baz) } } - """), - Example(""" + """, + """ class Foo { func bar() { print(↓Swift.type(of: self).baz) } } - """), - ], - corrections: [ - Example(""" + """, + ]), + corrections: #examplesDictionary([ + """ class Foo { func bar() { ↓type(of: self).baz() } } - """): Example(""" + """: """ class Foo { func bar() { Self.baz() } } - """), - Example(""" + """, + """ class Foo { func bar() { print(↓type(of: self).baz) } } - """): Example(""" + """: """ class Foo { func bar() { print(Self.baz) } } - """), - Example(""" + """, + """ class Foo { func bar() { print(↓Swift.type(of: self).baz) } } - """): Example(""" + """: """ class Foo { func bar() { print(Self.baz) } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/PrefixedTopLevelConstantRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/PrefixedTopLevelConstantRule.swift index 79de73d867..3172ef902c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/PrefixedTopLevelConstantRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/PrefixedTopLevelConstantRule.swift @@ -62,22 +62,22 @@ struct PrefixedTopLevelConstantRule: Rule { } """#), ], - triggeringExamples: [ - Example("private let ↓Foo = 20.0"), - Example("public let ↓Foo = false"), - Example("internal let ↓Foo = \"Foo\""), - Example("let ↓Foo = true"), - Example("let ↓foo = 2, ↓bar = true"), - Example(""" + triggeringExamples: #examples([ + "private let ↓Foo = 20.0", + "public let ↓Foo = false", + "internal let ↓Foo = \"Foo\"", + "let ↓Foo = true", + "let ↓foo = 2, ↓bar = true", + """ let ↓foo = true - """), - Example(""" + """, + """ let ↓foo = { return a + b }() - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ProtocolPropertyAccessorsOrderRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ProtocolPropertyAccessorsOrderRule.swift index 4bf198c8b5..ded1b86db7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ProtocolPropertyAccessorsOrderRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ProtocolPropertyAccessorsOrderRule.swift @@ -9,18 +9,18 @@ struct ProtocolPropertyAccessorsOrderRule: Rule { name: "Protocol Property Accessors Order", description: "When declaring properties in protocols, the order of accessors should be `get set`", kind: .style, - nonTriggeringExamples: [ - Example("protocol Foo {\n var bar: String { get set }\n }"), - Example("protocol Foo {\n var bar: String { get }\n }"), - Example("protocol Foo {\n var bar: String { set }\n }"), - ], - triggeringExamples: [ - Example("protocol Foo {\n var bar: String { ↓set get }\n }") - ], - corrections: [ - Example("protocol Foo {\n var bar: String { ↓set get }\n }"): - Example("protocol Foo {\n var bar: String { get set }\n }"), - ] + nonTriggeringExamples: #examples([ + "protocol Foo {\n var bar: String { get set }\n }", + "protocol Foo {\n var bar: String { get }\n }", + "protocol Foo {\n var bar: String { set }\n }", + ]), + triggeringExamples: #examples([ + "protocol Foo {\n var bar: String { ↓set get }\n }" + ]), + corrections: #examplesDictionary([ + "protocol Foo {\n var bar: String { ↓set get }\n }": + "protocol Foo {\n var bar: String { get set }\n }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ReturnArrowWhitespaceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ReturnArrowWhitespaceRule.swift index a18a97973f..79a1bb79b3 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ReturnArrowWhitespaceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ReturnArrowWhitespaceRule.swift @@ -10,47 +10,47 @@ struct ReturnArrowWhitespaceRule: Rule { description: "Return arrow and return type should be separated by a single space or on a " + "separate line", kind: .style, - nonTriggeringExamples: [ - Example("func abc() -> Int {}"), - Example("func abc() -> [Int] {}"), - Example("func abc() -> (Int, Int) {}"), - Example("var abc = {(param: Int) -> Void in }"), - Example("func abc() ->\n Int {}"), - Example("func abc()\n -> Int {}"), - Example(""" + nonTriggeringExamples: #examples([ + "func abc() -> Int {}", + "func abc() -> [Int] {}", + "func abc() -> (Int, Int) {}", + "var abc = {(param: Int) -> Void in }", + "func abc() ->\n Int {}", + "func abc()\n -> Int {}", + """ func reallyLongFunctionMethods(withParam1: Int, param2: String, param3: Bool) where T: AGenericConstraint -> Int { return 1 } - """), - Example("typealias SuccessBlock = ((Data) -> Void)"), - ], - triggeringExamples: [ - Example("func abc()↓->Int {}"), - Example("func abc()↓->[Int] {}"), - Example("func abc()↓->(Int, Int) {}"), - Example("func abc()↓-> Int {}"), - Example("func abc()↓-> Int {}"), - Example("func abc()↓ ->Int {}"), - Example("func abc()↓ -> Int {}"), - Example("var abc = {(param: Int)↓ ->Bool in }"), - Example("var abc = {(param: Int)↓->Bool in }"), - Example("typealias SuccessBlock = ((Data)↓->Void)"), - Example("func abc()\n ↓-> Int {}"), - Example("func abc()\n ↓-> Int {}"), - Example("func abc()↓ ->\n Int {}"), - Example("func abc()↓ ->\nInt {}"), - ], - corrections: [ - Example("func abc()↓->Int {}"): Example("func abc() -> Int {}"), - Example("func abc()↓-> Int {}"): Example("func abc() -> Int {}"), - Example("func abc()↓ ->Int {}"): Example("func abc() -> Int {}"), - Example("func abc()↓ -> Int {}"): Example("func abc() -> Int {}"), - Example("func abc()\n ↓-> Int {}"): Example("func abc()\n -> Int {}"), - Example("func abc()\n ↓-> Int {}"): Example("func abc()\n -> Int {}"), - Example("func abc()↓ ->\n Int {}"): Example("func abc() ->\n Int {}"), - Example("func abc()↓ ->\nInt {}"): Example("func abc() ->\nInt {}"), - ] + """, + "typealias SuccessBlock = ((Data) -> Void)", + ]), + triggeringExamples: #examples([ + "func abc()↓->Int {}", + "func abc()↓->[Int] {}", + "func abc()↓->(Int, Int) {}", + "func abc()↓-> Int {}", + "func abc()↓-> Int {}", + "func abc()↓ ->Int {}", + "func abc()↓ -> Int {}", + "var abc = {(param: Int)↓ ->Bool in }", + "var abc = {(param: Int)↓->Bool in }", + "typealias SuccessBlock = ((Data)↓->Void)", + "func abc()\n ↓-> Int {}", + "func abc()\n ↓-> Int {}", + "func abc()↓ ->\n Int {}", + "func abc()↓ ->\nInt {}", + ]), + corrections: #examplesDictionary([ + "func abc()↓->Int {}": "func abc() -> Int {}", + "func abc()↓-> Int {}": "func abc() -> Int {}", + "func abc()↓ ->Int {}": "func abc() -> Int {}", + "func abc()↓ -> Int {}": "func abc() -> Int {}", + "func abc()\n ↓-> Int {}": "func abc()\n -> Int {}", + "func abc()\n ↓-> Int {}": "func abc()\n -> Int {}", + "func abc()↓ ->\n Int {}": "func abc() ->\n Int {}", + "func abc()↓ ->\nInt {}": "func abc() ->\nInt {}", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/ShorthandOperatorRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/ShorthandOperatorRule.swift index 7912bf25a5..40ccb0102c 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/ShorthandOperatorRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/ShorthandOperatorRule.swift @@ -9,33 +9,33 @@ struct ShorthandOperatorRule: Rule { name: "Shorthand Operator", description: "Prefer shorthand operators (+=, -=, *=, /=) over doing the operation and assigning", kind: .style, - nonTriggeringExamples: [ - Example("foo -= 1"), - Example("foo += variable"), - Example("foo *= bar.method()"), - Example("self.foo = foo / 1"), - Example("foo = self.foo + 1"), - Example("page = ceilf(currentOffset * pageWidth)"), - Example("foo = aMethod(foo / bar)"), - Example("foo = aMethod(bar + foo)"), - Example(""" + nonTriggeringExamples: #examples([ + "foo -= 1", + "foo += variable", + "foo *= bar.method()", + "self.foo = foo / 1", + "foo = self.foo + 1", + "page = ceilf(currentOffset * pageWidth)", + "foo = aMethod(foo / bar)", + "foo = aMethod(bar + foo)", + """ public func -= (lhs: inout Foo, rhs: Int) { lhs = lhs - rhs } - """), - Example("var helloWorld = \"world!\"\n helloWorld = \"Hello, \" + helloWorld"), - Example("angle = someCheck ? angle : -angle"), - Example("seconds = seconds * 60 + value"), - ], - triggeringExamples: [ - Example("↓foo = foo * 1"), - Example("↓foo = foo / aVariable"), - Example("↓foo = foo - bar.method()"), - Example("↓foo.aProperty = foo.aProperty - 1"), - Example("↓self.aProperty = self.aProperty * 1"), - Example("↓n = n + i / outputLength"), - Example("↓n = n - i / outputLength"), - ] + """, + "var helloWorld = \"world!\"\n helloWorld = \"Hello, \" + helloWorld", + "angle = someCheck ? angle : -angle", + "seconds = seconds * 60 + value", + ]), + triggeringExamples: #examples([ + "↓foo = foo * 1", + "↓foo = foo / aVariable", + "↓foo = foo - bar.method()", + "↓foo.aProperty = foo.aProperty - 1", + "↓self.aProperty = self.aProperty * 1", + "↓n = n + i / outputLength", + "↓n = n - i / outputLength", + ]) ) fileprivate static let allOperators = ["-", "/", "+", "*"] diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/SingleTestClassRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/SingleTestClassRule.swift index 59b234a4ea..56049bd657 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/SingleTestClassRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/SingleTestClassRule.swift @@ -8,45 +8,45 @@ struct SingleTestClassRule: SourceKitFreeRule, OptInRule { name: "Single Test Class", description: "Test files should contain a single QuickSpec or XCTestCase class.", kind: .style, - nonTriggeringExamples: [ - Example("class FooTests { }"), - Example("class FooTests: QuickSpec { }"), - Example("class FooTests: XCTestCase { }"), - ], - triggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + "class FooTests { }", + "class FooTests: QuickSpec { }", + "class FooTests: XCTestCase { }", + ]), + triggeringExamples: #examples([ + """ ↓class FooTests: QuickSpec { } ↓class BarTests: QuickSpec { } - """), - Example(""" + """, + """ ↓class FooTests: QuickSpec { } ↓class BarTests: QuickSpec { } ↓class TotoTests: QuickSpec { } - """), - Example(""" + """, + """ ↓class FooTests: XCTestCase { } ↓class BarTests: XCTestCase { } - """), - Example(""" + """, + """ ↓class FooTests: XCTestCase { } ↓class BarTests: XCTestCase { } ↓class TotoTests: XCTestCase { } - """), - Example(""" + """, + """ ↓class FooTests: QuickSpec { } ↓class BarTests: XCTestCase { } - """), - Example(""" + """, + """ ↓class FooTests: QuickSpec { } ↓class BarTests: XCTestCase { } class TotoTests { } - """), - Example(""" + """, + """ final ↓class FooTests: QuickSpec { } ↓class BarTests: XCTestCase { } class TotoTests { } - """), - ] + """, + ]) ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/SortedEnumCasesRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/SortedEnumCasesRule.swift index 024552741b..4ced05e8b7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/SortedEnumCasesRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/SortedEnumCasesRule.swift @@ -10,103 +10,103 @@ struct SortedEnumCasesRule: Rule { name: "Sorted Enum Cases", description: "Enum cases should be sorted", kind: .style, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ enum foo { case a case b case c } - """), - Example(""" + """, + """ enum foo { case example case exBoyfriend } - """), - Example(""" + """, + """ enum foo { case a case B case c } - """), - Example(""" + """, + """ enum foo { case a, b, c } - """), - Example(""" + """, + """ enum foo { case a case b, c } - """), - Example(""" + """, + """ enum foo { case a(foo: Foo) case b(String), c } - """), - Example(""" + """, + """ enum foo { case a case b, C, d } - """), - Example(""" + """, + """ @frozen enum foo { case b case a case c, f, d } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ enum foo { ↓case b ↓case a case c } - """), - Example(""" + """, + """ enum foo { ↓case B ↓case a case c } - """), - Example(""" + """, + """ enum foo { case ↓b, ↓a, c } - """), - Example(""" + """, + """ enum foo { case ↓B, ↓a, c } - """), - Example(""" + """, + """ enum foo { ↓case b, c ↓case a } - """), - Example(""" + """, + """ enum foo { case a case b, ↓d, ↓c } - """), - Example(""" + """, + """ enum foo { case a(foo: Foo) case ↓c, ↓b(String) } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/StatementPositionRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/StatementPositionRule.swift index 4e438b1183..0141c6ef37 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/StatementPositionRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/StatementPositionRule.swift @@ -10,28 +10,28 @@ struct StatementPositionRule: CorrectableRule { name: "Statement Position", description: "Else and catch should be on the same line, one space after the previous declaration", kind: .style, - nonTriggeringExamples: [ - Example("} else if {"), - Example("} else {"), - Example("} catch {"), - Example("guard foo() else { return }"), - Example("\"}else{\""), - Example("struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)"), - Example("struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)"), - ], - triggeringExamples: [ - Example("↓}else if {"), - Example("↓} else {"), - Example("↓}\ncatch {"), - Example("↓}\n\t catch {"), - Example("guard foo()↓else { return }"), - ], - corrections: [ - Example("↓}\n else {"): Example("} else {"), - Example("↓}\n else if {"): Example("} else if {"), - Example("↓}\n catch {"): Example("} catch {"), - Example("guard foo()↓else { return }"): Example("guard foo() else { return }"), - ] + nonTriggeringExamples: #examples([ + "} else if {", + "} else {", + "} catch {", + "guard foo() else { return }", + "\"}else{\"", + "struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)", + "struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)", + ]), + triggeringExamples: #examples([ + "↓}else if {", + "↓} else {", + "↓}\ncatch {", + "↓}\n\t catch {", + "guard foo()↓else { return }", + ]), + corrections: #examplesDictionary([ + "↓}\n else {": "} else {", + "↓}\n else if {": "} else if {", + "↓}\n catch {": "} catch {", + "guard foo()↓else { return }": "guard foo() else { return }", + ]) ) static let uncuddledDescription = RuleDescription( @@ -40,28 +40,28 @@ struct StatementPositionRule: CorrectableRule { description: "Else and catch should be on the next line, with equal indentation to the " + "previous declaration", kind: .style, - nonTriggeringExamples: [ - Example(" }\n else if {"), - Example(" }\n else {"), - Example(" }\n catch {"), - Example(" }\n\n catch {"), - Example("\n\n }\n catch {"), - Example("\"}\nelse{\""), - Example("struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)"), - Example("struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)"), - ], - triggeringExamples: [ - Example("↓ }else if {"), - Example("↓}\n else {"), - Example("↓ }\ncatch {"), - Example("↓}\n\t catch {"), - ], - corrections: [ - Example(" }else if {"): Example(" }\n else if {"), - Example("}\n else {"): Example("}\nelse {"), - Example(" }\ncatch {"): Example(" }\n catch {"), - Example("}\n\t catch {"): Example("}\ncatch {"), - ] + nonTriggeringExamples: #examples([ + " }\n else if {", + " }\n else {", + " }\n catch {", + " }\n\n catch {", + "\n\n }\n catch {", + "\"}\nelse{\"", + "struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)", + "struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)", + ]), + triggeringExamples: #examples([ + "↓ }else if {", + "↓}\n else {", + "↓ }\ncatch {", + "↓}\n\t catch {", + ]), + corrections: #examplesDictionary([ + " }else if {": " }\n else if {", + "}\n else {": "}\nelse {", + " }\ncatch {": " }\n catch {", + "}\n\t catch {": "}\ncatch {", + ]) ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/SuperfluousElseRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/SuperfluousElseRule.swift index cc63b2bf5e..6e8a9f66d6 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/SuperfluousElseRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/SuperfluousElseRule.swift @@ -78,16 +78,16 @@ struct SuperfluousElseRule: Rule { } """), ], - triggeringExamples: [ - Example(""" + triggeringExamples: #examples([ + """ if i > 0 { return 1 // comment } ↓else { return 2 } - """), - Example(""" + """, + """ if i > 0 { return 1 } ↓else if i < 12 { @@ -95,8 +95,8 @@ struct SuperfluousElseRule: Rule { } ↓else if i > 18 { return 3 } - """), - Example(""" + """, + """ if i > 0 { if i < 12 { return 5 @@ -114,8 +114,8 @@ struct SuperfluousElseRule: Rule { } ↓else { return 3 } - """), - Example(""" + """, + """ for i in list { if i > 13 { return @@ -127,10 +127,10 @@ struct SuperfluousElseRule: Rule { throw error } } - """), - ], - corrections: [ - Example(""" + """, + ]), + corrections: #examplesDictionary([ + """ func f() -> Int { if i > 0 { return 1 @@ -141,7 +141,7 @@ struct SuperfluousElseRule: Rule { // yet another comment } } - """): Example(""" + """: """ func f() -> Int { if i > 0 { return 1 @@ -151,8 +151,8 @@ struct SuperfluousElseRule: Rule { return 2 // yet another comment } - """), - Example(""" + """, + """ func f() -> Int { if i > 0 { return 1 @@ -163,7 +163,7 @@ struct SuperfluousElseRule: Rule { return 3 } } - """): Example(""" + """: """ func f() -> Int { if i > 0 { return 1 @@ -174,8 +174,8 @@ struct SuperfluousElseRule: Rule { } return 3 } - """), - Example(""" + """, + """ func f() -> Int { if i > 0 { @@ -186,7 +186,7 @@ struct SuperfluousElseRule: Rule { return 2 } } - """): Example(""" + """: """ func f() -> Int { if i > 0 { @@ -198,8 +198,8 @@ struct SuperfluousElseRule: Rule { return 2 } } - """), - Example(""" + """, + """ { if i > 0 { return 1 @@ -207,15 +207,15 @@ struct SuperfluousElseRule: Rule { return 2 } }() - """): Example(""" + """: """ { if i > 0 { return 1 } return 2 }() - """), - Example(""" + """, + """ for i in list { if i > 13 { return @@ -231,7 +231,7 @@ struct SuperfluousElseRule: Rule { } } - """): Example(""" + """: """ for i in list { if i > 13 { return @@ -248,8 +248,8 @@ struct SuperfluousElseRule: Rule { throw error } } - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/SwitchCaseAlignmentRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/SwitchCaseAlignmentRule.swift index 7f36f4f0de..28438fed29 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/SwitchCaseAlignmentRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/SwitchCaseAlignmentRule.swift @@ -105,16 +105,16 @@ extension SwitchCaseAlignmentRule { private var indentedCases: [Example] { let violationMarker = indentedCasesOption ? "" : violationMarker - return [ - Example(""" + return #examples([ + """ switch someBool { \(violationMarker)case true: print("red") \(violationMarker)case false: print("blue") } - """), - Example(""" + """, + """ if aBool { switch someBool { \(violationMarker)case true: @@ -123,8 +123,8 @@ extension SwitchCaseAlignmentRule { print('blue') } } - """), - Example(""" + """, + """ switch someInt { \(violationMarker)case 0: print('Zero') @@ -133,21 +133,21 @@ extension SwitchCaseAlignmentRule { \(violationMarker)default: print('Some other number') } - """), - Example(""" + """, + """ let a = switch i { \(violationMarker)case 1: 1 \(violationMarker)default: 2 } - """), - ] + """, + ]) } private var nonIndentedCases: [Example] { let violationMarker = indentedCasesOption ? violationMarker : "" - return [ - Example(""" + return #examples([ + """ switch someBool { \(violationMarker)case true: // case 1 print('red') @@ -162,8 +162,8 @@ extension SwitchCaseAlignmentRule { enum SomeEnum { case innocent } - """), - Example(""" + """, + """ if aBool { switch someBool { \(violationMarker)case true: @@ -172,8 +172,8 @@ extension SwitchCaseAlignmentRule { print('blue') } } - """), - Example(""" + """, + """ switch someInt { // comments ignored \(violationMarker)case 0: @@ -184,31 +184,31 @@ extension SwitchCaseAlignmentRule { \(violationMarker)default: print('Some other number') } - """), - Example(""" + """, + """ func f() -> Int { return switch i { \(violationMarker)case 1: 1 \(violationMarker)default: 2 } } - """), - ] + """, + ]) } private var invalidCases: [Example] { let indentation = indentedCasesOption ? " " : "" - return [ - Example(""" + return #examples([ + """ switch someBool { \(indentation)case true: \(indentation)print('red') \(indentation)\(violationMarker)case false: \(indentation)print('blue') } - """), - Example(""" + """, + """ if aBool { switch someBool { \(indentation)\(indentedCasesOption ? "" : violationMarker)case true: @@ -217,14 +217,14 @@ extension SwitchCaseAlignmentRule { \(indentation)print('blue') } } - """), - Example(""" + """, + """ let a = switch i { \(indentation)case 1: 1 \(indentation)\(indentedCasesOption ? "" : violationMarker)default: 2 } - """), - ] + """, + ]) } private var validOneLiners: [Example] = [ diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/TrailingCommaRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/TrailingCommaRule.swift index 47d3a6829d..4a9c4f258e 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/TrailingCommaRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/TrailingCommaRule.swift @@ -5,18 +5,18 @@ import SwiftSyntax struct TrailingCommaRule: Rule { var configuration = TrailingCommaConfiguration() - private static let triggeringExamples: [Example] = [ - Example("let foo = [1, 2, 3↓,]"), - Example("let foo = [1, 2, 3↓, ]"), - Example("let foo = [1, 2, 3 ↓,]"), - Example("let foo = [1: 2, 2: 3↓, ]"), - Example("struct Bar {\n let foo = [1: 2, 2: 3↓, ]\n}"), - Example("let foo = [1, 2, 3↓,] + [4, 5, 6↓,]"), - Example("let example = [ 1,\n2↓,\n // 3,\n]"), - Example("let foo = [\"אבג\", \"αβγ\", \"🇺🇸\"↓,]"), - Example("class C {\n #if true\n func f() {\n let foo = [1, 2, 3↓,]\n }\n #endif\n}"), - Example("foo([1: \"\\(error)\"↓,])"), - ] + private static let triggeringExamples: [Example] = #examples([ + "let foo = [1, 2, 3↓,]", + "let foo = [1, 2, 3↓, ]", + "let foo = [1, 2, 3 ↓,]", + "let foo = [1: 2, 2: 3↓, ]", + "struct Bar {\n let foo = [1: 2, 2: 3↓, ]\n}", + "let foo = [1, 2, 3↓,] + [4, 5, 6↓,]", + "let example = [ 1,\n2↓,\n // 3,\n]", + "let foo = [\"אבג\", \"αβγ\", \"🇺🇸\"↓,]", + "class C {\n #if true\n func f() {\n let foo = [1, 2, 3↓,]\n }\n #endif\n}", + "foo([1: \"\\(error)\"↓,])", + ]) private static let corrections: [Example: Example] = { let fixed = triggeringExamples.map { example -> Example in @@ -35,16 +35,16 @@ struct TrailingCommaRule: Rule { name: "Trailing Comma", description: "Trailing commas in arrays and dictionaries should be avoided/enforced.", kind: .style, - nonTriggeringExamples: [ - Example("let foo = [1, 2, 3]"), - Example("let foo = []"), - Example("let foo = [:]"), - Example("let foo = [1: 2, 2: 3]"), - Example("let foo = [Void]()"), - Example("let example = [ 1,\n 2\n // 3,\n]"), - Example("foo([1: \"\\(error)\"])"), - Example("let foo = [Int]()"), - ], + nonTriggeringExamples: #examples([ + "let foo = [1, 2, 3]", + "let foo = []", + "let foo = [:]", + "let foo = [1: 2, 2: 3]", + "let foo = [Void]()", + "let example = [ 1,\n 2\n // 3,\n]", + "foo([1: \"\\(error)\"])", + "let foo = [Int]()", + ]), triggeringExamples: Self.triggeringExamples, corrections: Self.corrections ) diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/TrailingNewlineRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/TrailingNewlineRule.swift index 2f249b5543..2464f225d2 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/TrailingNewlineRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/TrailingNewlineRule.swift @@ -26,18 +26,18 @@ struct TrailingNewlineRule: CorrectableRule, SourceKitFreeRule { name: "Trailing Newline", description: "Files should have a single trailing newline", kind: .style, - nonTriggeringExamples: [ - Example("let a = 0\n") - ], - triggeringExamples: [ - Example("let a = 0"), - Example("let a = 0\n\n"), - ].skipWrappingInCommentTests().skipWrappingInStringTests(), - corrections: [ - Example("let a = 0"): Example("let a = 0\n"), - Example("let b = 0\n\n"): Example("let b = 0\n"), - Example("let c = 0\n\n\n\n"): Example("let c = 0\n"), - ] + nonTriggeringExamples: #examples([ + "let a = 0\n" + ]), + triggeringExamples: #examples([ + "let a = 0", + "let a = 0\n\n", + ]).skipWrappingInCommentTests().skipWrappingInStringTests(), + corrections: #examplesDictionary([ + "let a = 0": "let a = 0\n", + "let b = 0\n\n": "let b = 0\n", + "let c = 0\n\n\n\n": "let c = 0\n", + ]) ) func validate(file: SwiftLintFile) -> [StyleViolation] { diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/TrailingWhitespaceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/TrailingWhitespaceRule.swift index c2d36e2947..8e967a18ef 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/TrailingWhitespaceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/TrailingWhitespaceRule.swift @@ -24,10 +24,10 @@ struct TrailingWhitespaceRule: Rule { Example("let codeWithSpace = 123↓ \n", configuration: ["ignores_literals": true], testWrappingInComment: false), ], - corrections: [ - Example("let name: String↓ \n"): Example("let name: String\n"), - Example("/* */ let name: String↓ \n"): Example("/* */ let name: String\n"), - ] + corrections: #examplesDictionary([ + "let name: String↓ \n": "let name: String\n", + "/* */ let name: String↓ \n": "/* */ let name: String\n", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/TypeContentsOrderRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/TypeContentsOrderRuleExamples.swift index 57186efc8b..1f9d694c58 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/TypeContentsOrderRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/TypeContentsOrderRuleExamples.swift @@ -122,20 +122,20 @@ internal struct TypeContentsOrderRuleExamples { """, ] - static let nonTriggeringExamples = [ - Example(""" + static let nonTriggeringExamples = #examples([ + """ class TestViewController: UIViewController { \(Self.defaultOrderParts.joined(separator: "\n\n")), } - """), - Example(""" + """, + """ struct ContentView: View { @available(SwiftUI_v5, *) // Availability macro syntax: https://github.com/swiftlang/swift/pull/65218 var v5Body: some View { EmptyView() } var body: some View { EmptyView() } } - """), - ] + """, + ]) static let triggeringExamples = [ Example(""" diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/UnneededParenthesesInClosureArgumentRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/UnneededParenthesesInClosureArgumentRule.swift index 1089af600e..6eadc3fce7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/UnneededParenthesesInClosureArgumentRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/UnneededParenthesesInClosureArgumentRule.swift @@ -61,16 +61,16 @@ struct UnneededParenthesesInClosureArgumentRule: Rule { } """, excludeFromDocumentation: true), ], - corrections: [ - Example("call(arg: { ↓(bar) in })"): Example("call(arg: { bar in })"), - Example("call(arg: { ↓(bar, _) in })"): Example("call(arg: { bar, _ in })"), - Example("call(arg: { ↓(bar, _)in })"): Example("call(arg: { bar, _ in })"), - Example("let foo = { ↓(bar) -> Bool in return true }"): - Example("let foo = { bar -> Bool in return true }"), - Example("method { ↓(foo, bar) in }"): Example("method { foo, bar in }"), - Example("foo.map { ($0, $0) }.forEach { ↓(x, y) in }"): Example("foo.map { ($0, $0) }.forEach { x, y in }"), - Example("foo.bar { [weak self] ↓(x, y) in }"): Example("foo.bar { [weak self] x, y in }"), - ] + corrections: #examplesDictionary([ + "call(arg: { ↓(bar) in })": "call(arg: { bar in })", + "call(arg: { ↓(bar, _) in })": "call(arg: { bar, _ in })", + "call(arg: { ↓(bar, _)in })": "call(arg: { bar, _ in })", + "let foo = { ↓(bar) -> Bool in return true }": + "let foo = { bar -> Bool in return true }", + "method { ↓(foo, bar) in }": "method { foo, bar in }", + "foo.map { ($0, $0) }.forEach { ↓(x, y) in }": "foo.map { ($0, $0) }.forEach { x, y in }", + "foo.bar { [weak self] ↓(x, y) in }": "foo.bar { [weak self] x, y in }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/UnusedOptionalBindingRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/UnusedOptionalBindingRule.swift index 66ea398deb..b1a231e9e4 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/UnusedOptionalBindingRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/UnusedOptionalBindingRule.swift @@ -9,25 +9,25 @@ struct UnusedOptionalBindingRule: Rule { name: "Unused Optional Binding", description: "Prefer `!= nil` over `let _ =`", kind: .style, - nonTriggeringExamples: [ - Example("if let bar = Foo.optionalValue {}"), - Example("if let (_, second) = getOptionalTuple() {}"), - Example("if let (_, asd, _) = getOptionalTuple(), let bar = Foo.optionalValue {}"), - Example("if foo() { let _ = bar() }"), - Example("if foo() { _ = bar() }"), - Example("if case .some(_) = self {}"), - Example("if let point = state.find({ _ in true }) {}"), - ], - triggeringExamples: [ - Example("if let ↓_ = Foo.optionalValue {}"), - Example("if let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {}"), - Example("guard let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {}"), - Example("if let (first, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {}"), - Example("if let (first, _) = getOptionalTuple(), let ↓_ = Foo.optionalValue {}"), - Example("if let (_, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {}"), - Example("if let ↓(_, _, _) = getOptionalTuple(), let bar = Foo.optionalValue {}"), - Example("func foo() { if let ↓_ = bar {} }"), - ] + nonTriggeringExamples: #examples([ + "if let bar = Foo.optionalValue {}", + "if let (_, second) = getOptionalTuple() {}", + "if let (_, asd, _) = getOptionalTuple(), let bar = Foo.optionalValue {}", + "if foo() { let _ = bar() }", + "if foo() { _ = bar() }", + "if case .some(_) = self {}", + "if let point = state.find({ _ in true }) {}", + ]), + triggeringExamples: #examples([ + "if let ↓_ = Foo.optionalValue {}", + "if let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {}", + "guard let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {}", + "if let (first, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {}", + "if let (first, _) = getOptionalTuple(), let ↓_ = Foo.optionalValue {}", + "if let (_, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {}", + "if let ↓(_, _, _) = getOptionalTuple(), let bar = Foo.optionalValue {}", + "func foo() { if let ↓_ = bar {} }", + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentOnCallRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentOnCallRule.swift index 589bb32ac1..4230fb6bc4 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentOnCallRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentOnCallRule.swift @@ -9,51 +9,51 @@ struct VerticalParameterAlignmentOnCallRule: Rule { name: "Vertical Parameter Alignment on Call", description: "Function parameters should be aligned vertically if they're in multiple lines in a method call", kind: .style, - nonTriggeringExamples: [ - Example(""" + nonTriggeringExamples: #examples([ + """ foo(param1: 1, param2: bar param3: false, param4: true) - """), - Example(""" + """, + """ foo(param1: 1, param2: bar) - """), - Example(""" + """, + """ foo(param1: 1, param2: bar param3: false, param4: true) - """), - Example(""" + """, + """ foo( param1: 1 ) { _ in } - """), - Example(""" + """, + """ UIView.animate(withDuration: 0.4, animations: { blurredImageView.alpha = 1 }, completion: { _ in self.hideLoading() }) - """), - Example(""" + """, + """ UIView.animate(withDuration: 0.4, animations: { blurredImageView.alpha = 1 }, completion: { _ in self.hideLoading() }) - """), - Example(""" + """, + """ UIView.animate(withDuration: 0.4, animations: { blurredImageView.alpha = 1 } { _ in self.hideLoading() } - """), - Example(""" + """, + """ foo(param1: 1, param2: { _ in }, param3: false, param4: true) - """), - Example(""" + """, + """ foo({ _ in bar() }, @@ -61,18 +61,18 @@ struct VerticalParameterAlignmentOnCallRule: Rule { baz() } ) - """), - Example(""" + """, + """ foo(param1: 1, param2: [ 0, 1 ], param3: 0) - """), - Example(""" + """, + """ myFunc(foo: 0, bar: baz == 0) - """), - Example(""" + """, + """ UIViewPropertyAnimator.runningPropertyAnimator( withDuration: 2.0, delay: 0.0, @@ -82,45 +82,45 @@ struct VerticalParameterAlignmentOnCallRule: Rule { } completion: { _ in // completion } - """), - ], - triggeringExamples: [ - Example(""" + """, + ]), + triggeringExamples: #examples([ + """ foo(param1: 1, param2: bar, ↓param3: false, param4: true) - """), - Example(""" + """, + """ foo(param1: 1, param2: bar, ↓param3: false, param4: true) - """), - Example(""" + """, + """ foo(param1: 1, param2: bar, ↓param3: false, ↓param4: true) - """), - Example(""" + """, + """ foo(param1: 1, ↓param2: { _ in }) - """), - Example(""" + """, + """ foo(param1: 1, param2: { _ in }, param3: 2, ↓param4: 0) - """), - Example(""" + """, + """ foo(param1: 1, param2: { _ in }, ↓param3: false, param4: true) - """), - Example(""" + """, + """ myFunc(foo: 0, ↓bar: baz == 0) - """), - Example(""" + """, + """ myFunc(foo: 0, bar: baz == 0, ↓baz: true) - """), - ] + """, + ]) ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentRuleExamples.swift index c8afa48101..1d0385b813 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalParameterAlignmentRuleExamples.swift @@ -1,97 +1,97 @@ internal struct VerticalParameterAlignmentRuleExamples { - static let nonTriggeringExamples: [Example] = [ - Example(""" + static let nonTriggeringExamples: [Example] = #examples([ + """ func validateFunction(_ file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) { } - """), - Example(""" + """, + """ func validateFunction(_ file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [StyleViolation] - """), - Example(""" + """, + """ func foo(bar: Int) - """), - Example(""" + """, + """ func foo(bar: Int) -> String - """), - Example(""" + """, + """ func validateFunction(_ file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [StyleViolation] - """), - Example(""" + """, + """ func validateFunction( _ file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [StyleViolation] - """), - Example(""" + """, + """ func validateFunction( _ file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary ) -> [StyleViolation] - """), - Example(""" + """, + """ func regex(_ pattern: String, options: NSRegularExpression.Options = [.anchorsMatchLines, .dotMatchesLineSeparators]) -> NSRegularExpression - """), - Example(""" + """, + """ func foo(a: Void, b: [String: String] = [:]) { } - """), - Example(""" + """, + """ func foo(data: (size: CGSize, identifier: String)) {} - """), - Example(""" + """, + """ func foo(data: Data, @ViewBuilder content: @escaping (Data.Element.IdentifiedValue) -> Content) {} - """), - Example(""" + """, + """ class A { init(bar: Int) } - """), - Example(""" + """, + """ class A { init(foo: Int, bar: String) } - """), - Example(""" + """, + """ func résuméBuilder(_ name: String, title: String, summary: String) -> String { return name } - """), - ] + """, + ]) - static let triggeringExamples: [Example] = [ - Example(""" + static let triggeringExamples: [Example] = #examples([ + """ func validateFunction(_ file: SwiftLintFile, kind: SwiftDeclarationKind, ↓dictionary: SourceKittenDictionary) { } - """), - Example(""" + """, + """ func validateFunction(_ file: SwiftLintFile, kind: SwiftDeclarationKind, ↓dictionary: SourceKittenDictionary) { } - """), - Example(""" + """, + """ func validateFunction(_ file: SwiftLintFile, ↓kind: SwiftDeclarationKind, ↓dictionary: SourceKittenDictionary) { } - """), - Example(""" + """, + """ func foo(data: Data, ↓@ViewBuilder content: @escaping (Data.Element.IdentifiedValue) -> Content) {} - """), - Example(""" + """, + """ class A { init(data: Data, ↓@ViewBuilder content: @escaping (Data.Element.IdentifiedValue) -> Content) {} } - """), - ] + """, + ]) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceOpeningBracesRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceOpeningBracesRule.swift index c0deffb9aa..71bac74739 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceOpeningBracesRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceOpeningBracesRule.swift @@ -11,11 +11,11 @@ private extension SwiftLintFile { struct VerticalWhitespaceOpeningBracesRule: Rule { var configuration = SeverityConfiguration(.warning) - private static let nonTriggeringExamples = [ - Example("[1, 2].map { $0 }.foo()"), - Example("[1, 2].map { $0 }.filter { num in true }"), - Example("// [1, 2].map { $0 }.filter { num in true }"), - Example(""" + private static let nonTriggeringExamples = #examples([ + "[1, 2].map { $0 }.foo()", + "[1, 2].map { $0 }.filter { num in true }", + "// [1, 2].map { $0 }.filter { num in true }", + """ /* class X { @@ -23,42 +23,42 @@ struct VerticalWhitespaceOpeningBracesRule: Rule { } */ - """), - ] + """, + ]) - private static let violatingToValidExamples: [Example: Example] = [ - Example(""" + private static let violatingToValidExamples: [Example: Example] = #examplesDictionary([ + """ if x == 5 { ↓ print("x is 5") } - """): Example(""" + """: """ if x == 5 { print("x is 5") } - """), - Example(""" + """, + """ if x == 5 { ↓ print("x is 5") } - """): Example(""" + """: """ if x == 5 { print("x is 5") } - """), - Example(""" + """, + """ struct MyStruct { ↓ let x = 5 } - """): Example(""" + """: """ struct MyStruct { let x = 5 } - """), - Example(""" + """, + """ class X { struct Y { ↓ @@ -66,77 +66,77 @@ struct VerticalWhitespaceOpeningBracesRule: Rule { } } } - """): Example(""" + """: """ class X { struct Y { class Z { } } } - """), - Example(""" + """, + """ [ ↓ 1, 2, 3 ] - """): Example(""" + """: """ [ 1, 2, 3 ] - """), - Example(""" + """, + """ foo( ↓ x: 5, y:6 ) - """): Example(""" + """: """ foo( x: 5, y:6 ) - """), - Example(""" + """, + """ func foo() { ↓ run(5) { x in print(x) } } - """): Example(""" + """: """ func foo() { run(5) { x in print(x) } } - """), - Example(""" + """, + """ KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil) { image, _, _, _ in ↓ guard let img = image else { return } } - """): Example(""" + """: """ KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil) { image, _, _, _ in guard let img = image else { return } } - """), - Example(""" + """, + """ foo({ }) { _ in ↓ self.dismiss(animated: false, completion: { }) } - """): Example(""" + """: """ foo({ }) { _ in self.dismiss(animated: false, completion: { }) } - """), - ] + """, + ]) private let pattern = "([{(\\[][ \\t]*(?:[^\\n{]+ in[ \\t]*$)?)((?:\\n[ \\t]*)+)(\\n)" } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceRule.swift index 6eccb01205..5ba5ba6903 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceRule.swift @@ -10,41 +10,41 @@ struct VerticalWhitespaceRule: Rule { name: "Vertical Whitespace", description: VerticalWhitespaceConfiguration.defaultDescriptionReason, kind: .style, - nonTriggeringExamples: [ - Example("let abc = 0\n"), - Example("let abc = 0\n\n"), - Example("/* bcs \n\n\n\n*/"), - Example("// bca \n\n"), - Example("class CCCC {\n \n}"), - Example(""" + nonTriggeringExamples: #examples([ + "let abc = 0\n", + "let abc = 0\n\n", + "/* bcs \n\n\n\n*/", + "// bca \n\n", + "class CCCC {\n \n}", + """ // comment import Foundation - """), - Example(""" + """, + """ // comment import Foundation - """), - ], - triggeringExamples: [ - Example("let aaaa = 0\n\n\n"), - Example("struct AAAA {}\n\n\n\n"), - Example("class BBBB {}\n\n\n"), - Example("class CCCC {\n \n \n}"), - Example(""" + """, + ]), + triggeringExamples: #examples([ + "let aaaa = 0\n\n\n", + "struct AAAA {}\n\n\n\n", + "class BBBB {}\n\n\n", + "class CCCC {\n \n \n}", + """ import Foundation - """), - ], - corrections: [ - Example("let b = 0\n\n\nclass AAA {}\n"): Example("let b = 0\n\nclass AAA {}\n"), - Example("let c = 0\n\n\nlet num = 1\n"): Example("let c = 0\n\nlet num = 1\n"), - Example("// bca \n\n\n"): Example("// bca \n\n"), - Example("class CCCC {\n \n \n \n}"): Example("class CCCC {\n \n}"), - ] // End of line autocorrections are handled by Trailing Newline Rule. + """, + ]), + corrections: #examplesDictionary([ + "let b = 0\n\n\nclass AAA {}\n": "let b = 0\n\nclass AAA {}\n", + "let c = 0\n\n\nlet num = 1\n": "let c = 0\n\nlet num = 1\n", + "// bca \n\n\n": "// bca \n\n", + "class CCCC {\n \n \n \n}": "class CCCC {\n \n}", + ]) // End of line autocorrections are handled by Trailing Newline Rule. ) } diff --git a/Source/SwiftLintBuiltInRules/Rules/Style/VoidReturnRule.swift b/Source/SwiftLintBuiltInRules/Rules/Style/VoidReturnRule.swift index 79981a7e14..4690b38938 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Style/VoidReturnRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Style/VoidReturnRule.swift @@ -11,43 +11,43 @@ struct VoidReturnRule: Rule { name: "Void Return", description: "Prefer `-> Void` over `-> ()`", kind: .style, - nonTriggeringExamples: [ - Example("let abc: () -> Void = {}"), - Example("let abc: () -> (VoidVoid) = {}"), - Example("func foo(completion: () -> Void)"), - Example("let foo: (ConfigurationTests) -> () throws -> Void"), - Example("let foo: (ConfigurationTests) -> () throws -> Void"), - Example("let foo: (ConfigurationTests) ->() throws -> Void"), - Example("let foo: (ConfigurationTests) -> () -> Void"), - Example("let foo: () -> () async -> Void"), - Example("let foo: () -> () async throws -> Void"), - Example("let foo: () -> () async -> Void"), - Example("func foo() -> () async throws -> Void {}"), - Example("func foo() async throws -> () async -> Void { return {} }"), - Example("func foo() -> () async -> Int { 1 }"), - ], - triggeringExamples: [ - Example("let abc: () -> ↓() = {}"), - Example("let abc: () -> ↓(Void) = {}"), - Example("let abc: () -> ↓( Void ) = {}"), - Example("func foo(completion: () -> ↓())"), - Example("func foo(completion: () -> ↓( ))"), - Example("func foo(completion: () -> ↓(Void))"), - Example("let foo: (ConfigurationTests) -> () throws -> ↓()"), - Example("func foo() async -> ↓()"), - Example("func foo() async throws -> ↓()"), - ], - corrections: [ - Example("let abc: () -> ↓() = {}"): Example("let abc: () -> Void = {}"), - Example("let abc: () -> ↓(Void) = {}"): Example("let abc: () -> Void = {}"), - Example("let abc: () -> ↓( Void ) = {}"): Example("let abc: () -> Void = {}"), - Example("func foo(completion: () -> ↓())"): Example("func foo(completion: () -> Void)"), - Example("func foo(completion: () -> ↓( ))"): Example("func foo(completion: () -> Void)"), - Example("func foo(completion: () -> ↓(Void))"): Example("func foo(completion: () -> Void)"), - Example("let foo: (ConfigurationTests) -> () throws -> ↓()"): - Example("let foo: (ConfigurationTests) -> () throws -> Void"), - Example("func foo() async throws -> ↓()"): Example("func foo() async throws -> Void"), - ] + nonTriggeringExamples: #examples([ + "let abc: () -> Void = {}", + "let abc: () -> (VoidVoid) = {}", + "func foo(completion: () -> Void)", + "let foo: (ConfigurationTests) -> () throws -> Void", + "let foo: (ConfigurationTests) -> () throws -> Void", + "let foo: (ConfigurationTests) ->() throws -> Void", + "let foo: (ConfigurationTests) -> () -> Void", + "let foo: () -> () async -> Void", + "let foo: () -> () async throws -> Void", + "let foo: () -> () async -> Void", + "func foo() -> () async throws -> Void {}", + "func foo() async throws -> () async -> Void { return {} }", + "func foo() -> () async -> Int { 1 }", + ]), + triggeringExamples: #examples([ + "let abc: () -> ↓() = {}", + "let abc: () -> ↓(Void) = {}", + "let abc: () -> ↓( Void ) = {}", + "func foo(completion: () -> ↓())", + "func foo(completion: () -> ↓( ))", + "func foo(completion: () -> ↓(Void))", + "let foo: (ConfigurationTests) -> () throws -> ↓()", + "func foo() async -> ↓()", + "func foo() async throws -> ↓()", + ]), + corrections: #examplesDictionary([ + "let abc: () -> ↓() = {}": "let abc: () -> Void = {}", + "let abc: () -> ↓(Void) = {}": "let abc: () -> Void = {}", + "let abc: () -> ↓( Void ) = {}": "let abc: () -> Void = {}", + "func foo(completion: () -> ↓())": "func foo(completion: () -> Void)", + "func foo(completion: () -> ↓( ))": "func foo(completion: () -> Void)", + "func foo(completion: () -> ↓(Void))": "func foo(completion: () -> Void)", + "let foo: (ConfigurationTests) -> () throws -> ↓()": + "let foo: (ConfigurationTests) -> () throws -> Void", + "func foo() async throws -> ↓()": "func foo() async throws -> Void", + ]) ) } diff --git a/Source/SwiftLintCore/Helpers/Macros.swift b/Source/SwiftLintCore/Helpers/Macros.swift index 3b683072c1..1d27c1b1e6 100644 --- a/Source/SwiftLintCore/Helpers/Macros.swift +++ b/Source/SwiftLintCore/Helpers/Macros.swift @@ -76,3 +76,31 @@ public macro SwiftSyntaxRule(foldExpressions: Bool = false, module: "SwiftLintCoreMacros", type: "SwiftSyntaxRule" ) + +/// Macro that expands an array of code strings into an array of ``Example``s, removing the per-element +/// `Example(...)` boilerplate. Each element is wrapped in an ``Example`` that captures the file and line of that +/// element, so test failures and rule documentation point at the right source location. Elements are usually +/// string literals, but any `String`-typed expression works. +/// +/// Use it for the common case where examples only carry code, e.g. +/// `nonTriggeringExamples: #examples(["let x = 1", "let y = 2"])`. Examples that need a custom configuration or +/// chained modifiers should keep using ``Example`` directly. +@freestanding(expression) +public macro examples(_ examples: [String]) -> [Example] = #externalMacro( + module: "SwiftLintCoreMacros", + type: "Examples" +) + +/// Macro that expands a dictionary of code strings into a dictionary of ``Example``s, removing the per-element +/// `Example(...)` boilerplate. Both the key and value of each pair are wrapped in an ``Example`` that captures the +/// file and line of the corresponding entry. Keys and values are usually string literals, but any `String`-typed +/// expression works. +/// +/// Use it for a rule's `corrections`, e.g. +/// `corrections: #examplesDictionary(["↓x": "y"])`. Pairs that need a custom configuration should keep using +/// ``Example`` directly. +@freestanding(expression) +public macro examplesDictionary(_ examples: [String: String]) -> [Example: Example] = #externalMacro( + module: "SwiftLintCoreMacros", + type: "ExamplesDictionary" +) diff --git a/Source/SwiftLintCore/Models/RuleDescription.swift b/Source/SwiftLintCore/Models/RuleDescription.swift index 4139f38f38..92c9f356c8 100644 --- a/Source/SwiftLintCore/Models/RuleDescription.swift +++ b/Source/SwiftLintCore/Models/RuleDescription.swift @@ -84,9 +84,9 @@ public struct RuleDescription: Equatable, Sendable { /// - parameter description: Sets the description's `description` property. /// - parameter kind: Sets the description's `kind` property. /// - parameter minSwiftVersion: Sets the description's `minSwiftVersion` property. - /// - parameter nonTriggeringExamples: Sets the description's `nonTriggeringExamples` property. - /// - parameter triggeringExamples: Sets the description's `triggeringExamples` property. - /// - parameter corrections: Sets the description's `corrections` property. + /// - parameter nonTriggeringExamples: Sets the description's `nonTriggeringExamples` property. Use the `#examples([...])` macro to turn an array of strings into an array of `Example`s. + /// - parameter triggeringExamples: Sets the description's `triggeringExamples` property. Use the `#examples([...])` macro to turn an array of strings into an array of `Example`s. + /// - parameter corrections: Sets the description's `corrections` property. Use the `#examplesDictionary([...])` macro to turn a `[String: String]` dictionary into an `[Example: Example]` dictionary. /// - parameter deprecatedAliases: Sets the description's `deprecatedAliases` property. /// - parameter requiresFileOnDisk: Sets the description's `requiresFileOnDisk` property. public init(identifier: String, diff --git a/Source/SwiftLintCoreMacros/Examples.swift b/Source/SwiftLintCoreMacros/Examples.swift new file mode 100644 index 0000000000..f0b4058a99 --- /dev/null +++ b/Source/SwiftLintCoreMacros/Examples.swift @@ -0,0 +1,78 @@ +import SwiftSyntax +import SwiftSyntaxBuilder +import SwiftSyntaxMacros + +/// Expands `#examples(["a", "b"])` into `[Example("a", file:, line:), Example("b", file:, line:)]`, capturing +/// the file and line of each element so test failures and documentation point at the right location. Elements are +/// usually string literals, but any `String`-typed expression works. +enum Examples: ExpressionMacro { + static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) -> ExprSyntax { + guard let array = node.arguments.first?.expression.as(ArrayExprSyntax.self) else { + context.diagnose(SwiftLintCoreMacroError.examplesNotArrayLiteral.diagnose(at: node)) + return "[]" + } + // Rewrite the original array in place (rather than building a fresh one) so the expansion keeps the + // source's brackets and per-element newlines, making it readable when a developer expands the macro. + let newElements = array.elements.map { element in + element.with( + \.expression, + makeExample(from: element.expression, in: context, preservingTriviaOf: element.expression) + ) + } + return ExprSyntax(array.with(\.elements, ArrayElementListSyntax(newElements))) + } +} + +/// Expands `#examplesDictionary(["a": "b"])` into `[Example("a", …): Example("b", …)]`, capturing the file and +/// line of each key and value. Keys and values are usually string literals, but any `String`-typed expression +/// works. Intended for a rule's `corrections` dictionary. +enum ExamplesDictionary: ExpressionMacro { + static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) -> ExprSyntax { + guard let dictionary = node.arguments.first?.expression.as(DictionaryExprSyntax.self) else { + context.diagnose(SwiftLintCoreMacroError.examplesNotDictionaryLiteral.diagnose(at: node)) + return "[:]" + } + guard case let .elements(elements) = dictionary.content else { + return "[:]" + } + let newElements = elements.map { element in + element + .with(\.key, makeExample(from: element.key, in: context, preservingTriviaOf: element.key)) + .with(\.value, makeExample(from: element.value, in: context, preservingTriviaOf: element.value)) + } + return ExprSyntax(dictionary.with(\.content, .elements(DictionaryElementListSyntax(newElements)))) + } +} + +/// Wraps a string expression in an `Example(…, file:, line:)` call, baking in the expression's own source +/// location. (It is usually a string literal, but any `String`-typed expression works.) Its surrounding trivia is +/// replaced with the trivia of `triviaSource` (the original node being substituted), so the result slots into the +/// same position as the expression it replaces. +private func makeExample( + from expression: ExprSyntax, + in context: some MacroExpansionContext, + preservingTriviaOf triviaSource: ExprSyntax? = nil +) -> ExprSyntax { + let code = expression.trimmed + let example: ExprSyntax = if let fileID = context.location( + of: expression, at: .afterLeadingTrivia, filePathMode: .fileID + ), let filePath = context.location( + of: expression, at: .afterLeadingTrivia, filePathMode: .filePath + ) { + "Example(\(code), fileID: \(fileID.file), file: \(filePath.file), line: \(filePath.line))" + } else { + "Example(\(code))" + } + guard let triviaSource else { + return example + } + return example + .with(\.leadingTrivia, triviaSource.leadingTrivia) + .with(\.trailingTrivia, triviaSource.trailingTrivia) +} diff --git a/Source/SwiftLintCoreMacros/SwiftLintCoreMacroError.swift b/Source/SwiftLintCoreMacros/SwiftLintCoreMacroError.swift index 5402bd6b9d..e8258b7f70 100644 --- a/Source/SwiftLintCoreMacros/SwiftLintCoreMacroError.swift +++ b/Source/SwiftLintCoreMacros/SwiftLintCoreMacroError.swift @@ -12,6 +12,8 @@ enum SwiftLintCoreMacroError: String, DiagnosticMessage { case noBooleanLiteral = "Macro argument must be a boolean literal" case noBody = "Macro can only be applied to functions with a body" case missingPathArgument = "Missing required 'path' argument" + case examplesNotArrayLiteral = "Macro argument must be an array literal" + case examplesNotDictionaryLiteral = "Macro argument must be a dictionary literal" var message: String { rawValue diff --git a/Source/SwiftLintCoreMacros/SwiftLintCoreMacros.swift b/Source/SwiftLintCoreMacros/SwiftLintCoreMacros.swift index 3447344d84..83f595ca45 100644 --- a/Source/SwiftLintCoreMacros/SwiftLintCoreMacros.swift +++ b/Source/SwiftLintCoreMacros/SwiftLintCoreMacros.swift @@ -9,6 +9,8 @@ struct SwiftLintCoreMacros: CompilerPlugin { AutoConfigParser.self, AcceptableByConfigurationElement.self, DisabledWithoutSourceKit.self, + Examples.self, + ExamplesDictionary.self, SwiftSyntaxRule.self, ] } diff --git a/Tests/MacroTests/ExamplesTests.swift b/Tests/MacroTests/ExamplesTests.swift new file mode 100644 index 0000000000..7e013357f5 --- /dev/null +++ b/Tests/MacroTests/ExamplesTests.swift @@ -0,0 +1,192 @@ +import SwiftSyntaxMacroExpansion +import SwiftSyntaxMacrosGenericTestSupport +import Testing + +@testable import SwiftLintCoreMacros + +private let macros = [ + "examples": MacroSpec(type: Examples.self), + "examplesDictionary": MacroSpec(type: ExamplesDictionary.self), +] + +@Suite +struct ExamplesTests { + @Test + func expandsExamplesCapturingLines() { + assertMacroExpansion( + #""" + #examples([ + "let x = 1", + """ + func f() {} + """, + ]) + """#, + expandedSource: #""" + [ + Example("let x = 1", fileID: "TestModule/test.swift", file: "test.swift", line: 2), + Example(""" + func f() {} + """, fileID: "TestModule/test.swift", file: "test.swift", line: 3), + ] + """#, + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + } + + @Test + func preservesArrayNewlines() { + // Each element stays on its own line in the expansion so it is readable when expanded. + assertMacroExpansion( + """ + #examples([ + "a", + "b", + "c", + ]) + """, + expandedSource: """ + [ + Example("a", fileID: "TestModule/test.swift", file: "test.swift", line: 2), + Example("b", fileID: "TestModule/test.swift", file: "test.swift", line: 3), + Example("c", fileID: "TestModule/test.swift", file: "test.swift", line: 4), + ] + """, + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + } + + @Test + func expandsEmptyArray() { + assertMacroExpansion( + """ + #examples([]) + """, + expandedSource: """ + [] + """, + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + } + + @Test + func nonArrayLiteralArgument() { + assertMacroExpansion( + """ + #examples(someExamples) + """, + expandedSource: """ + [] + """, + diagnostics: [ + DiagnosticSpec(message: SwiftLintCoreMacroError.examplesNotArrayLiteral.message, line: 1, column: 1) + ], + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + } + + @Test + func expandsDictionaryCapturingLines() { + // swiftlint:disable line_length + assertMacroExpansion( + """ + #examplesDictionary([ + "↓x": "y", + "↓a": "b", + ]) + """, + expandedSource: """ + [ + Example("↓x", fileID: "TestModule/test.swift", file: "test.swift", line: 2): Example("y", fileID: "TestModule/test.swift", file: "test.swift", line: 2), + Example("↓a", fileID: "TestModule/test.swift", file: "test.swift", line: 3): Example("b", fileID: "TestModule/test.swift", file: "test.swift", line: 3), + ] + """, + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + // swiftlint:enable line_length + } + + @Test + func expandsEmptyDictionary() { + assertMacroExpansion( + """ + #examplesDictionary([:]) + """, + expandedSource: """ + [:] + """, + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + } + + @Test + func nonDictionaryLiteralArgument() { + assertMacroExpansion( + """ + #examplesDictionary(someDictionary) + """, + expandedSource: """ + [:] + """, + diagnostics: [ + DiagnosticSpec( + message: SwiftLintCoreMacroError.examplesNotDictionaryLiteral.message, + line: 1, + column: 1 + ), + ], + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + } + + @Test + func expandsNonLiteralExamples() { + // Elements need not be string literals; any `String`-typed expression is wrapped as-is. + assertMacroExpansion( + """ + #examples([ + code, + makeCode(for: rule), + ]) + """, + expandedSource: """ + [ + Example(code, fileID: "TestModule/test.swift", file: "test.swift", line: 2), + Example(makeCode(for: rule), fileID: "TestModule/test.swift", file: "test.swift", line: 3), + ] + """, + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + } + + @Test + func expandsNonLiteralDictionary() { + // Keys and values need not be string literals; any `String`-typed expression is wrapped as-is. + // swiftlint:disable line_length + assertMacroExpansion( + """ + #examplesDictionary([ + trigger: corrected, + makeCode(for: rule): fixed + suffix, + ]) + """, + expandedSource: """ + [ + Example(trigger, fileID: "TestModule/test.swift", file: "test.swift", line: 2): Example(corrected, fileID: "TestModule/test.swift", file: "test.swift", line: 2), + Example(makeCode(for: rule), fileID: "TestModule/test.swift", file: "test.swift", line: 3): Example(fixed + suffix, fileID: "TestModule/test.swift", file: "test.swift", line: 3), + ] + """, + macroSpecs: macros, + failureHandler: FailureHandler.instance + ) + // swiftlint:enable line_length + } +}